Dan*_*ani 0 java arrays sorting methods object
我有一个数据文件,我需要通过Make && Model of vehicle对信息进行排序.我的bubbleort不起作用,你能帮我解决我的问题吗?非常感谢你!PS我不能有额外的方法:(如果我删除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());
}
}
Run Code Online (Sandbox Code Playgroud)
请按照以下步骤比较两辆车:
您应该使用使用上述逻辑比较两个Vehicle的方法替换if语句中的代码.
像这样的东西:
if (compareVehicles(vehicles[x], vehicles[x + 1]) > 0) {
swap(vehicles, x, x + 1);
}
Run Code Online (Sandbox Code Playgroud)
要以正确的方式执行此操作,您应该使Vehicle实现可比较.
这样你就可以将上面的逻辑放在compareTo方法中.
这将允许您简单地执行此操作:
if (vehicles[x].compareTo(vehicles[x + 1]) > 0) {
swap(vehicles, x, x + 1);
}
Run Code Online (Sandbox Code Playgroud)
这是一个如何实现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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
好的...因为已经有几天了,我只会告诉你如何做到这一点.
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());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
622 次 |
| 最近记录: |