如何修复此数组超出范围的异常

时间:2016-04-04 01:09:33

标签: java arrays for-loop

我的任务是创建2个char数组,其中一个使用"正确答案"用于测试,另一个用户输入答案。代码正常工作和编译,但是当我将所有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 个答案:

答案 0 :(得分: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的字符序列。

答案 1 :(得分:1)

您在循环中获得答案,这意味着您希望每次迭代都有一个答案,但是您在每次迭代中分配整个studentAnswers数组。

你可能应该改变

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

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

假设您希望每个输入行都有一个char答案。

如果输入以单行提供,以空格分隔,则可以使用

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

或者你可以用:

替换整个循环
studentAnswers = scan.nextLine().split(" ");