2012-11-17 65 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类的代码。 –