Scanner is skipping nextLine() after using next() or nextFoo()?
That's because the Scanner.nextInt
method does not read the newline character in your input created by hitting "Enter," and so the call to Scanner.nextLine
returns after reading that newline.
You will encounter the similar behaviour when you use Scanner.nextLine
after Scanner.next()
or any Scanner.nextFoo
method (except nextLine
itself).
Workaround:
Either put a
Scanner.nextLine
call after eachScanner.nextInt
orScanner.nextFoo
to consume rest of that line including newlineint option = input.nextInt(); input.nextLine(); // Consume newline left-over String str1 = input.nextLine();
Or, even better, read the input through
Scanner.nextLine
and convert your input to the proper format you need. For example, you may convert to an integer usingInteger.parseInt(String)
method.int option = 0; try { option = Integer.parseInt(input.nextLine()); } catch (NumberFormatException e) { e.printStackTrace(); } String str1 = 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()
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();