2015-05-01 33 views
0

我想用數組詢問用戶關於不同狀態的問題,但是當我編譯它時,它在線程「main」中輸出異常。我該如何完成這個stateQuiz.java程序

import java.util.*; 

class StateQuiz{ 

    public static void main(String[] args){ 
     boolean[] asked = new boolean[10]; 
     boolean correct[] = new boolean[10]; 
     Arrays.fill(asked, true); 
     String [] answers={"Alaska","Ohio","Illinois","Ohio","Florida","Hawaii","New York","California","Maryland","Texas"}; 
     String [] questions={"What is the largest state?","Where is the city of Columbus located?","Where is the city of Springfield located?","Where is Ohio State located?","What is the orange state?","What is the most southern state?","Where is the Big Apple?","Where is Hollywood?","What state is Baltimore located?","What state looks like a boot?"}; 
     int nextQ = -1; 
     boolean good = false; 
     do { 
      nextQ = getNextQuestion(asked); 
      good = quizUser(answers,questions,nextQ); 
      asked[nextQ] = true; 
      if (good == true) { 
       correct[nextQ] = true; 
      } else { 
       correct[nextQ] = false; 
      } 
     } while (nextQ != -1); 

     printResults(correct); 
    } 

    public static int getNextQuestion(boolean[] questions_asked){ 
     int[] poo = {}; 
     for (int i = 0; i < questions_asked.length; i ++) { 
      if (questions_asked[i] == false) { 
       poo[poo.length] = i; 
      } 
     } 

     if (poo.length == 0) { 
      return -1; 
     } 

     int rand = (int) Math.round(Math.random() * poo.length); 
     return poo[rand]; 
    } 

    public static boolean quizUser(String[]answers,String[]questions, int nextQ) 
    { 
     System.out.println(questions[nextQ]); 
     String an; 
     Scanner keyboard = new Scanner(System.in); 
     an = keyboard.nextLine(); 
     if(an.equalsIgnoreCase(answers[nextQ])){ 
      System.out.println("Correct"); 
      return true; 
     }else{ 
      System.out.println("Incorrect"); 
      return false; 
     } 
    } 


    //finding the average correct answers 
    public static void printResults (boolean[] questions){ 
     int correctQuestions = 0; 
     double average = 0; 
     for(int i=0; i < questions.length ; i++) { 
      if (questions[i]) { 
       correctQuestions += 1; 
      } 
     } 

     average = correctQuestions/questions.length; 

     //return average; 
     System.out.println("Your average socre is:" + average); 

     if (average > 80) { 
      System.out.println ("Wow! You really know a lot about state birds!"); 
     } else if (average > 40 && average < 80) { 
      System.out.println ("Apparently you know some state birds."); 
     } else if (average < 40) { 
      System.out.println ("You could spruce up your knowledge on state birds."); 
     } 
    } 
} 

回答

1

問題是與這一行:

INT nextQ = -1;

在第15行這將是:

好= quizUser(答案,提問,-1);

而且,48號線在你的代碼將是:

的System.out.println(問題[-1]);

因此,您將獲取ArrayIndexOutOfBoundsException,因爲您正嘗試訪問數組中的第-1個元素。

請記住,如果是do-while循環,它首先執行,然後檢查「while」中指定的條件。將它改爲簡單的while語句可能是最簡單的解決方案,如果這樣做 - 雖然令你感到困惑。