Skaner pomija nextLine () po użyciu next () lub nextFoo ()?
UżywamScanner
metodynextInt()
inextLine()
do odczytu danych wejściowych.
To wygląda tak:
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)
Problem polega na tym, że po wprowadzeniu wartości liczbowej pierwszyinput.nextLine()
jest pomijany, a drugiinput.nextLine()
jest wykonywane, więc moje dane wyjściowe wyglądają tak:
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
Przetestowałem moją aplikację i wygląda na to, że problem leży w użytkowaniuinput.nextInt()
. Jeśli go usunę, to obastring1 = input.nextLine()
istring2 = input.nextLine()
są wykonywane tak, jak chcę, żeby były.