I am using the Scanner
methods nextInt()
and nextLine()
for reading input.
It looks like this:
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
System.out.println("Enter 1st string");
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
The problem is that after entering the numerical value, the first input.nextLine()
is skipped and the second input.nextLine()
is executed, so that my output looks like this:
Enter numerical value
3 // This is my input
Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped
Enter 2nd string // ...and this line is executed and waits for my input
I tested my application and it looks like the problem lies in using input.nextInt()
. If I delete it, then both string1 = input.nextLine()
and string2 = input.nextLine()
are executed as I want them to be.
It does that because
input.nextInt();
doesn't capture the newline. you could do like the others proposed by adding aninput.nextLine();
underneath.Alternatively you can do it C# style and parse a nextLine to an integer like so:
Doing this works just as well, and it saves you a line of code.
If you want to read both strings and ints, a solution is to use two Scanners:
The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now.
Try it like that:
Instead of
input.nextLine()
useinput.next()
, that should solve the problem.Modified code:
sc.nextLine()
is better as compared to parsing the input. Because performance wise it will be good.As
nextXXX()
methods don't readnewline
, exceptnextLine()
. We can skip thenewline
after reading anynon-string
value (int
in this case) by usingscanner.skip()
as below: