java扫描器不会停止获取输入
好的,非常好的问题。我正在制作一个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();
}
}
谢谢:)
# 1 楼答案
我询问您是否从扫描仪读取
noOfQuestions
的原因是Scanner.nextInt()
不使用分隔符(例如新行)这意味着下一次调用
nextLine()
时,您将从上一个readInt()
中得到一个空字符串我的建议是逐行阅读,总是使用
nextLine()
,然后使用Integer.parseInt()
进行解析如果这是你的路线,根本不需要扫描仪;您可以只接受一个BufferedReader
# 2 楼答案
{a1}的文档说明将扫描器前进到当前行,并返回跳过的输入可能解释了您看到的行为。只是为了验证您是否可以添加一个sysout并在
title = entry.nextLine()
之后打印title的值,并查看它所包含的值如果要从输入中读取完整的行,可能需要使用InputStreamReader combination with BufferedReader