java - 我在调用矩形面积的方法时遇到问题

标签 java class methods constructor

我的 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;
}

这样做的好处是,您不必在 widthheight 发生变化时记住调用 setArea 方法

关于java - 我在调用矩形面积的方法时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42797789/

相关文章:

html - 在 HTML 中编写 BEM 样式的更好方法

javascript - 编写一个带有方法的类

c# - 需要将通用方法移动到另一个类并从 C# 中的不同类调用它

android - trim()检查不起作用,应用崩溃-Android

java - 如何在java中将一个类按钮连接到另一个类方法

java - 如果文件不存在,PrinterWriter 是否会创建该文件?

php - 有用函数的集合最好作为函数库保存还是应该转换为类?

java - OSGi 列表,那些 header 是什么?

java - 如何使用 Jsoup 遍历 XML 标签?

java - 忽略 JSON 到 XML 转换中的键