2017  Kodetalk | Feedback | Privacy Policy | Terms | About

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

I can not find what is the logic behind this issue.I am using Scanner methods nextInt() and nextLine() for reading input. Basically it looks like that

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 first string which is skipped
System.out.println("enter 2nd string");
String string2 = input.nextLine ();//read 2nd string which appeared straight after reading numerical value

and the problem is that after entering numerical value first input.nextLine() is skipped and the second input.nextLine() is executed, so my output looks

Enter numerical value
3//this is my input
enter 1st string//here suppose to be stopped and wait for my input but is skipped
enter 2nd string//and this line is executed and wait for my input

I tested my "application" and it looks like the problem lies in using input.nextInt(). If I delete it then nextLine() works fine, I mean both string1 = input.nextLine() and string1 = input.nextLine() are executed.


That is because the newline is consumed in the next call to Scanner.nextLine , and thus that Scanner.nextInt method does not consume the last newline character of your input.

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).

Answer is