开发者

How do I generate a random value between two numbers [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Java: generating random number in a ran开发者_开发百科ge

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


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 from can be bigger then to.


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


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜