# 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 inputSystem.out.println("enter 1st string"); String string1 = input.nextLine ();//read first string which is skippedSystem.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 value3//this is my inputenter 1st string//here suppose to be stopped and wait for my input but is skippedenter 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) {        e.printStackTrace();    }    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).