我正在处理一个任务,该任务应该返回一个由 10 个矩形组成的数组,这些矩形具有从字符串中选择的随机高度、随机宽度和随机颜色。
该程序可以很好地返回一个矩形的对象,但是我将如何实现它来创建一个由 10 个矩形组成的数组,然后在循环中返回每个矩形?
这是我的类文件和我的对象:
import java.util.*;
public class Rectangle
{
private double width;
private double height;
public static String color = "White";
private Date date;
Rectangle() {
width = 1;
height = 1;
date = new Date();
}
Rectangle (double w, double h) {
width = w;
height = h;
date = new Date();
}
public double getHeight() {
return height;
}
public void setHeight(double h) {
height = h;
}
public double getWidth() {
return width;
}
public void setWidth(double w) {
width = w;
}
public static String getColor() {
return color;
}
public static void setColor(String c) {
color = c;
}
public Date getDate() {
return date;
}
public void setDate (Date d) {
date = d;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
public String toString() {
String S;
S = "Rectangle with width of " + width;
S = S + " and height of " + height;
S = S + " was created on " + date.toString();
return S;
}
}
到目前为止,这是我的客户程序。我正在设置随机高度和随机宽度,并从颜色字符串中选择随机颜色。
我希望能够为 10 个不同矩形的数组执行此操作:
import java.util.*;
public class ClientRectangle
{
public static void main(String[] args)
{
String[] colors = {"White","Blue","Yellow","Red","Green"};
Rectangle r = new Rectangle();
int k;
for(int i = 0; i < 10; i++)
{
r.setWidth((Math.random()*40)+10);
r.setHeight((Math.random()*40)+10);
System.out.println(r.toString() + " has area of " + r.getArea() + " and perimeter of " + r.getPerimeter());
k = (int)(Math.random()*4)+1;
System.out.println(colors[k]);
}
}
}
谢谢!