我的 Rectangle 类上有 getter 和 setter、默认和重载的构造函数、toString 和区域方法。我的 RectangleTest 只是我的值和输出语句。我一直在尝试让我的面积方法正常工作,但无论我尝试什么,都没有调用我的高度和宽度。
public class Rectangle {
public double width ;
private double height;
private String color ;
private double area;
public double getWidth ( ) { return width; }
public void setWidth ( double w ) {
this.width = w; }
public double getHeight ( ) {return height; }
public void setHeight ( double h ) {
this.height = h; }
public String getColor ( ) {return color; }
public void setColor ( String co ) {
this.color = (co); }
public Rectangle ( ) {
height = 0;
width = 0;
color = (" ");
System.out.println("Default constructor");
//default constructor
}
public Rectangle ( double w, double h, String co) {
width = w;
height = h;
color = (co);
System.out.println("Overloaded constructor" );
//overloaded constructor
}
public double findArea (){
return area;
}
public void setArea (double width, double height){
area = width * height;
}
public String toString ( ) {
String x = "Rectangle width is " + width + ", height is " + height +
", color is " + color + " and the area is " + area;
return x;
}
}
public class RectangleTest {
public static void main(String[] args) {
Rectangle shape = new Rectangle(2.0, 4.0, "red");
Rectangle r2 = new Rectangle(2.0, 3.0, "Yellow");
Rectangle r3 = new Rectangle(2.0, 3.0, "Yellow");
do { r2.width++ ;
} while (r2.width == (r3.width));
if (r2.equals (r3))
System.out.println("r2 still equals r3" );
else
System.out.println("r2 is now a square");
System.out.println("First rectangle is " + shape );
System.out.println("Second rectangle is " + r2 );
if (r2.equals (r3))
System.out.println("\nShape 2 equals shape 3");
else
System.out.println("\nShape 2 and 3 are not equal");
//System.exit(0);
}
}
最佳答案
findArea
是一个可计算的结果,这意味着它的结果是基于计算其他值的结果。根据您的代码示例,计算 area
的唯一位置是在调用 setArea
时,但从未调用 setArea
。
更好的解决方案是让 findArea
自行执行计算
public double findArea (){
return width * height;
}
这样做的好处是,您不必在 width
或 height
发生变化时记住调用 setArea
方法
关于java - 我在调用矩形面积的方法时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42797789/