I need to implement a comparable interface into my code so I can compare multiple bits of information from my ArrayList e.g. height. Once I have this working I need to be able to call it in a switch statement. I think I've got the comparable interface bit working however it's showing up an error message when I try to call it in the switch statement. Does anyone have any ideas as to why this is/how I can fix it? I've just attached the relevant code but please say if I need to attach more.
Comparable Interface
public class Superhero implements Comparable<Superhero> {
public int compareTo(Superhero other) {
return Integer.compare(this.height, other.height);
}
Switch Statement
case 5:
System.out.println(sortMenu());
int val = input.nextInt();
switch (val) {
//HEIGHT
case 6:
System.out.println(Superhero.compareTo());
}
break;
EDIT
error message when I run the code added below:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: <any>
at heros.java.Heros.main(Heros.java:54)
Java Result: 1
compiler error message:
method compareTo in class Superhero cannot be applied to given types;
require: Superhero
found: no arguments
reason: actual and formal argument lists differ in length
You have correctly identified that your problem is in this snippet of code:
case 5:
System.out.println(sortMenu());
int val = input.nextInt();
switch (val) {
//HEIGHT
case 6:
System.out.println(Superhero.compareTo());
}
break;
It's on this line:
System.out.println(Superhero.compareTo());
In this expression:
Superhero.compareTo()
Superhero looks like a variable here (variables should start with lowercase, so that is confusing) and you need to supply another Superhero object to it as follows:
Superhero anotherSuperhero = new Superhero();
System.out.println(Superhero.compareTo(anotherSuperhero));