Why does this while loop work?

匿名 (未验证) 提交于 2019-12-03 00:56:02

问题:

Why does this work:

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(); 

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?

回答1:

keyboard.hasNextInt() 

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

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.



回答2:

As long as you don't enter a valid integer value, the Scanner.hasNextInt() does not return a true. Since the negation of hasNextInt() is being checked at the while condition - it prints "Make sure you enter an integer." until an Integer value is entered.

Hope this helps Scanner.hasNextInt()



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!