如何在两个数字之间生成随机值

时间:2010-10-11 12:18:25

标签: java

  

可能重复:
  Java: generating random number in a range

如何在两个数字之间生成随机值。 Random.nextInt()为您提供0和传递的值。如何在minValue和maxValue

之间生成一个值

3 个答案:

答案 0 :(得分:9)

random.nextInt(max - min + 1) + min会做到这一点。我假设你想要min <= number <= max

答案 1 :(得分:7)

编写如下方法:

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()论证必须是正面的,来自可以大于

答案 2 :(得分:1)

示例:生成1到6之间的数字 因为nextInt(6)返回0-5的数字,所以需要加1以将数字缩放到1-6范围内

static Random randGen = new Random();
int spots;
. . .
spots = randGen.nextInt(6) + 1;