我有一个数据文件,我需要通过Make&& Model of vehicle对信息进行排序。我的bubbleort不起作用,你能帮我解决我的问题吗?非常感谢你! 附:我不能有额外的方法:(如果我删除getMake()方法,它可以工作,但&& getModel根本不起作用:(
public static void sortByVehicleMakeModel(Vehicle[] vehicles) {
for(int y = 0; y < vehicles.length; y++) {
for (int x = 0 ; x < vehicles.length - 1 ; x++){
if((vehicles[x].getMake().compareToIgnoreCase(vehicles[x+1].getMake()) > 0) && (vehicles[x].getModel().compareToIgnoreCase(vehicles[x+1].getModel()) > 0)) {
swap(vehicles, x, x + 1);
}
}
}
for(int x = 0; x < vehicles.length - 1; x++){
System.out.println(vehicles[x].getMake());
}
}
答案 0 :(得分:5)
按照以下步骤比较两辆车:
您应该使用上述逻辑比较两辆车的方法替换 if语句中的代码。
这样的事情:
if (compareVehicles(vehicles[x], vehicles[x + 1]) > 0) {
swap(vehicles, x, x + 1);
}
要以正确的方式执行此操作,您应该使 Vehicle 实现 Comparable 。
通过这种方式,您可以将上述逻辑放在 compareTo 方法中。
这将允许您简单地执行此操作:
if (vehicles[x].compareTo(vehicles[x + 1]) > 0) {
swap(vehicles, x, x + 1);
}
以下是如何实现Comparable的简单示例:
class Vehicle implements Comparable<Vehicle> {
private String make;
private String model;
public int compareTo(Vehicle other) {
if (other == null) {
return -1;
}
int compareVal = make.compareToIgnoreCase(other.make);
if (compareVal == 0) {
return model.compareToIgnoreCase(other.model);
}
else {
return compareVal;
}
}
}
好的...因为已经过了几天,我只会告诉你如何做到这一点。
public static void sortVehicles(Vehicle[] vehicles) {
for (int i = 0; i < vehicles.length - 1; i++) {
Vehicle curr = vehicles[i];
Vehicle next = vehicles[i + 1];
String currMake = curr.getMake();
String nextMake = next.getMake();
int compareVal = currMake.compareToIgnoreCase(nextMake);
// if the makes are the same, we need to compare the models
if (compareVal == 0) {
String currModel = curr.getModel();
String nextModel = next.getModel();
compareVal = currModel.compareToIgnoreCase(nextModel);
}
if (compareVal > 0) {
swap(vehicles, i, i + 1);
}
}
for (Vehicle v : vehicles) {
System.out.println(v.getMake());
}
}
答案 1 :(得分:2)
只是为了提高性能(我意识到比较逻辑,@ jahroy是对的)。我认为第二个循环的代码应该如下所示: x&lt; vehicles.length - y -1
for(int y = 0; y < vehicles.length; y++) {
for (int x = 0 ; x < vehicles.length - y -1 ; x++){
if((vehicles[x].getMake().compareToIgnoreCase(vehicles[x+1].getMake()) > 0) && (vehicles[x].getModel().compareToIgnoreCase(vehicles[x+1].getModel()) > 0)) {
swap(vehicles, x, x + 1);
}
}
}
答案 2 :(得分:0)
这是我如何解决它:
public static void sortByVehicleMakeModel(Vehicle[] vehicles) {
for(int y = 0; y < vehicles.length; y++) {
for (int x = 0 ; x < vehicles.length - 1 ; x++){
boolean compare1 = (vehicles[x].getMake().compareToIgnoreCase(vehicles[x+1].getMake()) > 0);
if (compare1){
swap(vehicles, x, x + 1);
}
}
}