繁体   English   中英

基本类型双重错误

[英]primitive type double error

对不起,如果我的问题看起来很愚蠢。 我在.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;
            }
        }
    }
}

将您的getCost()方法的返回类型从double更改为Double ,这将正常工作。 自动装箱将解决其余问题。

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

您需要在某处>0

compareTo方法在本地类型上不可用。 使用Wrapper Double作为:

     if(Double.valueOf(vehicles[x].getCost())
          .compareTo(Double.valueOf(vehicles[x + 1].getCost()))>0){

请注意: Double.valueOf(double)返回包装类型Double ,其值为double

请注意:如果您的目标是使用compareTo那么就可以了,否则,您可能需要使用比较运算符<, >, ==直接比较double值。

您只能在引用类型上调用方法, double是原始类型。 如错误消息所示, vehicles[x].getCost()返回double

有一两件事你可以做的是手工打你doubleDouble

int costComp = Double.valueOf(vehicles[x].getCost()).compareTo(Double.valueOf(vehicles[x + 1].getCost());

if(costComp < 0) {
    //...
} else if(costComp == 0) {
    //...
} else {
    //...
}

您的这段代码可以正常工作

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 ),所以类型不匹配,并且编译器抱怨没有可以接受double compareTo方法(原始)

我将其更改为:

public Double getCost() 

代替

public double getCost(){ 
return cost; 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM