开发者

Specify max and min for Random.nextInt()? [duplicate]

开发者 https://www.devze.com 2023-01-08 09:55 出处:网络
This question already has answers here: Closed 12 years a开发者_开发问答go. Possible Duplicate: Java: generating random number in a range
This question already has answers here: Closed 12 years a开发者_开发问答go.

Possible Duplicate:

Java: generating random number in a range

I want to generate a random int in a logical range. So, say for example, I'm writing a program to "roll" a dice with a specified number of sides.

public int rollDice() {
     Random generator = new Random();
     return generator.nextInt(sides);
}

Now the problem becomes that this will return values between sides and zero, inclusive, which makes no sense because most dice go from 1 to 6, 9, etc. So how can I specify that nextInt should work between 1 and the number of sides?


To generate a random int value (uniform distribution) between from and to (inclusive) use:

from + rndGenerator.nextInt(to - from + 1)

In your case (1..sides):

1 + rndGenerator.nextInt(sides)
0

精彩评论

暂无评论...
验证码 换一张
取 消