你能检查一下我的方法并让我知道我做错了什么吗?谢谢你:)
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;
}
}
}
}
最佳答案
我建议将 int getCost()
添加到 Vehicle 对象,然后使用 vehicles[x].getCost() > cars[x - 1].getCost()
用于 if 语句。
而且,这种排序效率不是很高。也许车辆应该实现 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)) {
关于java - String.compareTo方法进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13428071/