我的任務是創建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));
}
堆棧跟蹤請。當你遇到錯誤,你應該更好地發佈你的完整堆棧跟蹤 – HungPV
問題在這裏:'studentAnswers = scan.next()。toCharArray();',你想添加用戶輸入到'studentAnswers',而不是替換數組在每一個輸入 – Maljam