關于數(shù)組越界的問題
package?com.test3; /* ?*? ?*?功能:輸出保存在數(shù)組中的前三名 ?*/ import?java.util.Arrays; public?class?test8?{ /** ?*?@param?args ?*/ public?static?void?main(String[]?args)?{ //?TODO?Auto-generated?method?stub int?[]scores?=?{?89?,?-23?,?64?,?91?,?119?,?52?,?73}; ????????test8?sys?=?new?test8(); ????????sys.getScore(scores); } public?int[]?getScore(int?score[]){ Arrays.sort(score); int?count?=?0; for(int?i=score.length;i>=0;i--){ if((score[i]>100)||(score[i]<0)){ continue; } count++; if(count>3){ break; } System.out.println("考試成績的前三名為:"); System.out.println(score[i]); } return?score; } }
我想要輸出保存在數(shù)組中的前三名的成績,可是eclipse提示數(shù)組越界呢,這是為什么呢?
這是運行結(jié)果:
2016-03-27
因為第一個數(shù)組的下標是從0開始的,如果你訪問score.length的話,會超出了數(shù)組的長度。從1到score.length的長度是score.length,但是數(shù)組從0開始,訪問score.length的話,相當于訪問了第score.length+1,所以會出現(xiàn)訪問數(shù)組越界Exception
2016-03-23
for(int?i=score.length-1;i>=0;i--)