私は、静的なfindMaxメソッドを使用して最大周囲長の矩形を見つけようとしています。どうにかして、配列内で最大長の配列ではなく、生成されたRectangleが得られます。私は何が間違っているのかわからないのは、私が打ち勝ったcompareToメソッドがうまく動作しているようだからです。ここなぜ私のfindMaxメソッドは、最大要素の代わりに配列の最初の要素の結果を返しますか?
は、Rectangleクラスのコードです:
public class Rectangle implements Comparable<Rectangle> {
private double length;
private double width;
private double perimeter;
public Rectangle(double l, double w){
this.length = l;
this.width = w;
}
public double getLength() {
return length;
}
public double getWidth(){
return width;
}
public void setLength(double l){
length= l;
}
public void setWidth(double w){
width = w;
}
public double getPerimeter(){
perimeter = 2*(length+width);
return perimeter;
}
@Override
public int compareTo(Rectangle other){
return Double.compare(this.perimeter, other.perimeter);
}
@Override
public String toString(){
return "Rectangle: "+ width +" by "+ length ;
}
}
そして、これはfindMaxを有している主なある:私はあなたではない
public class Problem1{
public static <Anytype extends Comparable<Anytype>> Anytype findMax(Anytype[] arr){
int maxIndex = 0;
for (int i = 1; i < arr.length; i++)
if (arr[i].compareTo(arr[maxIndex]) > 0)
maxIndex = i;
return arr[maxIndex];
}
public static void main(String[] args){
Rectangle[] arr = new Rectangle[5];
for(int i = 0; i < 5; i++)
{
Rectangle r = new Rectangle(10, 20);
r.setWidth((Math.random()*10)+10);
r.setLength((Math.random()*10)+10);
arr[i] = r;
}
// Rectangle max = findMax(<Rectangle>[] arr);
Rectangle max = findMax(arr);
double maxP =max.getPerimeter();
System.out.println("The rectangle that has the max perimeter is "+findMax(arr)+" maxP is "+maxP);
for(Rectangle rec: arr){
System.out.println(rec.getPerimeter());
System.out.println(rec);
}
}
}
はあなた 'compareTo'方法は' getPerimeter() 'の呼び出し後に初期化されるフィールド' perimeter'を、使用しています。私はそのフィールドを廃止し、 'getPerimeter()'(これは常に 'width'と' height'フィールドに基づいて正しい周囲を返します)を使うことを提案します。あるいは、あなたの長さ/幅のセッターで 'perimeter'を更新することもできます。 – qxz
ここで提案するように、コードのゲッターとセッターを更新することができます - http://stackoverflow.com/a/41906384/1746118 – nullpointer
長方形の長さと幅の5つのオブジェクトを作成しましたが、周囲はどこにも設定されていませんすべての矩形は、0.0(デフォルト値)として境界を持ちます。だから、** this.perimeter = 2(this.length * this.width); ** –