为什么我的findMax方法给出了数组的第一个元素而不是最大元素的结果?

时间:2017-01-28 05:20:58

标签: java arrays

我试图使用静态findMax方法找到具有最大周长的矩形。不知怎的,它只给了我在数组中生成的Rectangle,而不是具有最大周长的数组。我不知道什么是错的,因为我覆盖的compareTo方法似乎工作正常。

这是矩形类的代码:

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);


                }

    }


}

2 个答案:

答案 0 :(得分:1)

您没有调用getPerimeter()来设置对象的周长,因此周长将具有默认值0,我建议您编辑compareTo以在其体内调用getPerimeter方法,如下所示:

public int compareTo(Rectangle other){
    return Double.compare(this.getPerimeter(), other.getPerimeter());
} 

答案 1 :(得分:0)

@Override
public int compareTo(Rectangle other){
    System.out.println(this.perimeter + " :: " + other.perimeter);//all 0.0 :: 0.0
   return Double.compare(this.perimeter, other.perimeter);
}

更改退货:

return Double.compare(this.getPerimeter(), other.getPerimeter());