The nextInt()
and nextLine()
methods of Scanner
are used as follows to receive keyboard input.
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 numerical values, the first input.nextLine()
is not executed, but the second input.nextLine()
is executed.
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 it, and this seems to be caused by input.nextInt()
. So when I erase it and run it, string1 = input.nextLine()
and string2 = input.nextLine()
run as I expected. What's the problem?
This is because the Scanner#nextInt
method does not remove the last opening character (newline) of the user input. In other words, I'm reading it in numbers before the opening letter. So the open letter was then processed as an input to the Scanner#nextLine()
method that was called.
int option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();
int option = 0;
try {
option = Integer.parseInt(input.nextLine());
} } catch (NumberFormatException e) {
e.printStackTrace();
}
String str1 = input.nextLine();
If you run the Scanner#next()
or Scanner#nextFoo
method and then use Scanner#nextLine
the same situation will continue.
© 2024 OneMinuteCode. All rights reserved.