I have this little code. It happens that when the time comes to enter the third data (the name), it skips it, it is as if it automatically hit enter and could not write anything:
Scanner sc = new Scanner(System.in);
System.out.println("Introduce el primer numero: ");
int num1 = sc.nextInt();
System.out.println("Introduce el segundo numero: ");
int num2 = sc.nextInt();
System.out.println("Introduce tu nombre: ");
String nombre = sc.nextLine();
System.out.println("--------------"); //esto no es mas que decoracion
In such a way that the console output would be something like this:
Introduce el primer numero:
1
Introduce el segundo numero:
2
Introduce tu nombre:
-------------
I don't know why this happens. It's like the Scanner class goes crazy when I first ask it for int and then for String. Do you know what happens?
This is because the method
Scanner.nextInt
does not consume the last newline character of its input, and therefore that newline is consumed on the next call toScanner.nextLine
.You will find the same behavior when you use
Scanner.nextLine
afterScanner.next ()
or any other methodScanner.nextFoo
(exceptnextLine
).What you can do is the following:
Font:
Just change the
by
For some reason the nextLine() doesn't let you enter such an input.
In case you have doubts about the differences>
next() reads until it finds a space (stops reading at the first space)
nextLine() reads the entire line (stops reading at line break)