Basic Random Rolling Dice Java

前端 未结 5 954
栀梦
栀梦 2021-01-05 11:31

I am trying to write a method rollDice(int number, int nSides) which returns the total result of rolling the number dice with nSides sides.

So for example rollDice(3

5条回答
  •  执笔经年
    2021-01-05 11:46

    Random.nextInt() has unpredicable behaviour - it can produce all values possible for an integer, including negative numbers. Use Random.nextInt(numSides) instead - it will return an integer from [0,numSides) i.e. including 0 and excluding numSides. To get your desired functionality [1,numSides] use

    r.nextInt(numSides)+1;
    

    See here for more information.

提交回复
热议问题