Java 比较-两个矩形
我试图使用compareTo方法比较应该在main方法中创建的两个矩形的面积。通过这样做,程序应该能够判断矩形是否相等,或者矩形是否较大或较小 我在正确使用compareTo方法确定哪个矩形的面积最大时遇到了问题 这就是代码的发展程度: 矩形类:Java 比较-两个矩形,java,rectangles,compareto,Java,Rectangles,Compareto,我试图使用compareTo方法比较应该在main方法中创建的两个矩形的面积。通过这样做,程序应该能够判断矩形是否相等,或者矩形是否较大或较小 我在正确使用compareTo方法确定哪个矩形的面积最大时遇到了问题 这就是代码的发展程度: 矩形类: public abstract class Rectangle extends SimpleGeometricObject implements Comparable <Rectangle>{ private double widt
public abstract class Rectangle extends SimpleGeometricObject implements Comparable <Rectangle>{
private double width;
private double height;
public Rectangle() {
}
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public Rectangle(double width, double height, String color, boolean filled) {
this.width = width;
this.height = height;
setColor(color);
setFilled(filled);
}
/**Return width */
public double getWidth() {
return width;
}
/**Set a new width */
public void setWidth(double width) {
this.width = width;
}
/**Return height */
public double getHeight() {
return height;
}
/**Set a new height */
public void setHeight(double height) {
this.height = height;
}
/**Return area */
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
public boolean equals(Object obj) {
return this.getArea() == ((Rectangle)obj).getArea();
}
public int compareTo(SimpleGeometricObject o) {
if (this.getArea() > ((Rectangle) o).getArea()) {
return 1;
} else if (this.getArea() < ((Rectangle) o).getArea()) {
return -1;
} else {
return 0;
}
}
public static void main(String[] args) {
}
}
您声明您的类实现了
Comparable
,但您的代码表明您正在比较simplegeMetricObject
s
另外,在
Double
类中的函数Double.compare(Double d1,Double d2)
也会有所帮助。()你对“更大”的定义是什么?就面积而言?那么,问题又是什么呢?你得多试试自己。方法是使用谷歌搜索一些compareTo的例子,这样你就知道如何使用它,并将其应用到你的问题上。问题是如何正确使用compareTo方法,然后打印出解决方案。在过去的几个小时里,我一直在尝试谷歌——希望能有任何帮助链接!然后。。有什么问题吗?
public abstract class SimpleGeometricObject {
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;
/**Construct a default geometric object */
public SimpleGeometricObject() {
dateCreated = new java.util.Date();
}
/**Construct a geometric object with the specified color and filled value */
public SimpleGeometricObject(String color, boolean filled) {
dateCreated = new java.util.Date();
this.color = color;
this.filled = filled;
}
/**Return a color */
public String getColor() {
return color;
}
/**Set a new color */
public void setColor(String color) {
this.color = color;
}
/**Return filled. Since filled is boolean, its get method is named isFilled */
public boolean isFilled() {
return filled;
}
/**Set a new filled */
public void setFilled(boolean filled) {
this.filled = filled;
}
/**Get dateCreated */
public java.util.Date getDateCreated() {
return dateCreated;
}
/**Return a string representation of this object */
public String toString() {
return "created on " + dateCreated + "\ncolor: " + color + "and filled: " + filled;
}
}