2013-05-02 85 views
1
playerDice = new Dice(); 
int playerDiceNo = playerDice.getfaceofDie(); 
MessageBox.Show("Your roll" + playerDiceNo); 

compDice = new Dice(); 
int compDiceNo = compDice.getfaceofDie(); 
MessageBox.Show("Computers roll:" + compDiceNo); 

上面是我點擊滾動按鈕時的方法。 下面是我的骰子類:骰子返回0且沒有捲筒

class Dice 
{ 
    private int faceofDie; 
    public void rollDice() 
    { 
     Random rollDice = new Random(); 
     faceofDie = rollDice.Next(1, 7);   
    } 
    public int getfaceofDie() 
    { 
     return faceofDie; 
    } 
} 

我已表示我對compDice和playerDice變量:

Dice compDice; 
Dice playerDice; 

我似乎無法弄清楚它爲什麼兩個軋&在返回0 。誰能幫忙?

+1

因爲你不擲骰子 – musefan 2013-05-02 15:55:18

+1

也許是因爲你從來不擲骰子? – Howard 2013-05-02 15:55:44

+0

我已添加playerDice.RollDice();它仍然顯示0 – user2326995 2013-05-02 15:59:51

回答

5

我似乎無法弄清楚爲什麼它會在&以上返回0。誰能幫忙?

你永遠不會調用rollDice(),所以faceofDie變量從未設置,並且已經是0

playerDice = new Dice(); 
playerDice.rollDice(); // Add this 
int playerDiceNo = playerDice.getfaceofDie(); 
MessageBox.Show("Your roll" + playerDiceNo); 

默認值一個更好的方法是通過投擲骰子在構造函數中的第一次,並不能保持創造新的隨機實例:

class Dice 
{ 
    private static Random diceRoller = new Random(); 

    private int faceofDie; 

    public Dice() 
    { 
     this.RollDice(); // Roll once on construction 
    } 

    public void RollDice() 
    { 
     lock(diceRoller) 
      faceofDie = diceRoller.Next(1, 7);   
    } 

    public int FaceOfDie 
    { 
     get { return faceofDie; } 
    } 
} 

靜態隨機實例將防止在同一時間執行多個骰子從得到相同的種子(如日所有這些都會隨機分享),這將有助於保持結果的一致性。這也移動到標準的C#的公約,並希望可以使用:

playerDice = new Dice(); 
int playerDiceNo = playerDice.FaceOfDie; 
MessageBox.Show("Your roll" + playerDiceNo); 

compDice = new Dice(); 
int compDiceNo = compDice.FaceOfDie; 
MessageBox.Show("Computers roll:" + compDiceNo); 
+0

只是把這個,但它仍然顯示0 – user2326995 2013-05-02 15:59:10

+0

@ user2326995我的代碼,如上所述,將返回1和6(含)之間的2個不同的數字 - 只是測試驗證。 – 2013-05-02 16:01:19

+0

對不起,我的錯誤是,我的電腦沒有顯示第二批代碼。謝謝你的幫助,這完美的作品。 – user2326995 2013-05-02 16:04:26