可能重复:
Java:在范围内生成随机数
我该如何生成两个数字之间的随机值。Random.nextInt() 只能生成介于0和传递值之间的数。我该如何生成介于最小值和最大值之间的数
可能重复:
Java:在范围内生成随机数
我该如何生成两个数字之间的随机值。Random.nextInt() 只能生成介于0和传递值之间的数。我该如何生成介于最小值和最大值之间的数
编写一个类似以下方法的函数:
public static int getRandom(int from, int to) {
if (from < to)
return from + new Random().nextInt(Math.abs(to - from));
return from - new Random().nextInt(Math.abs(to - from));
}
这也考虑到了以下事实:nextInt()
参数必须是正数,而且from可能比to大。
random.nextInt(max - min + 1) + min
可以解决问题。我假设你想要min <= number <= max
例子:生成一个1到6的数
因为nextInt(6)返回0-5之间的数,所以必须加1来调整这个数在1-6的范围内
static Random randGen = new Random(); int spots; . . . spots = randGen.nextInt(6) + 1;