java - 如何修复此数组越界异常

标签 java arrays for-loop

我的任务是创建 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/

相关文章:

java - GWT MVC + UIBinder

java - 使用方法重载时程序中的额外输出

java - Android - 如何通过 url 获取 pdf 文件大小?

java - TreeMap 自动删除自身

java - for 循环的 onClickListener 不起作用

c - 使用数组进行队列

javascript - 乘法 2 数组 javascript/jquery

javascript - 根据 D3 中的属性值对对象进行排序

batch-file - 通过类似开关的参数循环的批处理文件?

javascript - 如何循环获取从 config.json 文件获取的值的数量