我的思路跟答案不同,但是冒泡法部分有點問題
代碼及思路如下:
public class HelloWorld {
? ??
? ? //完成 main 方法
? ? public static void main(String[] args) {
? ? ? ??
? ? int scores[] = {89,-23,64,91,119,52,73};
? ? HelloWorld arr = new HelloWorld();
? ? arr.showTop3(scores);
? ? }
? ??
? ? //定義方法完成成績排序并輸出前三名的功能
? ??
? ? public void showTop3(int[] scores){
? ? ? ? int tempDataBox[] = {0,0,0,0,0,0,0};
? ? ? ? for (int i = 0;i < tempDataBox.length;i++){
? ? ? ? ? ? if (scores[i] < 100 && scores[i] > 0){
? ? ? ? ? ? ? ? tempDataBox[i] = scores[i];
? ? ? ? ? ? ? ? //System.out.println(tempDataBox[i]);
? ? ? ? ? ? ? ? }
? ? ? ? }
? ? ? ??
? //關(guān)尹子注:
? //解決思路與題設(shè)不同。
? /*1 初始化一個數(shù)組,存儲預(yù)定成績。
? ? 2 初始化一個臨時數(shù)組,全部設(shè)置為0。判斷最初數(shù)組中數(shù)字有效性,如果有效就把值賦予臨時數(shù)組中對應(yīng)下標的元素。
? ? 3 利用冒泡法,對臨時數(shù)組進行排序。
? ? 4 輸出最大的三個值。
? ? 問題:冒泡法寫不出來了。*/
? ? for (int j = 0;j < tempDataBox.length - 1;j++){
? ? ? ? ? ? for(int k = 0;k < tempDataBox.length - 1 - j;k++){
? ? ? ? ? ? ? ? if (tempDataBox[k] < tempDataBox[ k + 1])
? ? ? ? ? ? ? ? int temp = tempDataBox[k];
? ? ? ? ? ? ? ? tempDataBox[k] = tempDataBox[k + 1];
? ? ? ? ? ? ? ? tempDataBox[k + 1] = temp;
? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? System.out.println("排序后的前三位成績?yōu)椋?+tempDataBox[4]+tempDataBox[5]+tempDataBox[6]);
? ? ? ? ? ? }
? ? ? ? ? ?
? ? ? ? ? ??
? ? ? ? }
? ??
? ? }
? ??
}
問題:
報錯,提示 冒泡法過程中 temp不能被聲明,不知道為什么?求大神賜教。
2019-04-18
自問自答:
錯誤一:冒泡法部分的if語句,沒有大括號。
錯誤二:冒泡法的寫法,與正常人思路不一致。
目前雖然最后已經(jīng)編譯通過了,但是冒泡法寫的很擰巴。