如何在特定范围内生成随机int值?

以下方法存在与整数溢出相关的错误:

randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.

当前回答

Use:

minValue + rn.nextInt(maxValue - minValue + 1)

其他回答

Random random = new Random();
int max = 10;
int min = 3;
int randomNum = random.nextInt(max) % (max - min + 1) + min;
import java.util.Random; 

public class RandomUtil {
    // Declare as class variable so that it is not re-seeded every call
    private static Random random = new Random();

    /**
     * Returns a psuedo-random number between min and max (both inclusive)
     * @param min Minimim value
     * @param max Maximim value. Must be greater than min.
     * @return Integer between min and max (both inclusive)
     * @see java.util.Random#nextInt(int)
     */
    public static int nextInt(int min, int max) {
        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        return random.nextInt((max - min) + 1) + min;
    }
}

我只是使用Math.random()生成一个随机数,然后将其乘以一个大数,比方说10000。因此,我得到一个介于0到10000之间的数字,并将其称为I。现在,如果我需要介于(x,y)之间的数字时,请执行以下操作:

i = x + (i % (y - x));

所以,所有的i都是x和y之间的数字。

要消除注释中指出的偏差,而不是将其乘以10000(或大数字),请将其乘以(y-x)。

Use:

Random ran = new Random();
int x = ran.nextInt(6) + 5;

整数x现在是可能结果为5-10的随机数。

另一种选择是使用Apache Commons:

import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;

public void method() {
    RandomData randomData = new RandomDataImpl();
    int number = randomData.nextInt(5, 10);
    // ...
 }