Java 扫描仪没有';不要停下来获取输入
好的,非常好的问题。我正在制作一个CLI应用程序,允许用户设计调查。首先他们输入问题,然后输入选择的数量和选择。我使用扫描仪获取输入,出于某种原因,它允许用户输入大部分内容,但不允许输入问题的文本。下面是代码片段Java 扫描仪没有';不要停下来获取输入,java,input,java.util.scanner,Java,Input,Java.util.scanner,好的,非常好的问题。我正在制作一个CLI应用程序,允许用户设计调查。首先他们输入问题,然后输入选择的数量和选择。我使用扫描仪获取输入,出于某种原因,它允许用户输入大部分内容,但不允许输入问题的文本。下面是代码片段 String title = ""; Question[] questions; int noOfQuestions = 0; int[] noOfChoices; Scanner entry = new Scanner(System.in); System.out.println("
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();
}
}
String title=”“;
问题[]问题;
int noOfQuestions=0;
国际[]无选择;
扫描仪条目=新扫描仪(System.in);
System.out.println(“请输入调查标题:”);
title=entry.nextLine();
System.out.println(“请输入问题数量:”);
noOfQuestions=entry.nextInt();
noOfChoices=newint[noOfQuestions];
问题=新问题[无问题];
for(int i=0;i
谢谢:)此扫描仪的文档使其越过当前行并返回跳过的输入。可以解释你看到的行为。只是为了验证您是否可以添加一个sysout并在title=entry.nextLine()
之后打印title的值,然后查看它所包含的值
如果要从输入中读取完整的行,可能需要使用。我询问您是否从扫描仪读取
noOfQuestions
的原因是Scanner.nextInt()
不使用分隔符(例如新行)
这意味着下次调用nextLine()
,您只会从前面的readInt()
中得到一个空字符串
我的建议是逐行阅读,始终使用nextLine()
,然后使用Integer.parseInt()
进行解析
如果这是你的路线,根本不需要扫描仪;您可以只接受BufferedReader。您确定这是所有相关代码吗?你不也从扫描器中读取“noOfQuestions”吗?是的,扫描器声明和for循环之间还有一些代码。我忽略了它们,因为这会使引用的代码太长。现在就把它们加回去……是的,但是我用了nextLine好几次,只是在“问题文本”部分跳过了。例如,它没有在“输入标题”部分跳过,另一种方法是将每个nextInt()与一个nextLine()配对,然后丢弃其结果,但这会变得很混乱。
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()