Skip to content
Advertisement

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement