Пример № 1: Этот пример работает так, как задумано. Строка String sentence = scanner.nextLine(); ожидает ввода, прежде чем перейти к System.out.print("Enter an index:\t");.
Пример № 2: Этот пример работает не так, как предполагалось. В этом примере используются цикл while и структура if - else, позволяющие пользователю выбирать, что делать. Как только программа добирается до String sentence = scanner.nextLine();, она не ожидает ввода, а вместо этого выполняет строку System.out.print("Enter an index:\t");.
Это приводит к выводу:
Menu Options
(1) - dothis (2) - quit
Please enter your selection: 1 Enter a sentence: Enter an index:
Что делает невозможным ввод предложения.
Почему пример # 2 работает не так, как задумывалось? Единственное различие между Ex. 1 и 2 заключается в том, что Ex. 2 имеет цикл while и структуру if-else . Я не понимаю, почему это влияет на поведение scanner.nextInt() .
Переведено автоматически
Ответ 1
I think your problem is that
intselection= scanner.nextInt();
reads just the number, not the end of line or anything after the number. When you declare
Stringsentence= scanner.nextLine();
This reads the remainder of the line with the number on it (with nothing after the number I suspect)
Try placing a scanner.nextLine(); after each nextInt() if you intend to ignore the rest of the line.
Ответ 2
Rather than placing an extra scanner.nextLine() each time you want to read something, since it seems you want to accept each input on a new line, you might want to instead changing the delimiter to actually match only newlines (instead of any whitespace, as is the default)
Thus, to read a line of input, you only need scanner.next() that has the same behavior delimiter-wise of next{Int, Double, ...}
The difference with the "nextLine() every time" approach, is that the latter will accept, as an index also <space>3, 3<space> and 3<space>whatever while the former only accepts 3 on a line on its own
Ответ 3
It's because when you enter a number then press Enter, input.nextInt() consumes only the number, not the "end of line". Primitive data types like int, double etc do not consume "end of line", therefore the "end of line" remains in buffer and When input.next() executes, it consumes the "end of line" from buffer from the first input. That's why, your String sentence = scanner.next() only consumes the "end of line" and does not wait to read from keyboard.
Tip: use scanner.nextLine() instead of scanner.next() because scanner.next() does not read white spaces from the keyboard. (Truncate the string after giving some space from keyboard, only show string before space.)
Ответ 4
Don't try to scan text with nextLine(); AFTER using nextInt() with the same scanner! It doesn't work well with Java Scanner, and many Java developers opt to just use another Scanner for integers. You can call these scanners scan1 and scan2 if you want.