Skip to content

Why does Scanner skip user input?

discorddioxin edited this page Apr 15, 2022 · 18 revisions

Contents


Reproducing the issue

Given the input:

1
2
Hello World

Writing a Scanner to read the data:

Scanner scanner = new Scanner(System.in);

System.out.println(scanner.nextInt());
System.out.println(scanner.nextInt());
System.out.println(scanner.nextLine());

The code above will print

1
2

"Hello World" did not print.


Solution

Add a dummy nextLine() after the last non-nextLine() call.

Scanner scanner = new Scanner(System.in);

System.out.println(scanner.nextInt());
System.out.println(scanner.nextInt());
scanner.nextLine(); // dummy call

System.out.println(scanner.nextLine());

Pressing "Enter" is the issue

Notice the extra \n characters?

When the user presses Enter to submit data, \n gets added after the input

The only method capable of consuming \n by default is nextLine()

Let's see how Scanner is processing input:

Diving in

  • Step 1: Reading the first number

    • Buffer Before: 1\n2\nHello World\n

    • Operation: nextInt() - looks for the next available number, consumes it

    • Value Consumed: 1

    • Buffer After: \n2\nHello World\n

  • Step 2: Reading the 2nd number

    • Buffer before: \n2\nHello World\n

    • Operation: nextInt() - looks for the next available number, consumes it

    • Value Consumed: 2 - the \n before it gets removed

    • Buffer After: \nHello World\n

  • Step 3: Reading the sentence (!! This is where the issue occurs !!)

    • Buffer before: \nHello World\n

    • Operation: nextLine() - consumes everything from the beginning, up to the next \n

    • Value Consumed: \n

    • Buffer After: Hello World\n


Code Demos

Clone this wiki locally