编写一个矩形类Rect,包含长度、宽度属性,构造参数方法初始化长度、宽度,创建面积、周长方法,在测试类输入长度、宽度中进行测试。
// Rect类,属性:长度,宽度
public class Rect {
private double height;
private double width;
Rect() {
}
// 构造方法,参数:长度,宽度
Rect(double height, double width) {
this.height = height;
this.width = width;
}
// 面积计算方法
public double area() {
return (height * width);
}
// 周长计算方法
public double perimeter() {
return (height + width);
}
}
import java.util.Scanner;
// 测试类
public class RectTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("输入矩形长度:");
double height = in.nextInt();
System.out.print("输入矩形宽度:");
double width = in.nextInt();
Rect rect = new Rect(height, width);
double area = rect.area();
double perimeter = rect.perimeter();
System.out.println("矩形面积为:"+ area);
System.out.println("矩形周长为:"+ perimeter);
}
}
输入矩形长度:19
输入矩形宽度:21
矩形面积为:399.0
矩形周长为:40.0