为Random.nextInt()指定最大值和最小值? [英] Specify max and min for Random.nextInt()?
问题描述
可能重复:
Java:生成一定范围内的随机数
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);
}
现在的问题是这将返回边和零之间的值,包含,这没有任何意义,因为大多数骰子从1到6、9等.所以我如何指定nextInt应该工作在1到边数之间?
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?
推荐答案
要在 from 和 to (含)之间生成随机的int值(均匀分布),请使用:
To generate a random int value (uniform distribution) between from and to (inclusive) use:
from + rndGenerator.nextInt(to - from + 1)
以您的情况(1 ..面):
In your case (1..sides):
1 + rndGenerator.nextInt(sides)
这篇关于为Random.nextInt()指定最大值和最小值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!