package demo;import java.util.Arrays;public class HelloWorld { public static void main(String[] args){ HelloWorld hello=new HelloWorld(); int[] score={89 , -23 , 64 , 91 , 119 , 52 , 73}; hello.test(score); } public void test(int[]score){ Arrays.sort(score); int number=0; for(int i=score.length-1;i>=0;i--){ if(score[i]<=0 || score[i]>=100){ continue; } number++; if(number>3){ break; } System.out.println(score[i]); } } }?for循環之前雖然經過sort方法進行排序過. 但是for循環為什么 i=score.length還要-1? 看不明白. 求解答
3 回答

慕粉3233872
TA貢獻70條經驗 獲得超29個贊
數組下標是從0開始排序的。
例如int[] score={89 , -23 , 64 , 91 , 119 , 52 , 73};
score[0]=89,score[1]=-23,score[6]=73.
length是獲取數組長度的,從1開始數,這里的score.length=7
所以score[6]=score[score.length-1]=73

yanrun
TA貢獻317條經驗 獲得超240個贊
這個和有沒有排序是無關的,i=score.length-1是因為數組的下標是從0開始的,也就是說你的score數組的下標是從0到6的,而數組的長度為7,如果不減1,就會出現score[7],而數組中并不存在這個元素,會拋出數組下標越界異常
添加回答
舉報
0/150
提交
取消