首页 > 解决方案 > 错误-> java.lang.ArrayIndexOutOfBoundsException:8

问题描述

我创建了这个多项选择程序,一切都很好,正确的答案正在打印出来,但我不断得到:

线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 8 在 MultipleChoices.main(MultipleChoices.java:21)

有人可以告诉我我需要做什么来解决这个错误吗?

        for(int i = 0; i < student[i].length; i++){
            int rightAns = 0;
            for(int j = 0; j < student[i].length; j++){
                if(student[i][j].equalsIgnoreCase(key[j])){
                    rightAns++;
            }
        }

标签: javaarraysindexoutofboundsexception

解决方案


您的第一个 for 循环使用了错误的值。你应该使用 student.length 而不是 student[i]。

for(int i = 0; i < student.length; i++){
        int rightAns = 0;
        for(int j = 0; j < student[i].length; j++){
            if(student[i][j].equalsIgnoreCase(key[j])){
                rightAns++;
            }
        }

        System.out.print("Student's " + i + "#correct answer: " + rightAns + "\n");
    }

}

推荐阅读