java在通过方法传递的数组中添加值?
private void setAverage(int[] grades1) {
for(int i = 0; i <= grades1.length; i++){
avg += grades1[i];
}
System.out.println(avg);
}
出于某种原因,我得到了一个错误的代码说:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at StudentRecords.setAverage(StudentRecords.java:29)
at StudentRecords.<init>(StudentRecords.java:16)
at StudentRecordTest.main(StudentRecordTest.java:54)
# 1 楼答案
例如,你有一个长度为3的数组,然后你有索引0,1,2。 你不能试图得到索引3
# 2 楼答案
因为代码试图访问数组中不存在的
grades1[3]
元素,所以得到了ArrayIndexOutOfBoundsException: 3
。让我们仔细看看:数组的长度为
3
。这意味着您的数组从index 0
开始,到index 2
->[0, 2]
。如果你数数0, 1, 2,
,你会得到3
,这是长度现在,逻辑在for循环中关闭。你从
i = 0
开始,到i <= 3
结束。在for循环中访问grades1[i]
时,访问每个元素i
,直到条件为false有几种方法可以解决这个问题:
希望这有帮助:-)
# 3 楼答案
你必须使用
<
而不是<=
。在您的代码中,如果grades1
的大小为10,您将尝试在循环结束时获取grades1[10]
,而只能从0到9