用java定义Rectangle类(矩形类),矩形的宽度和高度为double类型变量with,height;从键盘为with,height变量输入值,计算矩形的面积及周长。
时间: 2024-05-06 11:20:04 浏览: 112
java代码-类名为Rectangle(矩形),它有两个整型的变量width(宽)和height(高);有一个方法area(),没有参数,返回类型为double,功能是求矩形的面积;还有另一个方法为perimeter()没有参数,返回类型为double,功能是求矩形的周长
以下是Java代码实现:
```java
import java.util.Scanner;
public class Rectangle {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入矩形的宽度:");
double width = scanner.nextDouble();
System.out.print("请输入矩形的高度:");
double height = scanner.nextDouble();
Rectangle rectangle = new Rectangle(width, height);
System.out.println("矩形的面积为:" + rectangle.getArea());
System.out.println("矩形的周长为:" + rectangle.getPerimeter());
}
}
```
运行结果示例:
```
请输入矩形的宽度:3.2
请输入矩形的高度:4.5
矩形的面积为:14.399999999999999
矩形的周长为:15.4
```
阅读全文