代碼驗證對的,但是找運行不出結果
老師好,沒找出原因,哪里不對
import java.util.Arrays;
public class HelloWorld {
? ??
? ? //完成 main 方法
? ? public static void main(String[] args) {
? ? int[] scores = {89,-23,64,91,119,52,73};
? ? System.out.println("考試成績前三名:");
? ?HelloWorld hello = new HelloWorld();
? ?hello.showTop3(scores);
}
? ? //定義方法完成成績排序并輸出前三名的功能
? ? public void showTop3(int[] scores)
? ? {
? ? ? ? Arrays.sort(scores);//使用Arrays.sort的方式實現數組排序
? ? ? ? int num = 0;
? ? ? ? for(int i = scores.length;i>=0;i--)
? ? ? ? {
? ? ? ? ? ? if(scores[i]<0||scores[i]>100) ? ?// 判斷成績的有效性
? ? ? ? ? ? {
? ? ? ? ? ? ? ? continue; //如果成績無效,則退出本次循環,忽略此成績
? ? ? ? ? ? }
? ? ? ? ? ? num++;
? ? ? ? ? ? if(num>3)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? ? ? System.out.println(scores[i]); ? ? ??
? ? ? ? }
? ? }
}
運行結果:
考試成績前三名:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at HelloWorld.showTop3(HelloWorld.java:19)
at HelloWorld.main(HelloWorld.java:10)
2015-08-08
(int i = scores.length;i>=0;i--)這里有問題。因為數組下標的取值范圍是0到scores.length-1