2011-09-29 123 views
-1

我正在尝试打印多个信息条目,这些条目将作为对象插入到数组中,并且我想使用可用于这些对象的方法并打印结果。这是我的代码。我在我的最后两句话得到一个错误如何在数组中打印对象?

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


      } 
     } 
    } 
} 
+1

什么是错误? –

+0

你有什么错误?随意删除多余的代码以及... –

+0

第一个错误是在最后一个z“局部变量名称”z“已在范围中定义”,并在数组中它说:“坏阵列减速和它说的相等“;预期“和新的”预期“,你是什么意思的无关代码请解释 – user959349

回答

2

首先,在派生类Rectangle,你不需要重新分配变量的形状基本构造仍然被调用。

此外,它会更有意义,而不是传入像“圆”这样的字符串来创建一个圆,以创建一个新的类Circle:实现了不同GetArea()的形状,而不是让您的矩形类计算一个圆圈的面积。

您可能具有错误是与线:

Rectangle z[i,j] = new Rectangle(ShapeName, sw, sh); 

因为已经定义Z [I,J]为阵列此行应该读取

z[i,j] = new Rectangle(ShapeName, sw, sh); 

(不长方形)。

但是,我怀疑你想要定义第一个for循环之外的矩形的数组。使用当前的代码,您将最终得到y个2D数组,每个数组填充一列。你需要移动这个:在第一个for循环之外 Rectangle [,] z = new Rectangle [y,4];