2013-10-07 110 views
0

该程序应该从用户的单个输入中接收四个整数(例如1 2 3 42)。我正在尝试编写一些代码来检查输入是否全是整数。如何验证单个输入行是否只有整数?

然而,即使输入是像1 2 B,它不进入while循环,我想不通为什么。任何帮助,将不胜感激。

Scanner scan = new Scanner(System.in);  
System.out.print("Please list at least one and up to 10 integers: "); 
scan.hasNextInt(); 

    while(!scan.hasNextInt()) 
     { 
      System.out.println("One or more of your inputs was not an integer. Please input only integers: "); 
      scan.next(); 
     } 
+0

我强烈建议你通过这个步骤与调试器。你会立刻看到你的错误是什么。 –

回答

1

你没有被读下intScanner进展。

尝试用输入1 a b使用下面的代码:

scan.hasNextInt(); 
scan.nextInt(); // or scan.next() to read next integer 
    while(!scan.hasNextInt()) 
     { 
      System.out.println("One or more of your inputs was not an integer. Please input only integers: "); 
      scan.next(); 
     } 

它会打印:

一个或多个输入项是不是整数。请输入只有 整数:

仅整数:一个或多个输入项是不是整数。请输入

+0

这确实有帮助,但我不明白为什么println在用户再次输入前迭代两次,为什么? –

+0

读取第一1之后,下一个标记是'A',其是非整数,在''TRUE'循环while'结果的条件,所以打印的第一行,然后执行'scan.next()'。现在进行第二次迭代,它看到'b'是非整数,'while'条件再次成立。所以它进入内部,再次打印并尝试阅读'next()'。但没有什么可读的。 – Sage

相关问题