我在尝试使用 java.util.Scanner 中的 nextLine() 方法时遇到了麻烦。
这是我尝试过的:
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() 的行为。