How do I generate a random value between two numbers

Possible Duplicate:
Java: generating random number in a range

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;
链接地址: http://www.djcxy.com/p/17668.html

上一篇: 如何在java中生成一个4位数的随机长整型?

下一篇: 如何在两个数字之间生成一个随机值