Вопрос-ответ

Using scanner.nextLine() [duplicate]

Использование scanner.nextLine()

У меня возникли проблемы при попытке использовать метод nextLine() из java.util.Scanner .

Вот что я попробовал:

import java.util.Scanner;

class TestRevised {
public void menu() {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a sentence:\t");
String sentence = scanner.nextLine();

System.out.print("Enter an index:\t");
int index = scanner.nextInt();

System.out.println("\nYour sentence:\t" + sentence);
System.out.println("Your index:\t" + index);
}
}

Пример № 1: Этот пример работает так, как задумано. Строка String sentence = scanner.nextLine(); ожидает ввода, прежде чем перейти к System.out.print("Enter an index:\t");.

Это приводит к выводу:

Enter a sentence:   Hello.
Enter an index: 0

Your sentence: Hello.
Your index: 0

// Example #2
import java.util.Scanner;

class Test {
public void menu() {
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("\nMenu Options\n");
System.out.println("(1) - do this");
System.out.println("(2) - quit");

System.out.print("Please enter your selection:\t");
int selection = scanner.nextInt();

if (selection == 1) {
System.out.print("Enter a sentence:\t");
String sentence = scanner.nextLine();

System.out.print("Enter an index:\t");
int index = scanner.nextInt();

System.out.println("\nYour sentence:\t" + sentence);
System.out.println("Your index:\t" + index);
}
else if (selection == 2) {
break;
}
}
}
}

Пример № 2: Этот пример работает не так, как предполагалось. В этом примере используются цикл while и структура if - else, позволяющие пользователю выбирать, что делать. Как только программа добирается до String sentence = scanner.nextLine();, она не ожидает ввода, а вместо этого выполняет строку System.out.print("Enter an index:\t");.

Это приводит к выводу:

Menu Options

(1) - do this
(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

int selection = scanner.nextInt();

reads just the number, not the end of line or anything after the number. When you declare

String sentence = 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)

import java.util.Scanner;

class ScannerTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\\n");

System.out.print("Enter an index: ");
int index = scanner.nextInt();

System.out.print("Enter a sentence: ");
String sentence = scanner.next();

System.out.println("\nYour sentence: " + sentence);
System.out.println("Your index: " + index);
}
}

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.

java