-
Notifications
You must be signed in to change notification settings - Fork 0
Why does Scanner skip user input?
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.
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());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:
-
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\nbefore 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
-