如何在java中允许越界索引

s71maibg  于 2021-07-08  发布在  Java
关注(0)|答案(6)|浏览(325)

我试着编写程序,这样用户就可以输入月份的整数(例如,当用户输入数字4时,输出应该是4月份),并且它会一直询问用户输入的有效数字(1-12)。如果用户输入了一个无效的数字,程序应该说“invalid!”,然后终止。但是,我的程序无法执行while循环并立即将无效数字设置为异常。我该怎么做才能使程序显示“无效!”?谢谢!

String[] months = new String[] {"January", "February", "March", "April", "May", "June", "July", "August", "September", "Oktober", "November", "December"};
    Scanner input = new Scanner(System.in);

    int i = 1;
    while(i < 13 && i > 0)
    {

        if(i > 12 && i < 1)
        {
            break;
        }
        else
        {
            System.out.println("Month?");
            i = input.nextInt();
            System.out.println(months[i - 1] + "\n");
        }
    }
    System.out.println("Invalid!");
to94eoyn

to94eoyn1#

您使用相同的i变量进行数组索引,这也是为什么您会收到异常,因为在退出while循环输入无效输入之前 System.out.println(months[i - 1] + "\n"); 如果数组索引中的值 months[value] 大于您将收到的异常数组大小 ArrayIndexOutBoundsException 如果索引值小于0
为了避免这种情况,只需添加 if(i>12 || i<1) break; 输入语句之后 i = input.nextInt(); ```
System.out.println("Month?");
i = input.nextInt();
if(i>12 || i<1)
break;
System.out.println(months[i - 1] + "\n");

因此,输入大于12或小于1的数字后,while循环将中断

System.out.println("Invalid!");

将执行
y1aodyip

y1aodyip2#

您应该检查数组绑定是否在0到months.length-1之间,因为数组索引从0开始。应该避免捕捉indexoutofbounds,这表示代码有问题,而不是。

i = input.nextInt();
        if(i-1 < 0 || i-1 >= months.length)
        {
            break;
        }
        else
        {
            System.out.println(months[i - 1] + "\n");
        }
laximzn5

laximzn53#

你有两个选择。
将数组访问 Package 到try-catch块中并捕获异常,然后打印“invalid”。
您必须遵循以下原则:首先请求输入,然后检查是否满足约束,并且只有满足约束时,才能访问数组。然后继续在循环中执行此操作,直到不再满足约束(更好的选择)
考虑选项2的这个例子:

public static void main(String[] args) {
    String[] months = new String[] { "January", "February", "March", "April", "May", "June", "July", "August", "September",
            "Oktober", "November", "December" };
    Scanner input = new Scanner(System.in);
    System.out.println("Month?");
    int i = input.nextInt();

    while (i < 13 && i > 0) {
        System.out.println(months[i - 1] + "\n");
        System.out.println("Month?");
        i = input.nextInt();
    }
    System.out.println("Invalid!");
}

不需要if子句和break,因为while循环完成了所有的工作。

qni6mghb

qni6mghb4#

if条件总是false,因为数字不能同时大于12和i<1。使用 i > 12 || i < 1 相反。
访问数组时会发生异常,因此可以先读取下一个数字,然后进行检查,只有在数字有效时才能访问数组。
(最低限度)更正后的清单为:

String[] months = new String[] {"January", "February", "March", "April", "May", "June", "July", "August", "September", "Oktober", "November", "December"};
        Scanner input = new Scanner(System.in);

        int i = 1;
        while(i < 13 && i > 0)
        {

            System.out.println("Month?");
            i = input.nextInt();
            if(i > 12 || i < 1)
            {
                break;
            }
            else
            {
                System.out.println(months[i - 1] + "\n");
            }
        }
        System.out.println("Invalid!");
4ngedf3f

4ngedf3f5#

您可以使用无限循环(即。 while(true){} )把它弄断以备不时之需 InputMismatchException 或输入整数超出有效范围(即。 112 ).

import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String[] months = new String[] { "January", "February", "March", "April", "May", "June", "July", "August",
                "September", "Oktober", "November", "December" };
        Scanner input = new Scanner(System.in);
        int i;
        while (true) {
            System.out.print("Month?");
            try {
                i = input.nextInt();
                if (i >= 1 && i <= 12) {
                    System.out.println(months[i - 1]);
                } else {
                    System.out.println("Invalid");
                    break;
                }
            } catch (InputMismatchException e) {
                System.out.println("Invalid");
                break;
            }
        }
    }
}

示例运行:

Month?10
Oktober
Month?1
January
Month?15
Invalid

另一个示例运行:

Month?12
December
Month?1
January
Month?abc
Invalid

通过使用java.time api:

import java.time.DateTimeException;
import java.time.Month;
import java.time.format.TextStyle;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while (true) {
            System.out.print("Month?");
            try {
                Month month = Month.of(input.nextInt());
                // Change the locale as per your requirement e.g. Locale.ENGLISH
                System.out.println(month.getDisplayName(TextStyle.FULL, Locale.GERMAN));
            } catch (DateTimeException | InputMismatchException e) {
                System.out.println("Invalid");
                break;
            }
        }
    }
}

示例运行:

Month?10
Oktober
Month?1
Januar
Month?15
Invalid

另一个示例运行:

Month?10
Oktober
Month?1
Januar
Month?Abc
Invalid
ckocjqey

ckocjqey6#

你应该试试this:------
(如果你不想破坏循环)

public static void main(String[] args) {
        String[] months = new String[] { "January", "February", "March", "April", "May", "June", "July", "August",
                "September", "Oktober", "November", "December" };
        Scanner input = new Scanner(System.in);
        while (true) {
            try {
                System.out.println("Month?");
                int inputFromUser = input.nextInt();

                if (inputFromUser < 13 && inputFromUser > 0)

                {
                    System.out.println(months[inputFromUser - 1]);
                } else {
                    System.out.println("Invalid! input");
                    System.out.println("Do you want to come out from loop yes/no");
                    if (input.next().equalsIgnoreCase("yes")) {
                        break;
                    }
                }
            } catch (InputMismatchException e) {
                System.out.println("Invalid! input , please provide the correct integer input");
                break;
            }
        }
        input.close();
    }

如果你是ohk打破循环,然后尝试下面logic:--
首先使用“if”检查输入,然后应用while循环。

相关问题