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();
Which works correctly:
This is a string
1714
natural= 1714
string = This is a string
But if I change the order of the lines of the Scanner
:
int i2 = scan.nextInt();
String s2 = scan.nextLine();
It ignores the line scan.nextLine()
and gives me the result right after I enter the int
.
1714
natural= 1714
chain =
Does anyone know what is going on and how to fix it?
The behavior
nextInt()
is not what you expect. When you input a1714
you are actually inputting a1714
and a line break (\n
) and thenextInt()
does not consume the line break (\n
).That means the
nextLine()
is reading this line break (which is empty -->\n
).To fix it, when you do a
nextInt()
always put anextLine()
that will have no content.From your code:
Another way to fix it is to always read with
nextLine()
and do acast
post:In this answer from the original SO they give some more detail, in case you are interested.