您得到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++)
希望這有助於:-)
閱讀此異常 – Dici 2014-12-03 22:41:57
的文檔的終止語句應該比,而不是更少少用大於或等於。 – August 2014-12-03 22:42:17
爲什麼在這個問題上有一個倒退? – 2014-12-03 22:44:44