CompareTo LinkedList greatest volume java

Viewed 38

I file read a file with width height and length to a linked list of objects and now I have to find which object from the linked list has the greatest and smallest volume. I tried doing this for the greatest method but I get this error: Exception in thread "main" java.lang.ClassCastException: class java.lang.Double cannot be cast to class Box (java.lang.Double is in module java.base of loader 'bootstrap'; Box is in unnamed module of loader 'app'). Which I think it's because what I am comparing is wrong I am not sure what to compare. And this does have to be done with the compareTo method I have

UPDATE: I have change the compares to head and head.next and now it is printing the correct volume but it is printing null after it how can I remove that. And for the smaller method it is printing an extra volume line when it's only supposed to be one and a nullpointerexception message

static void largestBox(Box head){
     while(head != null){
        if (head.next.compareTo(head) > 0){
            head = head.next;
            System.out.println(head.next);
        }
        head = head.next;
    }

}
    class Box {
      private double width, height, length;
      public Box next;

    Box(double w, double h, double l){
        width=w;
        height=h;
        length=l;
    }

    double getVolume(){
       return width*height*length;
    }

    public int compareTo(Object o){    
      double vol1 = this.getVolume();
      double vol2 = ((Box)o).getVolume();
      if (vol1>vol2)
        return 1;
      else if (vol1<vol2)
         return -1;
      else
        return 0;
    }
 }
2 Answers

if(head.next.compareTo(bigVolume) > 0)

You are trying to compare a Box (head.next) to a double (bigVolume). This line should instead look like if (head.next.compareTo(head)), which will let you compare boxes instead of a volume and a Box. This should get you on the right track, but I will warn you I see other issues with your code.

Change:

double bigVolume = head.getVolume();  

To:

Box biggestBox = head;  

And change

if (head.next.compareTo(bigVolume) > 0) {

To

if (head.next.compareTo(biggestBox) > 0) {

There's another bug in your code. Change:

while (head != null) {

to:

while (head.next != null) {

Also, you're always printing System.out.println(head); not matter what is the biggest box. Change it to System.out.println(biggestBox);

Related