我在调用矩形区域的方法时遇到问题

时间:2017-03-14 22:30:53

标签: java class methods constructor

我的Rectangle类上有getter和setter,默认和重载的构造函数,toString和我的area方法。我的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);
}
}

3 个答案:

答案 0 :(得分:2)

findArea是一个可计算的结果,这意味着它的结果是基于计算其他值的结果。根据您的代码示例,计算area的唯一位置是调用setArea时,但永远不会调用setArea

更好的解决方案是让findArea自己执行计算

public double findArea (){
    return width * height;
}

这样做的好处是,只要setAreawidth更改

,您就无法记住调用height方法

答案 1 :(得分:0)

你的矩形没有完全构造,因为永远不会调用方法setArea(double width, double height),所有对象的区域都保留默认值0.0 .....你应该在构造函数中调用它的方法。 / p>

public Rectangle ( double w, double h, String co) { 
    width = w;
    height = h;
    color = (co);
    System.out.println("Overloaded constructor" );
    //overloaded constructor
   setArea (width, height);   ///here!
} 

注意: 区域可以使用w和h立即计算,它们是类成员,无需定义方法

setArea (width, height); 

使用同一类中的参数,setArea()就足够了

答案 2 :(得分:0)

永远不会调用计算区域setArea的方法。按照您的代码运行方式,您可以将其放入toString

public String toString ( ) {
   setArea(width, height);
   String x = "Rectangle width is " + width + ", height is " + height +
    ", color is " + color + " and the area is " + area;
   return x;
} 

但是你的代码不是应该如何完成的标准方法。