2016-10-19 122 views
-4

我嘗試隨機化值,如果它們沒有改變,但它不會讓我在構造函數中使用隨機數發生器,並且當我使用其他函數時會給出錯誤。C#構造函數中的錯誤

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace Randomizer { 
    class Apartment { 
     public int height; 
     public int bas; 
     public int hasPent; 
     public Apartment(int b = 100, int h = 100, int p = 100) { 
      height = h; 
      bas = b; 
      hasPent = p; 
      public Room[,,] rooms = new Room[bas, bas, height]; 
      finCon(bas, height, hasPent, rooms); 
     } 

     void finCon(int b, int h, int p, Room[,,] ro) { 
      Random r = new Random(); 
      if (b==100) { 
       b = r.Next(2,4); 
      } 
      if (h==100) { 
       h = r.Next(4,15); 
      } 
      if (p==100) { 
       p = r.Next(0,20); 
      } 
     } 
    } 
    class Room { 
     int some = 37; 
    } 
    class Program { 
     static void Main(string[] args) 
     { 
      Apartment ap = new Apartment(); 
      ap.finCon(ap.bas,ap.height,ap.hasPent,ap.rooms); 
      Console.WriteLine("{0}{1}",ap.bas,ap.height); 
      } 
     } 
    } 

錯誤:

(1:1)命名空間不能直接包含成員如字段或方法

(16點25)}預期

(18時13分)方法必須具有返回類型

(18:23)標識符預計

(18時31)標識符預期

(18:40)標識符預期

(18時47分)標識符預期

(21:9)命名空間不能直接包含成員如字段或方法

(21點47分)標識符預期

(21點48分)標識符預期

(2 1:51)預期類,預期的委託,枚舉接口,或結構

(22時28分)類,委託,枚舉接口,或結構

(33:5)輸入或命名空間定義,或檔案結尾預期

(46:1)類型或命名空間定義,或 - 的文件結束預定

+3

你應該在你的問題中包含錯誤的細節。 – mason

+1

如果您遇到錯誤,它總是**有幫助將它們包含在您的帖子中。不要讓我們猜測和搜索你的代碼的問題。 –

+2

您不能在構造函數中放置'public room [,,] rooms = new Room [bas,bas,height];''。你需要'public room [,,] rooms;'和其餘的字段(例如,直接在'public int hasPent;'之下),然後在構造函數中,你需要'rooms = new Room [bas,bas,height]; '分配給'bas'和'height'後。 – Quantic

回答

0

我找到了編譯:

namespace Randomizer 
{ 
    public class Apartment 
    { 
     public int height; 
     public int bas; 
     public int hasPent; 
     public Room[,,] rooms; 

     public Apartment(int b = 100, int h = 100, int p = 100) 
     { 
      height = h; 
      bas = b; 
      hasPent = p; 
      rooms = new Room[bas, bas, height]; 
      finCon(bas, height, hasPent, rooms); 
     } 

     public void finCon(int b, int h, int p, Room[,,] ro) 
     { 
      Random r = new Random(); 
      if (b == 100) 
      { 
       b = r.Next(2, 4); 
      } 
      if (h == 100) 
      { 
       h = r.Next(4, 15); 
      } 
      if (p == 100) 
      { 
       p = r.Next(0, 20); 
      } 
     } 
    } 

    public class Room 
    { 
     int some = 37; 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      Apartment ap = new Apartment(); 
      ap.finCon(ap.bas, ap.height, ap.hasPent, ap.rooms); 
      Console.WriteLine("{0}{1}", ap.bas, ap.height); 
     } 
    } 
} 

你的問題是試圖在構造函數中聲明一個property(你不能這麼做)。我也把所有課程都公開了。

希望它能幫助你。

+0

我也改變了它,所以它只是finCon()並使用this.thevariablename – opfromthestart