写一个Rectangle类,描述一个矩形。 具备以下域: 四个顶点的坐标leftTop,rightTop,leftFloor,rightFloor,以Point对象表示; 图形的周长; 图形的面积。 构造器: 无参构造器 Rectangle(),生成一个四个顶点均为(0.0,0.0)的矩形; Rectangle(double x1, double y1, double x2, double y2),其中(x1, y1)是一个顶点,其中(x2, y2)是对角线上另一个顶点; Rectangle(Point p1,Point p2),p1、p2是对角线上的两个顶点。 设计如下方法: Point getLeftTop(); Point getLeftFloor(); Point getRightTop(); Point getRightFloor(); 返回周长; 返回面积。 写一个测试类,测试Rectangle类。
时间: 2023-04-10 22:04:10 浏览: 227
Rectangle类的代码如下:
```
public class Rectangle {
private Point leftTop;
private Point rightTop;
private Point leftFloor;
private Point rightFloor;
public Rectangle() {
this.leftTop = new Point(0.0, 0.0);
this.rightTop = new Point(0.0, 0.0);
this.leftFloor = new Point(0.0, 0.0);
this.rightFloor = new Point(0.0, 0.0);
}
public Rectangle(double x1, double y1, double x2, double y2) {
this.leftTop = new Point(x1, y1);
this.rightTop = new Point(x2, y1);
this.leftFloor = new Point(x1, y2);
this.rightFloor = new Point(x2, y2);
}
public Rectangle(Point p1, Point p2) {
this.leftTop = new Point(Math.min(p1.getX(), p2.getX()), Math.min(p1.getY(), p2.getY()));
this.rightTop = new Point(Math.max(p1.getX(), p2.getX()), Math.min(p1.getY(), p2.getY()));
this.leftFloor = new Point(Math.min(p1.getX(), p2.getX()), Math.max(p1.getY(), p2.getY()));
this.rightFloor = new Point(Math.max(p1.getX(), p2.getX()), Math.max(p1.getY(), p2.getY()));
}
public Point getLeftTop() {
return leftTop;
}
public Point getLeftFloor() {
return leftFloor;
}
public Point getRightTop() {
return rightTop;
}
public Point getRightFloor() {
return rightFloor;
}
public double getPerimeter() {
return 2 * (Math.abs(leftTop.getX() - rightTop.getX()) + Math.abs(leftTop.getY() - leftFloor.getY()));
}
public double getArea() {
return Math.abs(leftTop.getX() - rightTop.getX()) * Math.abs(leftTop.getY() - leftFloor.getY());
}
}
```
测试类的代码如下:
```
public class RectangleTest {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle(1.0, 1.0, 3.0, 4.0);
Rectangle r3 = new Rectangle(new Point(2.0, 3.0), new Point(5.0, 6.0));
System.out.println("r1 perimeter: " + r1.getPerimeter());
System.out.println("r1 area: " + r1.getArea());
System.out.println("r2 perimeter: " + r2.getPerimeter());
System.out.println("r2 area: " + r2.getArea());
System.out.println("r3 perimeter: " + r3.getPerimeter());
System.out.println("r3 area: " + r3.getArea());
}
}
```
输出结果如下:
```
r1 perimeter: 0.0
r1 area: 0.0
r2 perimeter: 10.0
r2 area: 6.0
r3 perimeter: 12.0
r3 area: 9.0
```
阅读全文