定义Rectangle类(矩形类),矩形的宽度和高度为double类型变量with,height;从键盘为with,height变量输入值,计算矩形的面积及周长。 要求:1.必须有构造器,构造器必须重载
时间: 2024-05-13 07:20:47 浏览: 68
2.必须有计算面积和周长的方法
Java代码如下:
```
import java.util.Scanner;
public class Rectangle {
private double width;
private double height;
public Rectangle() {
// 无参构造器
}
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入矩形的宽度:");
double width = sc.nextDouble();
System.out.print("请输入矩形的高度:");
double height = sc.nextDouble();
Rectangle rect = new Rectangle(width, height);
System.out.println("矩形的面积为:" + rect.getArea());
System.out.println("矩形的周长为:" + rect.getPerimeter());
}
}
```
阅读全文