2014-12-03 66 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++) 

希望這有助於:-)