package com.Java;
import java.util.Arrays;
public class HelloWorld {
public static void main(String[] args) {
int[] scores = {89 , -23 , 64 , 91 , 119 , 52 , 73};
System.out.println("成绩前三名为:");
HelloWorld hello = new HelloWorld();
hello.sortAndPrint(scores);
}
public void sortAndPrint(int[] scores){
Arrays.sort(scores);
int num=0;
for (int i=scores.length ;i>=0;i--){
if (scores[i]>0 && scores[i]<=100){
System.out.println(scores[i]);
num++;
} else {
continue;
}
if (num==3){break;}
}
}
}
运行结果
成绩前三名为:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at com.Java.HelloWorld.sortAndPrint(HelloWorld.java:27)
at com.Java.HelloWorld.main(HelloWorld.java:15)
下标越界
length-1
找到错误了,当数组有7个数的时候,scores.length=7,而数组中最高分的 数是 scores[6],
所以 int i=scores.length-1