Java String.compareTo要比较的方法

Java String.compareTo要比较的方法,java,compareto,Java,Compareto,你能检查一下我的方法,让我知道我做错了什么吗?谢谢:) 公共静态无效sortByVehicleMakeModel(车辆[]车辆){ 布尔交换=真; 对于(int y=0;y

你能检查一下我的方法,让我知道我做错了什么吗?谢谢:)

公共静态无效sortByVehicleMakeModel(车辆[]车辆){
布尔交换=真;
对于(int y=0;y
我的错误在第二条语句中。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;
            }
        }
    }
}
公共静态无效sortByOwnerName(车辆[]车辆){
布尔交换=真;
对于(int y=0;y0{
互换(车辆,x,x+1);
交换=真;
}
}
}
}

&&
的两个操作数必须是
布尔表达式(要么
要么
):

在下面的示例中,它们中的一个或两个都是
String

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

与其尝试使用该逻辑对
车辆
对象进行排序,不如为
车辆

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

我建议在Vehicle对象中添加一个
int getCost()
,然后在if语句中使用类似
vehicles[x].getCost()>vehicles[x-1].getCost()

而且,这种方法效率不高。也许车辆应该实施并使用
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)) {
if(车辆[x].getMake().compareTo(车辆[x-1].getMake())<0|
(车辆[x].getMake().compareTo(车辆[x-1].getMake())==0&&
车辆[x].getModel().compareTo(车辆[x-1].getModel())<0){

要实现
compareTo()
方法,必须实现
Comparable
接口和覆盖

public int compareTo(T o);
方法,该方法将返回so而不是

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.
那就只有工作了


希望这能对您有所帮助。

该方法名为sortByVehicleCost,但您正在与getMake()和getModel()进行比较.你能澄清你想要达到的目标吗?如果你只是寻求建设性的批评,你可能想尝试一下。如果它没有按照你期望的方式工作,或者你不了解它的工作方式,那么详细说明你得到了什么,什么是不期望的,你期望的等等。你的汽车成本中有哪些因素和型号?书面形式e你的车辆类getMake()和getModel()返回什么?Int、String、objects等?不,错误是相同的(运算符&未定义参数类型java.lang.String),我不知道,但我的教授要求它:(我知道它必须是这样的,但我无法理解!)谢谢你的帮助!
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.