使用while循环和扫描仪验证输入

时间:2013-03-03 06:23:50

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

从指定范围(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();

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

2 个答案:

答案 0 :(得分:1)

您可以这样做:

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;
}

该程序将继续询问输入,直到获得有效输入。

确保您了解该计划的每一步......

答案 1 :(得分:1)

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

您必须检查扫描程序没有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