Java Scanner if / else和while语句

时间:2014-11-21 21:38:22

标签: java arrays if-statement java.util.scanner

我正在尝试创建一个接收用户输入的程序,然后在程序中使用。我遇到的问题是例外。例如,如果我只希望用户输入介于0和之前放入的数字之间的数字。这是一个例子:

    Scanner input = new Scanner(System.in); 
    System.out.println("What length do you want your array to be?");
    int length = input.nextInt(); 
    int[] arr = full(length);
    print(arr);
    System.out.println();
    System.out.println("Write a number between (0-"+length+"):");//Its here I want to add an exception.
    int number = input.nextInt();                       //if the user types in a greater value
    check(arr,number);                                  //of "length" or smaller value than 0
                                                        //I want the question to repeat itself
                                                        //until the criteria is met

您不必担心“检查”或“打印方法。”

2 个答案:

答案 0 :(得分:2)

您不需要例外,只需添加一个do-while循环来检查它是否是有效条目。

// ...

do
{
    System.out.println("Write a number between (0-"+length+"):");
    int number = input.nextInt();
} while( number < 0 || number >= length ); 

注意:我将条件更改为不包括length,因为看起来您将使用它作为数组的索引,并且length不是长度为{的数组中的有效索引{1}}。

答案 1 :(得分:2)

我不相信你需要一个Exception,只是一个循环。像do-while循环,如

int number;
do {
    System.out.println("Write a number between (0-" + length + "):");
    number = input.nextInt();
    if (number < 0) {
        System.out.printf("%d is too low%n", number);
    } else if (number > length) {
        System.out.printf("%d is too high%n", number);
    }
} while (number < 0 || number > length);
check(arr, number);