How can i make a “dice” that randomly generates a

2019-05-23 13:44发布

问题:

Right now i am using

 int die = (int)(6.0 * Math.random()) + 1;

This does not work for the loop i am trying to create. This is the method i am using.

public void computerRoll()
{ 

 do { roll();
      System.out.println("Roll:"+ die);
      computerScore += die;
     } while (computerScore <= 20 && die >=2 && die <=6 );
     if (computerScore >=20)
        computerHold();

     if (die == 1)
        switchTurn();

 }

The roll() method just simply has the previous line of code in it, "int die = (int)(6.0 * Math.random()) + 1;" i have tried moving it around or even making a place holder for it but if i execute the method and the number is not a 1, it just prints that number until it reaches twenty. I am trying to create a "dice" that will make a NEW number each time it is used.

回答1:

It seems like your roll-method is not handled as a function. You need to return the value generated by your roll() function.

Try this:

int roll() {
    return (int)(6.0 * Math.random()) + 1;
}

and then:

public void computerRoll() { 

    do { 
        int die = roll();
        System.out.println("Roll:"+ die);
        computerScore += die;
     } while (computerScore <= 20 && die >=2 && die <=6 );
     if (computerScore >=20)
         computerHold();

     if (die == 1)
         switchTurn();

 }