gpt4 book ai didi

java - 扫描仪不会停止获取输入

转载 作者:搜寻专家 更新时间:2023-11-01 02:33:31 25 4
gpt4 key购买 nike

好吧,非常菜鸟的问题。我正在制作一个允许用户设计调查的 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();

}
}

谢谢:)

最佳答案

我问你是否从扫描仪读取 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。

关于java - 扫描仪不会停止获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3780524/

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