【问题标题】:Scanner doesn't stop to get input扫描仪不会停下来获取输入
【发布时间】:2010-09-23 16:31:36
【问题描述】:

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

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”?
  • 是的,在 Scanner 声明和 for 循环之间还有一些代码。我把它们排除在外是因为它会使引用的代码太长。立即将它们重新添加...

标签: java input java.util.scanner


【解决方案1】:

我问你是否从 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() 进行解析。

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

【讨论】:

  • 另一种方法是将每个 nextInt() 与一个 nextLine() 配对,您会丢弃其结果,但这会变得混乱。
【解决方案2】:

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

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

【讨论】:

  • 是的,但是我多次使用nextLine,只是在“问题文本”部分跳过。例如,它没有跳过“输入标题”部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-02
相关资源
最近更新 更多