其他分享
首页 > 其他分享> > 创建对象数组(求圆的数组的总面积)

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

作者:互联网

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;
    }

}



标签:circles,求圆,double,创建对象,newRadius,radius,数组,Circle,public
来源: https://blog.csdn.net/houlinhao123/article/details/102769726