静态方法将形状变为红色

时间:2013-12-08 21:01:37

标签: java

所以我做了这个程序,我试图在我的测试文件中添加一个静态方法,将随机数组形状全部变为“红色”。 公共抽象类形状 形状类

public abstract class Shape
{
private String color; 
public Shape() { color = "white";}
public String getColor() { return color;}
public void setColor(String c) { color = c; }
public abstract double area(); 
public abstract double perimeter();
public abstract void display();
}

圈子类

public class Circle extends Shape {

    private double radius;
    public Circle( double r)
    {
    super();
    radius = r;
    }
    public double getRadius()
    { return radius; }
    //Implement area, perimeter and display
    public double area()
    {
    return Math.PI * radius* radius;
    }
    public double perimeter()
    {
    return 2* Math.PI *radius;
    }
    //Circle class - continued
    public void display()
    {
    System.out.println( this);
    }
    public String toString()
    {


                return "Circle: radius:" + radius
                + "\tColor: " + getColor(); 

    }
}

我的主要测试课程

public class TestingShapes {

    public static double sumArea( Shape[] b)
    {
        double sum = 0.0;
        for( int k = 0; k < b.length; k++)
        {
            sum = sum + b[k].area();

        }
        return sum;

    }
    public static void printArray( Shape[] b)
    {
    for (Shape u: b)
System.out.println(u + "\tArearea " +  u.area());
    System.out.println();
    }





    public static void main( String[] args)
    {
    Shape[] list = new Shape[20]; //Not creating Shapes
     for ( int k = 0 ; k < list.length; k++)
    {
    double z = Math.random();
    if( z < 0.33 )
    list[k] = new Circle(1 + Math.random() * 10);
    else if(z<0.66)
    list[k] = new Rectangle ( 3*(k+1), 4*(k+1), 5*(k+1),6*(k+1));
    else
    list[k] = new Triangle ( 3*(k+1), 4*(k+1), 5*(k+1));

    }

     printArray(list);
     System.out.println();
     double sum = sumArea(list);
     System.out.println("Sum of List Area: " + sum);
    }

1 个答案:

答案 0 :(得分:0)

要将某些形状随机变为红色,您需要创建一个接受形状数组的方法,并在其上循环。您可以使用Math.random()获取0到1之间的随机浮点数。要将20%的形状变为红色,您只需将Math.random()与20%if (Math.random() < 0.2) { call the shape's setColor method with "red" }进行比较即可。由于Java中的数组/集合是通过引用传递的,因此您无需从方法返回任何内容,它将修改调用者拥有的副本。