blekione blekione - 1 year ago 103
Java Question

Skipping nextLine() after using next(), nextInt() or other nextFoo() methods

I am using

for reading input. Basically, 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
is skipped and the second
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
. If I delete it, then both
string1 = input.nextLine()
string2 = input.nextLine()
are executed as I want them to be.


Thats 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


  • Either fire a blank Scanner#nextLine call after Scanner#nextInt 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 integer using Integer#parseInt(String) method.

    int option = 0;
    try {
        option = Integer.parseInt(input.nextLine());
    } catch (NumberFormatException e) {
    String str1 = input.nextLine();

You will encounter the similar behaviour when you use Scanner#nextLine after Scanner#next() or any Scanner#nextFoo method (except nextLine itself).