2014-12-03 51 views
-1
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

阅读此异常 – Dici 2014-12-03 22:41:57

+2

的文档的终止语句应该比,而不是更少少用大于或等于。 – August 2014-12-03 22:42:17

+0

为什么在这个问题上有一个倒退? – 2014-12-03 22:44:44

回答

3

你必须使用<而不是<=。在你的代码,如果grades1的大小为10,你会尝试在你的循环结束时获得grades1[10],而你只能从0到9

private void setAverage(int[] grades1) { 
    for(int i = 0; i < grades1.length; i++){ 
     avg += grades1[i]; 
    } 
    System.out.println(avg);  
} 
0
private void setAverage(int[] grades1) { 

for(int i = 0; i < grades1.length; i++){ 
    avg += grades1[i]; 
} 

System.out.println(avg);  
} 

例如你有一个长度为3的数组,那么你有索引0,1,2。 您不能试图索引3

0

您得到ArrayIndexOutOfBoundsException: 3,因为您的代码试图访问数组中不存在的grades1[3]元素。让我们来仔细看看:

您的数组的长度是3。这意味着您的阵列开始于index 0并结束于index 2 ------->[0, 2]。如果您计算数字0, 1, 2,,您会得到3这是长度。

现在,您的for循环中的逻辑关闭。你从i = 0开始到i <= 3。当您在for循环中访问grades1[i]时,您访问每个元素i,直到条件为假。

// iteration 1 
for(int i = 0; i <= grades1.length; i++){ 
     avg += grades1[i];// accesses grades1[0] 
    } 
------------------------------------------------- 
// iteration 2 
for(int i = 0; i <= grades1.length; i++){ 
     avg += grades1[i];// accesses grades1[1] 
    } 
------------------------------------------------- 
// iteration 3 
for(int i = 0; i <= grades1.length; i++){ 
     avg += grades1[i];// accesses grades1[2] 
    } 
------------------------------------------------- 
// iteration 4 
for(int i = 0; i <= grades1.length; i++){ 
     avg += grades1[i];// tries to access grades1[3] which does not exist 
    } 
------------------------------------------------- 

有一对夫妇的方式来解决这个问题:

1. for (int i = 0; i < grades1.length; i++) 

2. for (int i = 0; i <= grades1.length - 1; i++) 

希望这有助于:-)