搞不清出了什么問題,求大神
public class hallo {
public static void main(String[] args){
?int i,j,k;
?int score[]={89,-23,64,91,119,52,73};
?for(i=0;i<7;i++){
?for(j=0;j<7;j++){
?if(score[j]<score[j+1]){
?k=score[j];
?score[j+1]=score[j];
?score[j+1]=k;
? }
?}
? }for(i=0;i<3;i++)
System.out.println("score[i]");
? }
}
出現(xiàn)Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7怎么解決
2016-01-31
這個報錯是說數(shù)組下表超出范圍,以后記住這個關鍵詞“ArrayIndexOutOfBounds”(數(shù)組索引超出界限)。
那么問題在哪里呢?看了下你寫這個程序目的是想比對score[j]<score[j+1]時,將數(shù)組值對調位置,實現(xiàn)排序目的。但是試想一下,數(shù)組數(shù)量是7個,下標是0到6,那你循環(huán)了7次,最后一次下標是6,就出現(xiàn)了score[6]<score[7],請問哪里有score[7]?
for(i = 0; i < 7; i++){
???for(j = 0; j < 7; j++){
將這里的7改成6就不會報錯,但是這個程序來看是有問題的計算出來的結果并不數(shù)你想要的排序。
在JAVA里有一個方法可以直接對數(shù)組排序,java.uitl.Arrays里面的sort()方法,你可以看看第6章6-7節(jié)的內容。
2016-01-31