gpt4 book ai didi

java - 如何使用 Rectangle 类创建矩形数组?

转载 作者:行者123 更新时间:2023-12-01 08:13:08 26 4
gpt4 key购买 nike

我正在做一项作业,该作业应该返回一个由 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]);

}



}
}

谢谢!

最佳答案

创建一个矩形数组并向每个索引添加一个矩形。

Rectangle[] arr = new Rectangle[10];

for(int i = 0; i < 10; i++)
{
Rectangle r = new Rectangle();
r.setWidth((Math.random()*40)+10);
r.setHeight((Math.random()*40)+10);

arr[i] = r;
}

关于java - 如何使用 Rectangle 类创建矩形数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15777064/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com