Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create an array of Rectangles with a Rectangle class?
    text
    copied!<p>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.</p> <p>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?</p> <p>Here's my class file with my objects:</p> <pre><code>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; } </code></pre> <p>}</p> <p>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. </p> <p>I would like to be able to do this for an array of 10 different rectangles: </p> <pre><code>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 &lt; 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]); } } } </code></pre> <p>Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload