如何创建矩形的一个矩形类的数组?

编程入门 行业动态 更新时间:2024-10-27 12:25:14
本文介绍了如何创建矩形的一个矩形类的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的工作是应该用随机高度,随机宽度和颜色随机从一个字符串返回选定的10矩形阵列的分配。

I'm working on an assignment that is supposed to return an array of 10 rectangles with a random height, random width, and random color selected from a string.

该程序工作正常,返回的对象的一个​​四边形,但我将如何实现这个创造的10矩形阵列,然后返回在一个循环中每一个?

The program works fine to return the objects for ONE rectangle, but how would I implement this to create an array of 10 rectangles and THEN return each one in a loop?

下面是我的对象我的类文件:

Here's my class file with my objects:

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; }

}

这是到目前为止,我的客户端程序。我设置一个随机的高度和宽度随机并从颜色串随机颜色。

Here is my client program so far. I am setting a random height and a random width and selecting a random color from the colors String.

我希望能够为10个不同的矩形阵列做到这一点:

I would like to be able to do this for an array of 10 different rectangles:

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]); } } }

谢谢!

推荐答案

创建矩形阵列和矩形添加到每个索引。

Create an array of rectangles and add a rectangle to each index.

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; }

更多推荐

如何创建矩形的一个矩形类的数组?

本文发布于:2023-11-30 00:25:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648111.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矩形   数组

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!