Scanner hasNextInt() return true if hasNextInt() has nothing

人盡茶涼 提交于 2019-12-11 06:18:30

问题


After reading the hasNextInt() API, I'm still at a lost at this code.

Scanner input = new Scanner(System.in);
while (input.hasNextInt()) {
    input.next();
}

Why does the loop start even though input has nothing. Also, the hasNextInt() API mentions

The scanner does not advance past any input.

What does that mean? And does that have anything to do with it?


回答1:


Scanner input = new Scanner(System.in) is not a blocking call, it's just creating a new Scanner with STDIN as input. Thus execution proceeds to the while loop.

From the API documents at Oracle - Scanner (Java Platform SE 7)

Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.

Scanner waits (input.hasNextInt() at this moment is actually a blocking call) for the user to input something and press Enter.

Then on the input.next() call, it actually reads the input(consumes it) and advances the read position.

However, if you type something like 12 hello as input in a terminal or console, this will cause the while loop to loop once and then exit. The reason for this is that hasNextInt() reads until the first whitespace and checks if the characters up to the whitespace are a valid int. In this case they are and hasNextInt() returns true. Then, on the second iteration of the loop, it encounters a String, thus hasNextInt() returns false, which causes the loop to end.



来源:https://stackoverflow.com/questions/38024861/scanner-hasnextint-return-true-if-hasnextint-has-nothing

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