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

4

6
人们觉得通过谷歌或在这里提问比思考更容易。 - vulkanino
2
考虑到我们有两个已删除的答案,一个不正确的答案和一个严重编辑过的答案,这可能比起初看起来更加困难。 - Thilo
3个回答

9

编写一个类似以下方法的函数:

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大。


9

random.nextInt(max - min + 1) + min可以解决问题。我假设你想要min <= number <= max


1

例子:生成一个1到6的数
因为nextInt(6)返回0-5之间的数,所以必须加1来调整这个数在1-6的范围内

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接