我的任务是创建 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));
}
最佳答案
您在循环中获得答案,这意味着您希望在每次迭代中得到一个答案,但您在每次迭代中分配整个 studentAnswers
数组。
你可能应该改变
studentAnswers = scan.next().toCharArray();
至
studentAnswers[i] = scan.nextLine().charAt(0);
假设您希望每个输入行中有一个字符答案。
如果输入是在单行中提供的,并用空格分隔,则可以使用
studentAnswers[i] = scan.next().charAt(0);
或者您可以将整个循环替换为:
studentAnswers = scan.nextLine().split(" ");
关于java - 如何修复此数组越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36393197/