使用scanner.nextLine()在尝试使用java.utils.caner的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: 0Your sentence: Hello.Your index: 0// Example #2import 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:此示例不按预期工作。此示例使用WHITH循环和if-Other结构来允许用户选择要执行的操作。一旦程序到达String sentence = scanner.nextLine();,它不等待输入,而是执行。System.out.print("Enter an index:\t");.这将产生输出:Menu Options(1) - do this(2) - quitPlease enter your selection: 1Enter a sentence: Enter an index:这使得不可能输入一个句子。为什么示例2不按预期工作?唯一的区别是。1和2是那个Ex。2有一个WITH循环和一个if-Other结构。我不明白为什么这会影响scanner.nextInt()的行为。
3 回答
繁星点点滴滴
TA贡献1803条经验 获得超3个赞
int selection = scanner.nextInt();
String sentence = scanner.nextLine();
慕雪6442864
TA贡献1812条经验 获得超5个赞
input.nextInt()
input.next()
String sentence = scanner.next()
提示:scanner.nextLine()
scanner.next()
scanner.next()
添加回答
举报
0/150
提交
取消