This question already has an answer here:
(这个问题在这里已有答案:)
I have been having trouble while attempting to use the nextLine() method from java.util.Scanner.
(尝试使用java.util.Scanner中的nextLine()方法时遇到了麻烦。)
Here is what I tried:
(这是我尝试过的:)
import java.util.Scanner;
class TestRevised {
public void menu() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence:");
String sentence = scanner.nextLine();
System.out.print("Enter an index:");
int index = scanner.nextInt();
System.out.println("
Your sentence:" + sentence);
System.out.println("Your index:" + index);
}
}
Example #1: This example works as intended.
(示例#1:此示例按预期工作。)
The line String sentence = scanner.nextLine();
(线String sentence = scanner.nextLine();
)
waits for input to be entered before continuing on to System.out.print("Enter an index:\t");
(在继续执行System.out.print("Enter an index:\t");
之前等待输入输入System.out.print("Enter an index:\t");
)
. (。)
This produces the output:
(这会产生输出:)
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("
Menu Options
");
System.out.println("(1) - do this");
System.out.println("(2) - quit");
System.out.print("Please enter your selection:");
int selection = scanner.nextInt();
if (selection == 1) {
System.out.print("Enter a sentence:");
String sentence = scanner.nextLine();
System.out.print("Enter an index:");
int index = scanner.nextInt();
System.out.println("
Your sentence:" + sentence);
System.out.println("Your index:" + index);
}
else if (selection == 2) {
break;
}
}
}
}
Example #2: This example does not work as intended.
(示例#2:此示例无法按预期工作。)
This example uses a while loop and and if - else structure to allow the user to choose what to do. (此示例使用while循环和if - else结构允许用户选择要执行的操作。)
Once the program gets to String sentence = scanner.nextLine();
(一旦程序到达String sentence = scanner.nextLine();
)
, it does not wait for input but instead executes the line System.out.print("Enter an index:\t");
(,它不等待输入,而是执行System.out.print("Enter an index:\t");
行System.out.print("Enter an index:\t");
)
. (。)
This produces the output:
(这会产生输出:)
Menu Options
(1) - do this
(2) - quit
Please enter your selection: 1
Enter a sentence: Enter an index:
Which makes it impossible to enter a sentence.
(这使得无法输入句子。)
Why does example #2 not work as intended?
(为什么示例#2不能按预期工作?)
The only difference between Ex. (Ex之间的唯一区别。)
1 and 2 is that Ex. (1和2是Ex。)
2 has a while loop and an if-else structure. (2有一个while循环和一个if-else结构。)
I don't understand why this affects the behavior of scanner.nextInt(). (我不明白为什么这会影响scanner.nextInt()的行为。)
ask by Taylor P. translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…