I need to make a program that uses compareTo, but I'm running into issues with it.
double sides1 = 1.0;
double sides2 = 1.3;
int compared = sides1.compareTo(sides2);
I always run into an error that says
Cannot invoke compareTo(double) on the primitive type double
What am I doing wrong, and how do I fix it?
You cannot call methods on primitive values such as doubles. But you can call Double.compare, which will compare two primitive doubles for you.
int compared = Double.compare(sides1, sides2);
You can also compare primitive double values directly with the comparison operators ==, !=, <, <=, > and >=.
A primitive type is not a Java Object and so the method compareTo does not exist. Use the Java Object Double and not the primitive type:
Double sides1 = Double.valueOf(1.0);
Double sides2 = Double.valueOf(1.3);
int compared = sides1.compareTo(sides2);
Edit - do not take from that that all Java Objects have the compareTo(..) method. The compareTo(..) is part of the Comparable Interface https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With