2016-10-26 12 views
0

クイズメーカーコードを作成しようとしているとき: 質問の数を尋ねて、それから多くの質問を作成し、それぞれの質問を返すことができます。私はなぜ出力が行ごとの出力と入力ではないのか混乱しています。私は、java.io. *とjava.utilのを輸入している。*Javaで配列の回数だけを出力するループで配列を作成する方法は?

public class quiz { 
    public static void main(String []args){ 

     Scanner kbReader = new Scanner(System.in); 
     System.out.println("[email protected]{@{@{{{{{{{{{{{{{{{{{{ Quizmaker }}}}}}}}}}}}}}}}}}@}@}@~"); 
     System.out.println("How many questions are in this quiz?"); 
     int numberoQuestions = kbReader.nextInt(); 
     //lets make this input 4 
     String question [] = new String [numberoQuestions]; //the questions the user has made 
     int createdQs = 0; //how many questions the user has made 

     do { 
     createdQs ++; 
     System.out.println("What is question " + createdQs); 
     question [createdQs]= kbReader.nextLine(); 
     } 
     while(createdQs <= numberoQuestions); 
/* 
supposed to print 
How many questions are in this quiz? 
(4) 
What is question 1? 
(input) 
What is question 2? 
(input) 
What is question 3? 
(input) 
What is question 4? 
(input) 

it instead prints 
How many questions are in this quiz? 
4 
What is question 1 
What is question 2 
age? 
What is question 3 
height? 
What is question 4 
school? 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 
    at finalProject.quiz.main(quiz.java:18) 

*/ 
     System.out.println(question[3]);//prints question 4 but I want it to print question 3 
    } 
} 
+0

:ここ

は、あなたが何をする必要があるかです。 java.lang.ArrayIndexOutOfBoundsExceptionが発生しないようにします。 –

答えて

2

使用scanner.readLine()を、nextInt()を呼び出した後、バッファに残って改行を消費do-whileループの最後にcreatedQs++;を移動し、ループを変更するには配列はcreatedQs < numberoQuestionsになります(配列は0から始まり、length-1になります)。

0

入力にスキャナを使用する場合、最初の入力の後には常にscanner.nextLine()を実行して、制御を入力に戻してさらに入力を行うことができます。あなたはcreatedQs

public static void main(String[] args) { 
     Scanner kbReader = new Scanner(System.in); 
      System.out.println("[email protected]{@{@{{{{{{{{{{{{{{{{{{ Quizmaker }}}}}}}}}}}}}}}}}}@}@}@~"); 
      System.out.println("How many questions are in this quiz?"); 
      int numberoQuestions = kbReader.nextInt(); 
      kbReader.nextLine();//<-- this is mandatory whenever you take input from scanner 
      //lets make this input 4 
      String question [] = new String [numberoQuestions]; //the questions the user has made 
      int createdQs = 0; //how many questions the user has made 

      do { 

      System.out.println("What is question " + createdQs+1);// you can say +1 here and display question 1 
      question [createdQs]= kbReader.nextLine(); 
      createdQs ++;// increment here not at beginning of do. So that index out of bound exception is not there 
      } 
      while(createdQs < numberoQuestions);// it should be < not <= 

    } 
+0

なぜdownvote ..説明してください? –

関連する問題