c# - Dice returning 0 and no rolls -


playerdice = new dice(); int playerdiceno = playerdice.getfaceofdie(); messagebox.show("your roll" + playerdiceno);  compdice = new dice(); int compdiceno = compdice.getfaceofdie(); messagebox.show("computers roll:" + compdiceno); 

above method when roll button clicked. below dice class:

class dice {     private int faceofdie;     public void rolldice()     {         random rolldice = new random();         faceofdie = rolldice.next(1, 7);               }     public int getfaceofdie()     {         return faceofdie;     } } 

i have stated variables compdice , playerdice :

dice compdice; dice playerdice; 

i can't seem figure out why it's returning 0 both rolls on & over. can help?

i can't seem figure out why it's returning 0 both rolls on & over. can help?

you never call rolldice(), faceofdie variable never set, , has it's default value of 0.

playerdice = new dice(); playerdice.rolldice(); // add int playerdiceno = playerdice.getfaceofdie(); messagebox.show("your roll" + playerdiceno); 

a better approach roll dice first time in constructor, , not keep creating new random instances:

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     {         { return faceofdie; }     } } 

the static random instance prevent multiple dice implemented @ same time getting same seed (as they'll share single random), keep results more consistent. moves standard c# conventions, , used like:

playerdice = new dice(); int playerdiceno = playerdice.faceofdie; messagebox.show("your roll" + playerdiceno);  compdice = new dice(); int compdiceno = compdice.faceofdie; messagebox.show("computers roll:" + compdiceno); 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

javascript - Clean way to programmatically use CSS transitions from JS? -

android - send complex objects as post php java -