import java.util.Arrays;

// 定义抽象类 Shape
abstract class Shape {
    // 抽象方法:获取周长
    public abstract int getPerimeter();

    // 抽象方法:获取面积
    public abstract int getArea();

    @Override
    public String toString() {
        return '';
    }
}

// 定义矩形类 Rectangle,继承自 Shape
class Rectangle extends Shape {
    private int width;
    private int length;

    public Rectangle(int width, int length) {
        this.width = width;
        this.length = length;
    }

    @Override
    public int getPerimeter() {
        return 2 * (width + length);
    }

    @Override
    public int getArea() {
        return width * length;
    }

    @Override
    public String toString() {
        return 'Rectangle [width=' + width + ', length=' + length + ']';
    }
}

// 定义圆形类 Circle,继承自 Shape
class Circle extends Shape {
    private int radius;

    public Circle(int radius) {
        this.radius = radius;
    }

    @Override
    public int getPerimeter() {
        return (int) (2 * Math.PI * radius);
    }

    @Override
    public int getArea() {
        return (int) (Math.PI * radius * radius);
    }

    @Override
    public String toString() {
        return 'Circle [radius=' + radius + ']';
    }
}

public class Main {
    public static void main(String[] args) {
        Rectangle[] rectangles = new Rectangle[2];
        Circle[] circles = new Circle[2];

        // 输入长方形的长和宽
        for (int i = 0; i < rectangles.length; i++) {
            int width = Integer.parseInt(System.console().readLine());
            int length = Integer.parseInt(System.console().readLine());
            rectangles[i] = new Rectangle(width, length);
        }

        // 输入圆形的半径
        for (int i = 0; i < circles.length; i++) {
            int radius = Integer.parseInt(System.console().readLine());
            circles[i] = new Circle(radius);
        }

        int totalPerimeter = 0;
        int totalArea = 0;

        // 计算周长和面积
        for (Rectangle rectangle : rectangles) {
            totalPerimeter += rectangle.getPerimeter();
            totalArea += rectangle.getArea();
        }

        for (Circle circle : circles) {
            totalPerimeter += circle.getPerimeter();
            totalArea += circle.getArea();
        }

        // 输出总周长和总面积
        System.out.println(totalPerimeter);
        System.out.println(totalArea);

        // 输出Rectangle数组和Circle数组
        System.out.println(Arrays.deepToString(rectangles));
        System.out.println(Arrays.deepToString(circles));
    }
}
Java面向对象编程:计算图形周长和面积

原文地址: https://www.cveoy.top/t/topic/bsTa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录