使用while循环和扫描仪validation输入

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

我想的是:

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

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

你在哪里改变你的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 

你可以这样做:

 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  MAX) { //Where MIN = 0 and MAX = 20 System.out.print("Error. "); return false; } return true; } 

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

确保你了解该计划的每一步……