Reputation: 533
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;
}
}
}
}
Upvotes: 2
Views: 14463
Reputation: 533
I changed this to :
public Double getCost()
instead of
public double getCost(){
return cost;
}
Upvotes: 0
Reputation: 424993
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.
Upvotes: 3
Reputation: 34367
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.
Upvotes: 1
Reputation: 51030
You can only invoke methods on a reference type, double
is a primitive type. As the error message suggests vehicles[x].getCost()
returns a double
.
One thing you can do is manually box your double
into Double
:
int costComp = Double.valueOf(vehicles[x].getCost()).compareTo(Double.valueOf(vehicles[x + 1].getCost());
if(costComp < 0) {
//...
} else if(costComp == 0) {
//...
} else {
//...
}
Upvotes: 0
Reputation: 15644
This code of yours works fine
if(vehicles[x].getOwner().getName().compareTo(vehicles[x+1].getOwner().getName())> 0)
because vehicles[x+1].getOwner().getName()
must be returning an object of String
and compareTo
method accepts an object as an argument.
This code doesn't work
if(vehicles[x].getCost().compareTo(vehicles[x + 1].getCost()))
because vehicles[x + 1].getCost()
must not be returning an object( in your case it must be returning a primitive double
) so there is mismatch in the type and the compiler complains that there is no such compareTo
method that accepts double
(a primitive)
Upvotes: 0
Reputation: 19302
if(vehicles[x].getCost().compareTo(vehicles[x + 1].getCost()))
You need >0
in there somewhere!
Upvotes: 1