gpt4 book ai didi

java - 如何重写矩形类中根据周长进行比较的compareTo方法?

转载 作者:行者123 更新时间:2023-12-01 17:59:48 24 4
gpt4 key购买 nike

我这里有一个矩形类,我需要重写compareTo方法,以便它根据矩形的周长进行比较。我知道我当前的 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*(width + length);
return perimeter;
}


@Override
public int compareTo(Rectangle other){
String t=Double.toString(perimeter);
String o=Double.toString(other.perimeter);
int comp = t.compareTo(o);

return comp;
}

@Override
public String toString(){
return "Rectangle: "+ width +" by "+ length ;
}




}

最佳答案

试试这个

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

关于java - 如何重写矩形类中根据周长进行比较的compareTo方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41906136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com