Davidh3
Davidh3

Reputation: 15

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

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?

Upvotes: 1

Views: 1319

Answers (1)

printfmyname
printfmyname

Reputation: 971

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.

Upvotes: 1

Related Questions