Imagine the following scanario: I have a program which ask for an integer input, followed by a String input.
int age=0;
String name;
Scanner sc = new Scanne
You should use only one Scanner
instance per object that you are scanning. In this case you are reading from the System.in
, so opening two scanners on the same them concurrently does not even make sense.
So you definately want to go with your first option, then the question comes, what is wrong with it:
Well, you ask for sc.nextInt()
, an integer, and a name rarely is an integer. You are most likely looking for either name = sc.next()
for one word or for name = sc.nextLine()
for a whole sentence (until the enter key has been pressed).
Also be aware that after sc.nextInt()
, actually after any sc.next***()
, you need to press Enter.