4

わかりました、非常に初歩的な質問です。ユーザーがアンケートを設計できる 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(); 

    }
}

ありがとう :)

4

2 に答える 2

6

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 を受け入れることができます。

于 2010-09-23T16:57:36.430 に答える
0

nextLine()のドキュメントには、現在の行を過ぎてこのスキャナーを進め、スキップされた入力を返すと書かれています。あなたが見ている行動を説明するかもしれません。title = entry.nextLine()sysout を追加して title の値を の後に出力し、保持されている値 を確認できることを確認するためだけに

入力から完全な行を読み取りたい場合は、InputStreamReader と BufferedReader の組み合わせを使用することをお勧めします。

于 2010-09-23T16:49:17.647 に答える