【问题标题】:Java Scanner if/else and while statements [duplicate]Java Scanner if/else 和 while 语句 [重复]
【发布时间】:2014-11-21 21:38:21
【问题描述】:

我正在尝试制作一个接收用户输入的程序,然后稍后在程序中使用该程序。我的问题是例外。例如,如果我只希望用户输入一个介于 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

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

【问题讨论】:

  • 你必须建立自己的异常类吗?或者你可以简单地抛出一个新的异常吗?
  • 我认为有一个误解,我的意思是 if/else 或 while 语句不会让用户输入不符合条件的值。我的英语不是最好的,所以对此我深表歉意。
  • 所以你不想抛出异常,而是只想循环直到用户输入正确的条件?
  • 这个数组真的没必要..

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


【解决方案1】:

我认为您不需要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);

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2015-12-28
      • 2012-06-18
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-08
      • 2014-11-29
      • 2015-10-19
      相关资源
      最近更新 更多