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()的求反,因此它会打印“确保输入整数”,直到输入整数值
希望这有帮助
一个建议:我认为一些额外的信息会给出更好的答案。。。我认为仅仅提供一个链接更适合发表评论