I am trying to print multiple Information entries that will be inserted in an array as an object, and I want to use the methods that are available to those objects and print the result. This is my code. I am getting an error in my last two sentences
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace homework2
{
class Shapes
{
protected string ShapeName;
protected double ShapeWidth;
protected double ShapeHeight;
public Shapes(string ShapeName, double ShapeWidth, double ShapeHeight)
{
this.ShapeName = ShapeName;
this.ShapeWidth = ShapeWidth;
this.ShapeHeight = ShapeHeight;
}
}
class Rectangle : Shapes
{
public Rectangle(string ShapeName, double ShapeWidth, double ShapeHeight)
: base(ShapeName, ShapeWidth, ShapeHeight)
{
this.ShapeName = ShapeName;
this.ShapeWidth = ShapeWidth;
this.ShapeHeight = ShapeHeight;
}
public double GetArea()
{
if (ShapeName == "Circle")
{
ShapeHeight = 3.14;
double x = ShapeHeight * (ShapeWidth * ShapeWidth);
return x;
}
else
{
double Area = ShapeHeight * ShapeWidth;
return Area;
}
}
}
class Program
{
static void Main(string[] args)
{
Rectangle Rec = new Rectangle("Circle",5,2);
System.Console.WriteLine("This is the Rectangle Area :"+Rec.GetArea());
System.Console.WriteLine("Please Enter How Many Shapes You want To enter:");
String x = Console.ReadLine();
int y = int.Parse(x);
for (int i = 0; i <= y; i++ )
{
System.Console.WriteLine("Enter Name for Shape No."+i+"Please");
String ShapeName = Console.ReadLine();
System.Console.WriteLine("Enter width for Shape No." + i + "Please");
String ShapeWidth = Console.ReadLine();
int sw = int.Parse(ShapeWidth);
System.Console.WriteLine("Enter height for Shape No." + i + "Please");
String ShapeHeight = Console.ReadLine();
int sh = int.Parse(ShapeHeight);
for(int j = 0; j < 4; j++)
{
Rectangle[,] z = new Rectangle[y,4];
Rectangle z[i,j] = new Rectangle(ShapeName, sw, sh);
}
}
}
}
}
Firstly, in your derived class Rectangle, you do not need to reassign the variables in shape as the base constructor will still be called.
Also, it would make more sense to, instead of passing in a string like “Circle” to create a circle, to create a new class Circle : Shapes that implemented a different GetArea() rather than having your rectangle class calculate the area of a circle.
The error you are presumably having is with the line:
Because you have already defined z[i,j] as an array this line should read
(Without the rectangle).
However, I suspect you want to define your array of Rectangles outside of the first for loop. With the current code, you are going to end up with y 2D arrays with one column filled in for each one. You need to move this: outside of the first for loop
Rectangle[,] z = new Rectangle[y,4];