Garmin
Garmin

Reputation: 13

Why can I only input data from the keyboard once when I call hasNext() twice in a row?

When my code is like below:

Scanner sc = new Scanner(System.in);
     System.out.println(sc.hasNext());
     System.out.println(sc.hasNext());

and I input 1, the following is what's printed in the console

1 // input 1
true
true

But when I add a System.out.println("str -> " + sc.next()); after calling the first println(), like this:

System.out.println(sc.hasNext());
System.out.println("str -> " + sc.next());
System.out.println(sc.hasNext());

I also input a 1, what's printed in the console has changed like this:

1 // input 1
true
str -> 1
1 //input 1
true

Why can I input 1 twice when I add a System.out.println("str -> " + sc.next()); after calling the first println()?

Upvotes: 0

Views: 65

Answers (2)

Akhil Surapuram
Akhil Surapuram

Reputation: 682

From Java Documentation

java.util.Scanner

public boolean hasNext()

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.

First Input has been taken form hasNext method. since has next called without any input

Second Input has been taken from next method.

Hope this clarifies your question.

Upvotes: 0

a guest
a guest

Reputation: 472

You can call hasNext() as many times in succession as you want, but it's still going to report on the next thing in the input stream.

It cannot tell you anything about the next token after the next token.

You have to read the next token first before you can ask what is after it.

Upvotes: 3

Related Questions