为什么这个while循环有效? [英] Why does this while loop work?

查看:39
本文介绍了为什么这个while循环有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这样做:

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 时偶然发现了这一点,我不知道它为什么会起作用,或者我是否遗漏了一些可怕的错误.它似乎工作得很好,这很好,但我不明白为什么确保输入整数"文本并不总是显示.谁能解释一下?

I stumbled on this while trying to make sure that the user input was an integer without using try/catch and I have no idea why it works or if something is horrendously wrong that I'm missing. It seems to work perfectly, which would be great, but I don't understand why the "Make sure you enter an integer" text doesn't always show. Can anyone explain?

推荐答案

keyboard.hasNextInt()

阻塞直到它有输入要检查.当它找到时,如果找到整数值,则返回 true,否则返回 false.

blocks until it has input to examine. When it does, it returns true if it finds an integer value, and false otherwise.

因此,如果您输入整数值,则永远不会进入 while 循环.如果没有,循环内的 keyboard.next() 会清除您输入的值,让您重试.

Therefore, if you enter an integer value, the while loop is never entered. If you didn't, the keyboard.next() inside the loop clears the value you entered to let you try again.

这篇关于为什么这个while循环有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆