原始类型双重错误

时间:2012-11-17 06:37:32

标签: java compareto

抱歉,如果我的问题看起来非常愚蠢。我得到错误.compareTo()无法在基本类型double上调用compareTo(double)!我怎样才能解决这个问题 ?谢谢!

车辆类:

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;
            }
        }
    }
}

6 个答案:

答案 0 :(得分:3)

getCost()方法的返回类型从double更改为Double,这样做一切正常。自动拳击将照顾其余部分。

答案 1 :(得分:1)

if(vehicles[x].getCost().compareTo(vehicles[x + 1].getCost()))

你在某处需要>0

答案 2 :(得分:1)

对于premitive类型,

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; 
}