Bad*_*est 4 java input java.util.scanner
好吧,非常菜鸟的问题。我正在制作一个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();
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢 :)
我询问您是否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()
Run Code Online (Sandbox Code Playgroud)
我的建议是始终按行逐行阅读nextLine(),然后使用解析Integer.parseInt()。
如果那是您选择的路线,那么根本不需要扫描仪。您可以只接受BufferedReader。
| 归档时间: |
|
| 查看次数: |
3469 次 |
| 最近记录: |