Reputation: 3
I'm trying to write code that compares the marks of two report cards but everytime I use an operator like > or < it says it's undefined for the argument type. Could someone tell me what I am doing wrong?
Edit (from comments): The type of marks
and getMarks
is double[]
.
* @param other
* @return 1 if the average mark of calling object is more than average of parameter object
* -1 if the average mark of calling object is less than average of parameter object
* 0 if the average mark of calling object and the average of parameter object are the same
*/
public int compareTo(ReportCard other) {
if(this.marks > other.getMarks()) {
return 1;
} else if (this.marks < other.getMarks()) {
return -1;
} else {
return 0;
}
} //to be completed
Upvotes: 0
Views: 130
Reputation: 34618
The operators <
, >
, <=
and >=
are only available for primitive numeric types (double
,int
,char
etc.).
The type double []
is not a primitive type. It's an array type (which is an object). You have to devise your own way of comparing an array and write a loop for it.
Consider: what will you do if the current report card has 3 marks, and the other report card has 5 marks? Suppose the first three marks are the same. Which report card should be considered the greater?
If they have the same number of marks, then your loop should be something like (pseudocode):
For each element marks[i] in the current report card marks
if it is greater than the other report card's mark at the same position
return 1;
else if it is less than the other report card's mark at the same position
return -1;
end of loop
Return zero (the two arrays were exactly the same)
You need to expand this to consider the case when the arrays are not of the same length.
Note that this gives most significance to the first mark. If all marks are equally important, you may want to do something else, like comparing the mark averages or sums.
To sum up: you were trying to compare non-primitive values using the comparison operators. The operators are not defined for objects and array types and you have to write your own implementation that does this correctly.
Upvotes: 0
Reputation: 298838
your code can be simplified to:
public int compareTo(ReportCard other) {
return Double.compare(this.getMarks(), other.getMarks());
}
Or, if you want to create a Comparator<ReportCard>
rather than implementing Comparable<ReportCard>
, then you can do something like this:
Comparator<ReportCard> comparator = Comparator.comparingDouble(ReportCard::getMarks);
Upvotes: 3