【问题标题】:Validating input with while loop and scanner使用 while 循环和扫描器验证输入
【发布时间】:2013-03-03 06:23:50
【问题描述】:

从用户那里获取指定范围 (0,20) 并且是int 的有效整数的最佳方法是什么?如果他们输入无效的整数,则打印出错误。

我在想这样的事情:

 int choice = -1;
 while(!scanner.hasNextInt() || choice < 0 || choice > 20) {
       System.out.println("Error");
       scanner.next(); //clear the buffer
 }
 choice = scanner.nextInt();

这是正确的还是有更好的方法?

【问题讨论】:

  • 这段代码是否符合您的预期?如果是,那么您的问题是什么,如果不是,那么错误是什么?
  • 即使我输入了一个在范围内的数字,它只会不断打印错误

标签: java input while-loop java.util.scanner validating


【解决方案1】:

在 while 循环中,您在哪里更改选择?如果它没有改变,你不能期望在你的 if 块的布尔条件中使用它。

您必须检查 Scanner 没有 int,如果它确实有 int,请选择并单独检查。

伪代码:

set choice to -1
while choice still -1
  check if scanner has int available
    if so, get next int from scanner and put into temp value
    check temp value in bounds
    if so, set choice else error
  else error message and get next scanner token and discard
done while

【讨论】:

    【解决方案2】:

    你可以这样做:

    Scanner sc = new Scanner(System.in);
    int number;
    do {
        System.out.println("Please enter a valid number: ");
        while (!sc.hasNextInt()) {
           System.out.println("Error. Please enter a valid number: ");
           sc.next(); 
        }
        number = sc.nextInt();
    } while (!checkChoice(number));
    
    private static boolean checkChoice(int choice){
        if (choice <MIN || choice > MAX) {     //Where MIN = 0 and MAX = 20
            System.out.print("Error. ");
            return false;
        }
        return true;
    }
    

    这个程序会一直要求输入,直到它得到一个有效的输入。

    确保您了解程序的每一步..

    【讨论】:

    • 我刚试过这个,如果第一次选择不是 int,它会抛出 InputMismathException。
    猜你喜欢
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    相关资源
    最近更新 更多