Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么这个while循环有效?_Java_While Loop - Fatal编程技术网

Java 为什么这个while循环有效?

Java 为什么这个while循环有效?,java,while-loop,Java,While Loop,为什么这样做有效: Scanner keyboard = new Scanner(System.in); int i; int beerBottles = 100; //Asks the user for the number of beer bottles on the wall System.out.println("How many bottles of beer are on the wall?"); while (!keyboard.hasNextInt()) { System.o

为什么这样做有效:

Scanner keyboard = new Scanner(System.in);
int i;
int beerBottles = 100;

//Asks the user for the number of beer bottles on the wall
System.out.println("How many bottles of beer are on the wall?");

while (!keyboard.hasNextInt())
{
System.out.println("Make sure you enter an integer.");
keyboard.next();
}
//Sets beerBottles to the user entered value
beerBottles = keyboard.nextInt();
我在尝试确保用户输入是一个整数而不使用try/catch时偶然发现了这一点,我不知道它为什么有效,也不知道是否有我遗漏的可怕错误。它似乎工作完美,这将是伟大的,但我不明白为什么“确保您输入一个整数”文本并不总是显示。有人能解释一下吗

keyboard.hasNextInt()
块,直到它有要检查的输入。如果找到整数值,则返回
true
,否则返回false


因此,如果输入整数值,则永远不会输入
while
循环。如果未输入,则循环中的
键盘.next()
将清除您输入的值以允许您重试。

只要您未输入有效的整数值,Scanner.hasNextInt()将不会返回true。由于在while条件下检查hasNextInt()的求反,因此它会打印“确保输入整数”,直到输入整数值

希望这有帮助

一个建议:我认为一些额外的信息会给出更好的答案。。。我认为仅仅提供一个链接更适合发表评论