利用GoodRing类,编写程序TotalArea.java。程序中创建一个存储由10个GoodRing对象组成的数组ringArray,然后创建10个环对象,用随机数初始化各个环的内、外半径。计算并输出这10个环的面积之和。 
自己编了一条,发现运行结果是错误的,想借鉴一下各位的解题方法。谢谢!

解决方案 »

  1.   

    import java.util.Random;public class B {
    private GoodRing [] rings = new GoodRing[10];
    Random rand = new Random();
    public TotalArea()
    {
    generateRings();
    }
    public void generateRings()
    {
    for(int i=0;i<10;i++)
    {
    int t1 = Math.abs(rand.nextInt());
    int t2 = Math.abs(rand.nextInt());
    rings[i] = new GoodRing();
    if(t1 >= t2)
    {
    rings[i].setR1(t1);
    rings[i].setR2(t2);
    }
    else
    {
    rings[i].setR1(t2);
    rings[i].setR2(t1);
    }
    }
    }
    public double countArea()
    {
    double sumArea = 0;
    for(int i=0; i<rings.length; i++)
    {
    sumArea += (rings[i].getR1()*rings[i].getR1()-rings[i].getR2()*rings[i].getR2())*Math.PI;
    }
    return sumArea;
    }
    public static void main(String[]args)
    {
    TotalArea b = new TotalArea();
    System.out.println(b.countArea());
    }
    }
    class GoodRing
    {
    private double r1;
    private double r2;
    public double getR1() {
    return r1;
    }
    public void setR1(double r1) {
    this.r1 = r1;
    }
    public double getR2() {
    return r2;
    }
    public void setR2(double r2) {
    this.r2 = r2;
    }
    }
      

  2.   

    public class B {
    改为
    public class TotalArea {