2011-09-29 117 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];