2016-04-04 57 views
0

我的任務是創建2個字符數組,其中一個用於測試的「正確答案」,另一個用戶輸入答案。代碼正常工作和編譯正確,但是當我得到所有10個答案輸入到程序中時,我得到一個數組越界異常。如何解決這個數組越界異常

這裏是代碼片段:

//Part 2 
    char[] correctAnswers = {'b', 'd', 'a', 'a', 'c', 'a', 'b', 'a', 'c', 'd'}; //Char arrays 
    char[] studentAnswers = new char[10]; 

    System.out.println("What are the students 10 answers?"); //Getting student answers 
    for(int i = 0; i < correctAnswers.length; i++) 
    { 
     System.out.println("What is the answer to the " + i + " question"); 
     studentAnswers = scan.next().toCharArray(); 
    } 

    int points = 0; //Used to calculate pass or fail 


    for(int i = 0; i < correctAnswers.length; i++) 
    { 
     if (correctAnswers[i] == studentAnswers[i]) 
     points++; 
    } 




    if (points >= 8) 
    { 
     System.out.println("Congratulations! \nYou have passed exam."); 
     System.out.println("Total number of correct answers: " + points); //print points 
     System.out.println("Total number of incorrect answers: " + (correctAnswers.length - points)); //10 - points would equal the remaining amount of points available which would be how many were missed. 
    } 

    else 
    { 
     System.out.println("Sorry, you have not passed the exam!"); 
     System.out.println("Total number of correct answers: " + points); 
     System.out.println("Total number of incorrect answers: " + (correctAnswers.length - points)); 
    } 
+2

堆棧跟蹤請。當你遇到錯誤,你應該更好地發佈你的完整堆棧跟蹤 – HungPV

+2

問題在這裏:'studentAnswers = scan.next()。toCharArray();',你想添加用戶輸入到'studentAnswers',而不是替換數組在每一個輸入 – Maljam

回答

1

你得到的答案在一個循環中,這意味着你在每次迭代中期待一個答案的字符序列,但您將在每次迭代中分配整個studentAnswers陣列。

你或許應該改變

studentAnswers = scan.next().toCharArray(); 

studentAnswers[i] = scan.nextLine().charAt(0); 

假設你希望在每個輸入行的單個字符的答案。

如果輸入的是在一個單一的線路供電,用空格分隔,可以使用

studentAnswers[i] = scan.next().charAt(0); 

,或者你可以用更換整個循環:

studentAnswers = scan.nextLine().split(" "); 
+0

謝謝你這麼多。這非常合理。 – Tyler

1

的問題是,在studentAnswers = scan.next().toCharArray();這裏你必須確保你得到來自用戶的整整10個字符長的響應。

爲了做到這一點,你可以做這樣的事情。

while(true){ 
    char[] temp=scan.next().toCharArray(); 
    if(temp.length==10){ 
     studentAnswers=temp; 
     break; 
    } 
    else{ 
     //print that the length is incorrect. 
    } 
} 

這種方式可以確保用戶輸入的準確長度10