【问题标题】:Error -> java.lang.ArrayIndexOutOfBoundsException: 8错误-> java.lang.ArrayIndexOutOfBoundsException: 8
【发布时间】:2020-05-01 08:02:23
【问题描述】:

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

线程“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++;
            }
        }

【问题讨论】:

  • 问题是您试图获取仅包含 8 个元素的数组的第 9 个元素。
  • @Stultuske 那么我该如何解决这个错误呢?

标签: java arrays indexoutofboundsexception


【解决方案1】:

您的第一个 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");
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 2018-09-10
    相关资源
    最近更新 更多