Scanner is skipping nextLine() after using next() or nextFoo()?
I am using the Scanner
methods nextInt()
and nextLine()
for reading input.
It looks like this:
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
System.out.println("Enter 1st string");
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
The problem is that after entering the numerical value, the first input.nextLine()
is skipped and the second input.nextLine()
is executed, so that my output looks like this:
Enter numerical value
3 // This is my input
Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped
Enter 2nd string // ...and this line is executed and waits for my input
I tested my application and it looks like the problem lies in using input.nextInt()
. If I delete it, then both string1 = input.nextLine()
and string2 = input.nextLine()
are executed as I want them to be.
That's because the Scanner.nextInt
method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine
.
You will encounter the similar behaviour when you use Scanner.nextLine
after Scanner.next()
or any Scanner.nextFoo
method (except nextLine
itself).
Workaround:
Either fire a blank Scanner.nextLine
call after Scanner.nextInt
or Scanner.nextFoo
to consume rest of that line including newline
int option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();
Or, it would be even better, if you read the input through Scanner.nextLine
and convert your input to the proper format you need. For examples, to an integer using Integer.parseInt(String)
method.
int option = 0;
try {
option = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String str1 = input.nextLine();
The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "n" Enter key. So to skip this you have to add the input.nextLine() . Hope this should be clear now.
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
It's because when you enter a number then press Enter, input.nextInt()
consumes only the number, not the "end of line". When input.nextLine()
executes, it consumes the "end of line" still in the buffer from the first input.
Instead, use input.nextLine()
immediately after input.nextInt()