我將問題發生點與解決辦法寫在註解裡....
你自己去看看吧.....
複製程式
public class E9430068{
public static void main (String[] args){
double week [] []={{18.2,17.3,15.0,13.4,0},
{23.8,25.1,20.6,17.8,0},
{20.6,21.5,18.4,15.7,0}}; //所輸入的質,後面之所以會多各0是為了補足AVG/4的不足
String n[] ={"早上","中午","晚上"};
System.out.println("未排序");
System.out.println("時段"+"\t"+"星期一"+"\t"+"星期二"+"\t"+"星期三"+"\t"+"星期四"+"\t"+"平均氣溫");
System.out.println("------"+"\t"+"------"+"\t"+"------"+"\t"+"------"+"\t"+"------"+"\t"+"--------");
for(int i=0;i<week.length;i++){
double avg=0; //先宣告平均數
System.out.print(n[ i ]+"\t");
for(int j=0;j<week[ i ].length-1;j++){ //因為前面有字串有補0,所以要減回來
System.out.print(week[ i ][j]+"\t");
avg+=week[ i ][j]; //宣告平均數的加總
}
week[ i ][4]=avg/4;
System.out.println(week[ i ][4]); //avg/ 後面為天數
}
do //要加一個迴圈...沒加的話則泡沫排序只排序一次
{
for (int k=week.length-1;k>=0;k--)
{
for (int l=0;l<=week.length-1;l++) //這邊有錯....k需改成week.length-1
{
if (week[k][l] > week[k][l+1])//當原數值大於後數值時
{ //進行交換
//這邊也有錯....k+1需改成l+1
double temp=week[k][l];
week[k][l] = week[k][l+1];
week[k][l+1] = temp;
}
}
}
}while(week[0][0] > week[0][1]);//由於你是main函式包含所有功能,
//所以無法使用遞迴(recursive),只好用這個有點偷吃步的方式解決了...
System.out.println(); //此為空行
System.out.println("排序後");
System.out.println("時段"+"\t"+"星期一"+"\t"+"星期二"+"\t"+"星期三"+"\t"+"星期四"+"\t"+"平均氣溫");
System.out.println("------"+"\t"+"------"+"\t"+"------"+"\t"+"------"+"\t"+"------"+"\t"+"--------");
for (int k=0;k<week.length;k++){
System.out.print(n[k]+"\t");
for (int l=0;l<week[k].length;l++)
System.out.print(week[k][l]+"\t");
System.out.println();
}
}
}