扫描仪使用nextInt()和循环继续跳过输入

我正在使用while循环来确保输入到scanner对象的值是一个整数,如下所示:

while (!capacityCheck) { try { System.out.println("Capacity"); capacity = scan.nextInt(); capacityCheck = true; } catch (InputMismatchException e) { System.out.println("Capacity must be an integer"); } } 

但是,如果用户没有输入一个整数,当它应该返回并接受另一个输入时,它只是重复打印“容量”,然后输入捕获中的输出而不需要更多输入。 我怎么阻止这个?

 scan.nextLine(); 

将这段代码放在catch块中,在你输入错误的情况下,使用非整数字符以及保留在缓冲区中的新行字符(因此,无限地打印catch sysout)。

当然,还有其他更简洁的方法来实现你想要的,但我想这需要你的代码中的一些重构。

使用以下内容:

 while (!capacityCheck) { System.out.println("Capacity"); String input = scan.nextLine(); try { capacity = Integer.parseInt(input ); capacityCheck = true; } catch (NumberFormatException e) { System.out.println("Capacity must be an integer"); } } 

尝试这个 :

 while (!capacityCheck) { try { System.out.println("Capacity"); capacity = scan.nextInt(); capacityCheck = true; } catch (InputMismatchException e) { System.out.println("Capacity must be an integer"); scan.nextLine(); } } 

试着把它放在循环的末尾 –

 scan.nextLine(); 

或者更好地把它放在catch块中。

  while (!capacityCheck) { try { System.out.println("Capacity"); capacity = scan.nextInt(); capacityCheck = true; } catch (InputMismatchException e) { System.out.println("Capacity must be an integer"); scan.nextLine(); } } 

我认为不需要try / catch或capacityCheck因为我们可以访问方法hasNextInt() – 它检查下一个标记是否为int。 例如,这应该做你想要的:

  while (!scan.hasNextInt()) { //as long as the next is not a int - say you need to input an int and move forward to the next token. System.out.println("Capacity must be an integer"); scan.next(); } capacity = scan.nextInt(); //scan.hasNextInt() returned true in the while-clause so this will be valid.