扫描仪不停止获取输入

4

好的,这是一个非常初级的问题。我正在制作一个CLI应用程序,让用户设计调查问卷。首先他们输入问题,然后是选项数量和选项。我使用Scanner获取输入,但出现了一个问题,它允许用户输入大部分内容,但不允许输入问题的文本。以下是代码片段。

String title = "";
Question[] questions;
int noOfQuestions = 0;
int[] noOfChoices;
Scanner entry = new Scanner(System.in);
System.out.println("Please enter the title of the survey: ");
title = entry.nextLine();
System.out.println("Please enter the number of questions: ");
noOfQuestions = entry.nextInt();
noOfChoices = new int[noOfQuestions];
questions = new Question[noOfQuestions];
for (int i = 0; i < noOfQuestions; i++) {
    questions[i] = new Question();
}
for (int i = 0; i < noOfQuestions; i++) {

    System.out.println("Please enter the text of question " + (i + 1) + ": ");
    questions[i].questionContent = entry.nextLine();
    System.out.println("Please enter the number of choices for question " + (i + 1) + ": ");
    questions[i].choices = new String[entry.nextInt()];
    for (int j = 0; j < questions[i].choices.length; j++) {
        System.out.println("Please enter choice " + (j + 1) + " for question " + (i + 1) + ": ");
        questions[i].choices[j] = entry.nextLine(); 

    }
}

感谢您的选择 :)

你确定这是所有相关的代码吗?难道你没有从扫描器中读取“noOfQuestions”吗? - Mark Peters
是的,在 Scanner 声明和 for 循环之间还有一些代码。我将它们省略了,因为这会使引用的代码太长。现在正在把它们添加回去... - Bad Request
2个回答

6

我询问你是否从Scanner读取 noOfQuestions 的原因是因为 Scanner.nextInt()不会消耗分隔符(例如换行符)。

这意味着下一次调用 nextLine()时,您将只从先前的 readInt()获得一个空字符串。

75\nQuestion 1: What is the square route of pie?
^ position before nextInt()

75\nQuestion 1: What is the square route of pie?
  ^ position after nextInt()

75\nQuestion 1: What is the square route of pie?
    ^ position after nextLine()

我的建议是逐行阅读,始终使用nextLine(),然后再使用Integer.parseInt()解析。

如果您选择这条路线,几乎不需要使用Scanner; 您可以只接受BufferedReader。


另一个选择是将每个nextInt()与一个nextLine()配对,但您要丢弃其结果,这会变得混乱不堪。 - Mark Peters

0

nextLine() 的文档说明中写道:将此扫描器推进到当前行之后,并返回跳过的输入。这可能可以解释您所看到的行为。为了验证,您可以添加 sysout 并在 title = entry.nextLine() 之后打印 title 的值,看看它持有什么值。

如果您想从输入中读取完整的一行,您可能需要使用 InputStreamReader 结合 BufferedReader


是的,但我使用了几次nextLine,只有在“问题文本”部分跳过了。例如,在“输入标题”部分没有跳过。 - Bad Request

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接