primitive type double error
Solution 1
Change the return type of your getCost()
method from double
to Double
and it will all work. Auto boxing will take care of the rest.
Solution 2
if(vehicles[x].getCost().compareTo(vehicles[x + 1].getCost()))
You need >0
in there somewhere!
Solution 3
compareTo
method is not available on premitive type. Use Wrapper Double
as:
if(Double.valueOf(vehicles[x].getCost())
.compareTo(Double.valueOf(vehicles[x + 1].getCost()))>0){
Please Note: Double.valueOf(double) returns the Wrapper type Double
with value as double
.
Please Note: If your objective is to use compareTo
then its fine otherwise, you may want to directly compare double
values using comparison operators <, >, ==
as appropriate.
SamR
Updated on July 24, 2022Comments
-
SamR almost 2 years
sorry if my question looks very stupid. I get error on .compareTo() Cannot invoke compareTo(double) on the primitive type double! how can i fix this ? Thank you!
Vehicle class:
public class Vehicle implements IOutput { private double cost;} public double getCost(){ return cost; }
Array Class:
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; } } } }
my other codes works fine:
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; } } } }