2012-11-17 63 views
1

你會檢查我的方法,讓我知道我做錯了什麼?謝謝:)String.compareTo方法比較

public static void sortByVehicleMakeModel(Vehicle[] vehicles) { 
    boolean swapped = true; 

    for(int y = 0; y < vehicles.length && swapped; y++) { 
     swapped=false; 
     for(int x = 0; x < vehicles.length - (y+1); x++) { 
      if(vehicles[x].getMake() && vehicles[x].getModel().compareTo(vehicles[x + 1].getMake() && vehicles[x].getModel())) {  
       swap(vehicles, x, x + 1); 
       swapped=true; 
      } 
     } 
    } 
} 

我的錯誤是在第二條語句.compareto() 操作& &未定義的參數類型java.lang.String中,java.lang.String中

但是,此代碼工作得很好:

public static void sortByOwnerName(Vehicle[] vehicles) { 
    boolean swapped = true; 

    for(int y = 0; y < vehicles.length && swapped; y++) { 
     swapped=false; 
     for(int x = 0; x < vehicles.length - (y + 1); x++) { 
      if(vehicles[x].getOwner().getName().compareTo(vehicles[x + 1].getOwner().getName())> 0) { 
       swap(vehicles, x, x + 1); 
       swapped=true; 
      } 
     } 
    } 
} 
+0

該方法稱爲sortByVehicleCost,但您正在與getMake()&getModel()進行比較。你能澄清你想達到的目標嗎? – threenplusone

+3

如果您只是尋求建設性的批評,您可能想嘗試http://codereview.stackexchange.com/。如果它沒有按照你期望的方式工作,或者你不明白它的工作方式,那麼詳細說明你正在得到什麼,什麼是不可預料的,你期待什麼等。 – EdC

+0

mytypo,對不起! – NilR

回答

1

我建議增加一個int getCost()到車輛對象,然後使用類似vehicles[x].getCost() > vehicles[x - 1].getCost()您的if語句。

此外,這種不是很有效。可能Vehicle應該執行Comparable並使用Collections.sort()進行排序。


只是閱讀您的問題的更新。

試試這個:

if (vehicles[x].getMake().compareTo(vehicles[x - 1].getMake()) < 0 || 
    (vehicles[x].getMake().compareTo(vehicles[x - 1].getMake()) == 0 && 
    vehicles[x].getModel().compareTo(vehicles[x - 1].getModel()) < 0)) { 
+0

我不知道這事,但是我的教授要求:( – NilR

+0

我知道它必須是這樣的,但我無法弄清楚它! :D你真棒;)謝謝你的幫助! – NilR

0

如果getMake()和/或getModel()比布爾返回另一種類型的,比你在這裏有一個錯誤。

+0

你是什​​麼意思?bcoz品牌和型號是字符串! – NilR

+0

你不能有字符串&&字符串。「兩個操作數到&&是布爾」 – dreamcrash

+0

嗯,好的,讓我試試吧! – NilR

1

兩個操作數到&&的必須是boolean表達式(無論是truefalse):

在遵循它們中的一個或兩者都是String

vehicles[x].getMake() && vehicles[x].getModel().compareTo(vehicles[x + 1].getMake() && vehicles[x].getModel()) 

而不是試圖將Vehicle對象與邏輯排序,你應該做一個比較爲您Vehicle

public class VehicleComparator implements Comparator<Vehicle> { 
    //... 
    public int compare(Vehicle v1, Vehicle v2) { 
     //.. 
    } 
} 

而且使用使用Arrays.sort()方法。

Arrays.sort(vehicles, new VehicleComparator()); 
0

爲了執行compareTo()方法,你必須實現Comparable<Type>接口和覆蓋

public int compareTo(T o); 

方法將返回所以不是

vehicles[x].getModel().compareTo(vehicles[x + 1.... 

你應該放置

vehicles[x].getModel().compareTo(vehicles[x + 1.... > -1 // or any constant which you want to say as invalid. 

那麼只有工作

希望這會幫助你。

+0

不,錯誤是一樣的(運算符&&未定義爲參數類型java.lang.String,) – NilR

+0

請放置Vehicle類的代碼。 –