So I instantiate the Scanner scan
a lot earlier but it skips right over my second scan.nextLine()
after scan.nextInt()
. I don't understand why it skips over it?
System.out.println("Something: ");
String name = scan.nextLine();
System.out.println("Something?: ");
int number = scan.nextInt();
System.out.println("Something?: ");
String insurer = scan.nextLine();
System.out.println("Something?: ");
String another = scan.nextLine();
All answers given before are more or less correct.
Here is a compact version:
What you want to do: First use
nextInt()
, then usenextLine()
What is happening: While
nextInt()
is waiting for your input, you pressENTER
key after you type your integer. The problem isnextInt()
recognizes and reads only numbers so the\n
for theENTER
key is left behind on the console. When thenextLine()
comes again, you expect it to wait till it finds\n
. But what do you didn't see is that\n
is already lying on the console because of erratic behavior ofnextInt()
[This problem still exists as a part of jdk8u77].So, the nextLine reads a blank input and moves ahead.
Solution: Always add a
scannerObj.nextLine()
after each use ofscannerObj.nextInt()
because when you enter a number
you enter some number and hit enter, it only accepts number and keeps new line character in buffer
so
nextLine()
will just see the terminator character and it will assume that it is blank String as input, to fix it add onescan.nextLine()
after you processint
for example:
When you call
int number = scan.nextInt();
it does not consume the carriage return that has been pushed, so this is does at the nextscan.nextLine();
You want your code to be
character left behind and consider the end ,skipping the rest.
Solution
OR
//Parse the string to interger explicitly