4

好吧,非常菜鸟的问题。我正在制作一个让用户设计调查的 CLI 应用程序。他们首先输入问题,然后输入选项的数量和选项。我正在使用扫描仪来获取输入,出于某种原因,它允许用户输入大多数内容,但不能输入问题的文本。下面的代码片段。

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(); 

    }
}

谢谢 :)

4

2 回答 2

6

我询问您是否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().

如果这是您采取的路线,则根本不需要扫描仪;你可以只接受一个 BufferedReader。

于 2010-09-23T16:57:36.430 回答
0

nextLine()的文档说将此扫描仪前进到当前行并返回被跳过的输入。可能会解释您所看到的行为。只是为了验证您可以添加一个 sysout 并在之后打印 title 的值,title = entry.nextLine()看看它持有什么值

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

于 2010-09-23T16:49:17.647 回答