Java 为 Random.nextInt() 指定最大值和最小值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3321611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Specify max and min for Random.nextInt()?
提问by Rafe Kettler
Possible Duplicate:
Java: generating random number in a range
可能的重复:
Java:在一个范围内生成随机数
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?
现在问题变成了这将返回边和零之间的值,包括,这没有意义,因为大多数骰子从 1 到 6、9 等。那么我如何指定 nextInt 应该在 1 和边数之间工作?
采纳答案by Eyal Schneider
To generate a random int value (uniform distribution) between fromand to(inclusive) use:
要在from和to(包括)之间生成随机 int 值(均匀分布),请使用:
from + rndGenerator.nextInt(to - from + 1)
In your case (1..sides):
在你的情况下(1..sides):
1 + rndGenerator.nextInt(sides)