Reputation: 63
Create an array of Rectangle (size 20)
Fill in the array with 20 rectangles, each has random length and width. then print the content of the array.
This is my the given rectangle class:
class Rectangle
{
private int length, width;
private int area, perimeter;
public Rectangle()
{
}
public Rectangle(int l, int w)
{
length = l;
width = w;
}
public void SetDimension(int l, int w)
{
length = l;
width = w;
}
public void InputRect()
{
length = int.Parse(Console.ReadLine());
width = int.Parse(Console.ReadLine());
}
public void ComputeArea()
{
area = length * width;
}
public void ComputePerimeter()
{
perimeter = 2 * (length + width);
}
public void Display()
{
Console.WriteLine("Length: {0} \tWidth: {1} \tArea: {2} \tPerimeter: {3}", length, width, area, perimeter);
}
}
This is the start of the program where I get the random numbers. I am stuck here.
How exactly would I enter 2 numbers into the same index of an array?
class Program
{
static void Main(string[] args)
{
Rectangle r1 = new Rectangle();
int[] x = new int[20];
Random rand = new Random();
for (int i = 0; i < x.Length; i++)
{
int width = rand.Next(45, 55);
int length = rand.Next(25, 35);
}
//r1.InputRect(width, length);
Console.WriteLine("The following rectanglesn are created: ");
//r1.Display(x);
}
}
Upvotes: 1
Views: 1097
Reputation: 5910
you can either do a List<Rectangle>
or Rect[] m_Rects = new Rect[20];
do it with a multidimensional array of int. looks a bit like homework to me ;)
a simple solution would be:
Random rand = new Random();
Rectangle[] ra = new Rectangle[20];
for (int i = 0; i < ra .Length; i++)
{
int length = rand.Next(25, 35);
int width = rand.Next(45, 55);
ra[i] = new Rectangle(length, width);
}
Console.WriteLine("The following rectangles are created: ");
foreach(Rect r in ra)
{
r.Display();
}
Upvotes: 2
Reputation: 25370
Rectangle[] rects = new Rectangle[20];
Random rand = new Random();
for (int i = 0; i < rects.Length; i++)
{
int width = rand.Next(45, 55);
int length = rand.Next(25, 35);
rects[i] = new Rectangle(length,width);
}
How exactly would I enter 2 numbers into the same index of an array?
That's not what you need to do here. You're wanting to create a one-dimensional array of rectangles with a known size. Create the empty array, then loop through it and fill it up.
Upvotes: 1
Reputation: 165
You should be creating an array of Rectangles, not an array of ints.
Upvotes: 3