车辆类:
public class Vehicle implements IOutput {
private double cost;}
public double getCost(){
return cost;
}
数组类:
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].getCost().compareTo(vehicles[x + 1].getCost()) > 0){
swap(vehicles, x, x + 1);
swapped=true;
}
}
}
}
我的其他代码工作正常:
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 :(得分:3)
将getCost()
方法的返回类型从double
更改为Double
,这样做一切正常。自动拳击将照顾其余部分。
答案 1 :(得分:1)
if(vehicles[x].getCost().compareTo(vehicles[x + 1].getCost()))
你在某处需要>0
!
答案 2 :(得分:1)
compareTo
方法不可用。使用Wrapper Double
作为:
if(Double.valueOf(vehicles[x].getCost())
.compareTo(Double.valueOf(vehicles[x + 1].getCost()))>0){
请注意:Double.valueOf(double)会返回包含类型Double
,其值为double
。
请注意:如果您的目标是使用compareTo
,那么就可以了,否则您可能需要使用比较运算符double
直接比较<, >, ==
值合适的。
答案 3 :(得分:0)
您只能在引用类型上调用方法,double
是基本类型。正如错误消息所示,vehicles[x].getCost()
会返回double
。
您可以做的一件事是将double
手动打入Double
:
int costComp = Double.valueOf(vehicles[x].getCost()).compareTo(Double.valueOf(vehicles[x + 1].getCost());
if(costComp < 0) {
//...
} else if(costComp == 0) {
//...
} else {
//...
}
答案 4 :(得分:0)
您的此代码可以正常使用
if(vehicles[x].getOwner().getName().compareTo(vehicles[x+1].getOwner().getName())> 0)
因为vehicles[x+1].getOwner().getName()
必须返回String
的对象而compareTo
方法接受一个对象作为参数。
此代码不起作用
if(vehicles[x].getCost().compareTo(vehicles[x + 1].getCost()))
因为vehicles[x + 1].getCost()
一定不能返回一个对象(在你的情况下它必须返回一个原语double
)所以类型不匹配,编译器抱怨没有这样的{{1接受compareTo
(原始)
答案 5 :(得分:0)
我将其更改为:
public Double getCost()
而不是
public double getCost(){
return cost;
}