How can i make a “dice” that randomly generates a number 1-6 EACH time it is used?

不问归期 提交于 2020-01-13 20:20:38

问题


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();

 }


来源:https://stackoverflow.com/questions/8410455/how-can-i-make-a-dice-that-randomly-generates-a-number-1-6-each-time-it-is-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!