2

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?

public static void
  • 95
  • 1
  • 6
  • 13

3 Answers3

6

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 >=.

rgettman
  • 176,041
  • 30
  • 275
  • 357
2

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

doc
  • 765
  • 1
  • 6
  • 24
1

double is a primitive type, not a class : it has not method. You should be using Double instead... and reviewing the basics in Java. Not to be offensive, but the thing is that you need the basics to efficiently program.

PS : you can also use the static method Double.compare

Dici
  • 25,226
  • 7
  • 41
  • 82