Scanner.nextLine () does not act correctly after Scanner.nextInt()

I have this code:

Scanner scan = new Scanner(System.in);

String s2 = scan.nextLine();
int i2    = scan.nextInt();

System.out.println("natural= " + i2);
System.out.println("cadena = " + s2);

scan.close();

That works correctly:

This is a string
1714
natural= 1714
string = this is a string

But if I change the order of the lines of Scanner:

int i2    = scan.nextInt();
String s2 = scan.nextLine();

Ignores the Line scan.nextLine() and gives me the result right after entering the int

1714
natural= 1714
string =

Does anyone know what's going on and how fix it?

 14
Author: joc, 2016-09-02

1 answers

The behavior of the nextInt() it's not what you expect. When you input a 1714 you're actually entering a 1714 and a line break(\n) and the nextInt() does not consume you the line break (\n).

That means the nextLine() is reading this line break (which is empty --> \n).

To fix it, when you make a nextInt() always put a nextLine() that will have no content.

From you code:

int i2    = scan.nextInt();
String saltoDeLinea = scan.nextLine();
String s2 = scan.nextLine();

Another way to fix it is to always read with nextLine() and do a cast a posteriori:

int i2 = Integer.parseInt(scan.nextLine());
String s2 = scan.nextLine();

In this answer from the original OS give some more detail, in case you are interested.

 17
Author: Miquel Coll, 2017-05-23 12:39:23