2013-12-08 20 views
0

所以我制作了这个程序,我试图在我的测试文件中添加一个静态方法,将所有“红色”形状的随机阵列变成一个。 公共抽象类Shape 形状类将形状变为红色的静态方法

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); 
    } 
+5

你的问题是什么? –

+0

我将如何做一个静态方法,可以随机将一些形状变成红色而不是白色 – russiandobby

+1

@ user2977404每个形状都有一个'setColor(String c)'方法。用它。 –

回答

0

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