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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3906081/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 06:38:03  来源:igfitidea点击:

How do I generate a random value between two numbers

java

提问by user339108

Possible Duplicate:
Java: generating random number in a range

可能的重复:
Java:在一个范围内生成随机数

How do I generate a random value between two numbers. Random.nextInt()gives you between 0 and the passed value. How do I generate a value between minValue and a maxValue

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

采纳答案by Margus

Write a method like:

写一个方法,如:

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));
}

This also takes account for facts, that nextInt()argument must be positive, and that fromcan be bigger then to.

这也考虑了事实,即nextInt()参数必须是积极的,而可以更大然后

回答by Petar Minchev

random.nextInt(max - min + 1) + minwill do the trick. I assume you want min <= number <= max

random.nextInt(max - min + 1) + min会做的伎俩。我假设你想要min <= number <= max

回答by cloverink

Example: Generating a number from 1 to 6
Because nextInt(6) returns a number from 0-5, it's necessary to add 1 to scale the number into the range 1-6

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

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