用Java 在一个有x,y轴都坐标系中,用坐标值建立一个长方形,采用下面两种方式来构造: (1)长方形左上角和右下角坐标; (2)长方形左上角坐标和长方形的长和高; 然后写出长方形的成员方法: (3)area() ---返回长方形面积; (4)perimeter()--返回边长; (5)print() --输出矩形的属性值; (6)isSquare() --如果长方形是正方形的话,返回true; 写出一个测试类RectangleTest,在主方法中创建长方形类的对象(用不同构造函数),求出面积、周长并输出显示,并判断是否为正方形。
时间: 2023-06-24 19:08:48 浏览: 88
长方形类的代码如下:
```java
public class Rectangle {
private double x1, y1, x2, y2;
private double width, height;
// 构造函数1:输入左上角和右下角坐标
public Rectangle(double x1, double y1, double x2, double y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.width = x2 - x1;
this.height = y2 - y1;
}
// 构造函数2:输入左上角坐标和宽高
public Rectangle(double x1, double y1, double width, double height) {
this.x1 = x1;
this.y1 = y1;
this.width = width;
this.height = height;
this.x2 = x1 + width;
this.y2 = y1 + height;
}
// 计算面积
public double area() {
return width * height;
}
// 计算周长
public double perimeter() {
return 2 * (width + height);
}
// 输出属性值
public void print() {
System.out.println("左上角坐标为 (" + x1 + ", " + y1 + ")");
System.out.println("右下角坐标为 (" + x2 + ", " + y2 + ")");
System.out.println("宽为 " + width);
System.out.println("高为 " + height);
System.out.println("面积为 " + area());
System.out.println("周长为 " + perimeter());
}
// 判断是否为正方形
public boolean isSquare() {
return width == height;
}
}
```
测试类的代码如下:
```java
public class RectangleTest {
public static void main(String[] args) {
// 构造函数1
Rectangle rect1 = new Rectangle(0, 0, 3, 4);
rect1.print();
System.out.println("是否为正方形:" + rect1.isSquare());
System.out.println();
// 构造函数2
Rectangle rect2 = new Rectangle(0, 0, 5, 5);
rect2.print();
System.out.println("是否为正方形:" + rect2.isSquare());
}
}
```
输出结果如下:
```
左上角坐标为 (0.0, 0.0)
右下角坐标为 (3.0, 4.0)
宽为 3.0
高为 4.0
面积为 12.0
周长为 14.0
是否为正方形:false
左上角坐标为 (0.0, 0.0)
右下角坐标为 (5.0, 5.0)
宽为 5.0
高为 5.0
面积为 25.0
周长为 20.0
是否为正方形:true
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)