I'm learning basic Java right now and have a problem with my code that I can't figure out. It's basically what the title says. My Java compiler is telling me that there's an error with my custom compareTo method, saying that it needs to return an int. The problem is, as far as I can tell, it IS returning an int. Yet it's still giving me an error. Could someone please point out in my code what's wrong? And also I have already implemented Comparable in my class. Here's my method:
public int compareTo(Homework other) {
if (getDaysLate() < other.getDaysLate()) {
return -1;
} else if ((dateSubmitted == other.dateSubmitted)
&& (files.compareTo(other.files) == -1)) {
return -1;
} else if ((dateSubmitted == other.dateSubmitted)
&& (files == other.files)) {
if (name.compareTo(other.name) == -1) {
return -1;
} else if (name.compareTo(other.name) == 1) {
return 1;
} else if (name.compareTo(other.name) == 0) {
return 0;
}
} else {
return 0;
}
}
There is a path in the third else
that does't return anything.
else if ((dateSubmitted == other.dateSubmitted) && (files == other.files)) {
if (name.compareTo(other.name) == -1) {
return -1;
}
else if (name.compareTo(other.name) == 1) {
return 1;
}
else if (name.compareTo(other.name) == 0) {
return 0;
} else return ...
}
BTW, I'm not sure if I'm following the logic of your implementation, since it seems that you are returning 0 if dateSubmitted != other.dateSubmitted
. compareTo
should also be anti-symetric (i.e. sgn(x.compareTo(y)) == -sgn(y.compareTo(x))
), but your implementation is not.
How can you be sure (with all these if and else) that you are always returning an int? It does not seem so obvious to me and aparently the compiler agrees with me too.
One way to solve this (probably not the best one) is to add a return -1; //or whatever value
at the end of your function.
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