這樣為什么運行不了
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
a[i]<a[i+1]這一行,你這個外面的for循環(huán)是i < a.length;那你這個a[i+1]就取不到了,所以會報錯。
就算解決了報錯,你這個也不能滿足題目的要求,你可以走一遍:89和0,89勝出,a數組第一個是89,此時開始判斷0和64了,a數組第二個就是64了,然后是64和91比較,第三個就是91了,有沒有發(fā)現哪里不對?