这是我分配给学校的问题之一,这非常令人困惑。我什至不知道从哪里开始。
方向:在提供的空白处,编写下面描述的Rectangle类。
实例变量:
构造函数:
示例] new Rectangle(2.5,7)
方法:
矩形:宽度= 2.5,高度= 7,周长= 19
这将是我的解决方案。请务必阅读内联注释。
public class Rectangle {
private double width, height; //declare the instance variables
public Rectangle() {
width = 0; //set both instance variables to zero
height = 0;
}
public Rectangle(double width, double height) {
this.width = width; //set the instance variables to the passed-in variables
this.height = height;
}
public double getWidth() {
return width; //accessor for width
}
public void setWidth(double width) {
this.width = width; //mutator for width
}
public double getHeight() {
return height; //accessor for height
}
public void setHeight(double height) {
this.height = height; //mutator for height
}
public double perimeter() {
return (width + height) * 2; //perimeter = 2 widths and w heights
}
public double area() {
return width * height; //area = width * height
}
@Override
public String toString() {
return "Rectangle: Width = " + width + ", Height = " + height
+ ", Perimeter = " + perimeter(); //construct a string with all the required parameters
}
}