Сканер пропускает nextLine() после использования next() или nextFoo()?JAVA

Программисты JAVA общаются здесь
Anonymous
Сканер пропускает nextLine() после использования next() или nextFoo()?

Сообщение Anonymous »

Я использую методы Scanner nextInt() и nextLine() для чтения входных данных.

Выглядит это так:

Код: Выделить всё

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)
Проблема в том, что после ввода числового значения пропускается первый input.nextLine(), а второй input.nextLine() выполняется, поэтому мой вывод выглядит следующим образом:

Код: Выделить всё

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
Я протестировал свое приложение, и похоже, что проблема заключается в использовании input.nextInt(). Если я удалю его, то и string1 = input.nextLine(), и string2 = input.nextLine() будут выполнены так, как я хочу.

Подробнее здесь: https://stackoverflow.com/questions/131 ... or-nextfoo

Вернуться в «JAVA»