這樣為什么運(yùn)行不了
public class HelloWorld {
? ??
? ? //完成 main 方法
? ? public static void main(String[] args) {
? ? int []scores= { 89 , -23 , 64 , 91 , 119 , 52 , 73};
? ? ?HelloWorld hello=new HelloWorld();
? ? ?hello.set(scores);
? ? ? ??
? ? ? ??
? ? }
? ??
? ? //定義方法完成成績排序并輸出前三名的功能
? ? public void set(int []a)
? ? {
? ? ? ??
? ? ? ? int temp;
? ? ? ? for(int j=0;j<a.length;j++)
? ? ? ? {
? ? ? ? ? ? if(a[j]<0)
? ? ? ? ? ? a[j]=0;
? ? ? ? }
? ? ? ? for(int i=0;i<a.length;i++)
? ? ? ? {
? ? ? ? ? ??
? ? ? ? ? ? if (a[i]<a[i+1])
? ? ? ? ? ? {
? ? ? ? ? ? temp=a[i];
? ? ? ? ? ? a[i]=a[i+1];
? ? ? ? ? ? a[i+1]=temp;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? System.out.println("考試成績的前三名為:");
? ? ? ? System.out.println(a[0]);
? ? ? ? System.out.println(a[1]);
? ? ? ? System.out.println(a[2]);
? ? }
? ??
? ??
? ??
? ??
? ??
? ??
? ??
? ??
}
2019-05-23
當(dāng) i = a.length -1 的時候,a[i + 1] 也就是 a[a.length] 是沒有值的,直接超出內(nèi)存范圍了所以報錯。另外,你這個排序算法不對,你這個不是冒泡排序,你這個只是如果兩個數(shù)比一下,小的放到前面,大的放到后面,冒泡排序是兩層循環(huán)。