gpt4 book ai didi

java - 使用scanner.nextLine()

转载 作者:IT老高 更新时间:2023-10-28 11:34:01 28 4
gpt4 key购买 nike

我在尝试使用 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() 的行为。

最佳答案

我认为你的问题是

int selection = scanner.nextInt();

只读取数字,而不是行尾或数字之后的任何内容。当你声明

String sentence = scanner.nextLine();

这会读取带有数字的行的其余部分(我怀疑的数字后面没有任何内容)

尝试放置一个scanner.nextLine();如果您打算忽略该行的其余部分,则在每个 nextInt() 之后。

关于java - 使用scanner.nextLine(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5032356/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com