2017-03-21 12 views
0

2つのレポートカードのマークを比較するコードを作成しようとしていますが、>または<のような演算子を使用するたびに、引数の型は未定義です。誰かが私が間違っていることを教えてもらえますか? (コメント)Java compareTo()未定義のオペレータ

編集:marksの種類とgetMarksdouble[]あります。

* @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 
あなたのコードは次のように単純化でき
+1

「マーク」はどのようなタイプですか? –

+0

marksはdouble型 – reez

+0

です。また、getMarks()も 'double'を返しますか? – domsson

答えて

0

<><=および>=の演算子は、プリミティブ数値型(double,int,charなど)。

タイプdouble []はプリミティブ型ではありません。配列型(オブジェクト)です。配列を比較してループを作成する独自の方法を工夫する必要があります。

検討:現在のレポートカードに3つのマークがあり、もう一方のレポートカードに5つのマークがある場合はどうしますか?最初の3つのマークが同じであるとします。どのレポートカードをより大きなものと見なすべきですか?

彼らはマークの数が同じ場合は、あなたのループは(擬似コード)のようなものでなければなりません:

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) 

あなたは、配列の長さが同じでない場合を考慮して、これを拡張する必要があります。

これは、最初のマークに最も重要な意味を持つことに注意してください。すべてのマークが同じように重要である場合は、マークの平均値または合計を比較するなど、何か他のことをしたい場合があります。

合計:比較演算子を使用して非プリミティブ値を比較しようとしていました。演算子はオブジェクトと配列型に対して定義されていないため、これを正しく行う独自の実装を作成する必要があります。

+0

ありがとう私のためにそれをクリアした – reez

3

public int compareTo(ReportCard other) { 
    return Double.compare(this.getMarks(), other.getMarks()); 
} 

それとも、あなたはむしろComparable<ReportCard>を実装するよりもComparator<ReportCard>を作成したい場合、あなたはこのような何か行うことができます。

Comparator<ReportCard> comparator = Comparator.comparingDouble(ReportCard::getMarks); 
+0

助けてくれてありがとう – reez

+1

さらに、 'Comparator.comparingDouble(ReportCard :: getMarks)'。 –

+0

@ OleV.V。おかげで、それを知らなかった –