创建对象数组(求圆的数组的总面积)

public class Circle {
    private double radius = 1;

    public Circle(double newRadius){
        radius=(newRadius>=1)?newRadius:0;
    }
    public double getRadius() {
        return radius;
    }

    public double setRadius(double newRadius) {
        radius = (newRadius >= 1) ? newRadius : 0;
        return radius;
    }
    public double getArea(){
        return radius*radius*Math.PI;
    }
}
public class Test {
    public static void main(String[] args) {
        Circle[] circles;
        circles = method();
        print(circles);

    }

    public static Circle[] method() {
        Circle[] circleArray = new Circle[5];
        for (int i = 0; i < circleArray.length; i++) {
            circleArray[i] = new Circle(Math.random() * 100);
        }
        return circleArray;
    }

    public static void print(Circle[] circle) {
        System.out.printf("%-30s%-15s\n", "Radius", "Area");
        for (int i = 0; i < circle.length; i++) {
            System.out.printf("%-30f%-15f\n", circle[i].getRadius(), circle[i].getArea());
        }
        System.out.println("-----------------------------------------------------");
        System.out.printf("%-30s%-15f", "The total area of circles is ", sumArea(circle));

    }

    public static double sumArea(Circle[] circles) {
        double sum = 0;
        for (int i = 0; i < circles.length; i++) {
            sum += circles[i].getArea();
        }
        return sum;
    }

}



上一篇:计网复习一些细小但重要的知识点


下一篇:[cf963E]Circles of Waiting