用Java 在一个有x,y轴都坐标系中,用坐标值建立一个长方形,采用下面两种方式来构造: (1)长方形左上角和右下角坐标; (2)长方形左上角坐标和长方形的长和高; 然后写出长方形的成员方法: (3)area() ---返回长方形面积; (4)perimeter()--返回边长; (5)print() --输出矩形的属性值; (6)isSquare() --如果长方形是正方形的话,返回true; 写出一个测试类RectangleTest,在主方法中创建长方形类的对象(用不同构造函数),求出面积、周长并输出显示,并判断是否为正方形。
时间: 2023-06-20 14:08:19 浏览: 64
长方形类Rectangle的代码实现如下:
```java
public class Rectangle {
private int x1, y1, x2, y2;
public Rectangle(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public Rectangle(int x1, int y1, int width, int height) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x1 + width;
this.y2 = y1 + height;
}
public int area() {
int width = Math.abs(x2 - x1);
int height = Math.abs(y2 - y1);
return width * height;
}
public int perimeter() {
int width = Math.abs(x2 - x1);
int height = Math.abs(y2 - y1);
return 2 * (width + height);
}
public void print() {
System.out.println("Rectangle: (" + x1 + ", " + y1 + "), (" + x2 + ", " + y2 + ")");
System.out.println("Area: " + area());
System.out.println("Perimeter: " + perimeter());
if (isSquare()) {
System.out.println("This rectangle is a square.");
} else {
System.out.println("This rectangle is not a square.");
}
}
public boolean isSquare() {
int width = Math.abs(x2 - x1);
int height = Math.abs(y2 - y1);
return width == height;
}
}
```
测试类RectangleTest的代码实现如下:
```java
public class RectangleTest {
public static void main(String[] args) {
Rectangle rect1 = new Rectangle(0, 0, 5, 10);
Rectangle rect2 = new Rectangle(0, 0, 10, 10);
rect1.print();
System.out.println();
rect2.print();
}
}
```
测试结果如下:
```
Rectangle: (0, 0), (5, 10)
Area: 50
Perimeter: 30
This rectangle is not a square.
Rectangle: (0, 0), (10, 10)
Area: 100
Perimeter: 40
This rectangle is a square.
```
阅读全文