如何在特定范围内生成随机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`.

当前回答

Java 17引入了RandomGenerator接口,它提供了一个int nextInt(int origin,int bound)方法来获取范围内的随机整数:

// Returns a random int between minimum (inclusive) & maximum (exclusive)
int randomInt = RandomGenerator.getDefault().nextInt(minimum, maximum);

除了用于Java17中添加的新的随机生成算法之外,该接口还添加到现有的随机生成类(random、SecureRandom、SplitableRandom和ThreadLocalRandom)中。因此,从Java 17开始,这些类具有以下有界nextInt方法:

new Random().nextInt(minimum, maximum);
new SecureRandom().nextInt(minimum, maximum);
new SplittableRandom().nextInt(minimum, maximum);
new ThreadLocalRandom().nextInt(minimum, maximum);

从Java17开始,这种方法是Random和SecureRandom的新方法。在Java17之前,ThreadLocalRandom和SplitableRandom已经有了这个方法,尽管它不是由共享接口指定的。

其他回答

如果您已经使用Commons Lang API 3.x或最新版本,那么有一个类用于随机数生成RandomUtils。

public static int nextInt(int startInclusive, int endExclusive)

返回指定范围内的随机整数。

参数:

startInclusive-指定的起始值

endExclusive-指定的结束值

int random = RandomUtils.nextInt(999,1000000);

注:在RandomUtils中,有许多生成随机数的方法

以下是使用Random和forEach的另一个示例

int firstNum = 20;//Inclusive
int lastNum = 50;//Exclusive
int streamSize = 10;
Random num = new Random().ints(10, 20, 50).forEach(System.out::println);

下面是一个函数,它按照用户42155的请求,在lowerBoundIncluded和upperBoundIncluded定义的范围内返回一个整数随机数

SplitableRandom splitableRandom=新的Splitablerandom();

BiFunction<Integer,Integer,Integer> randomInt = (lowerBoundIncluded, upperBoundIncluded)
    -> splittableRandom.nextInt(lowerBoundIncluded, upperBoundIncluded + 1);

randomInt.apply(…,…);//获取随机数

…或更短,用于一次性生成随机数

new SplittableRandom().nextInt(lowerBoundIncluded, upperBoundIncluded + 1);

使用Apache Lang3 Commons

Integer.parseInt(RandomStringUtils.randomNumeric(6, 6));

最小值100000到最大值999999

我已经创建了一个方法来获取给定范围内的唯一整数。

/*
      * minNum is the minimum possible random number
      * maxNum is the maximum possible random number
      * numbersNeeded is the quantity of random number required
      * the give method provides you with unique random number between min & max range
*/
public static Set<Integer> getUniqueRandomNumbers( int minNum , int maxNum ,int numbersNeeded ){

    if(minNum >= maxNum)
        throw new IllegalArgumentException("maxNum must be greater than minNum");

    if(! (numbersNeeded > (maxNum - minNum + 1) ))
        throw new IllegalArgumentException("numberNeeded must be greater then difference b/w (max- min +1)");

    Random rng = new Random(); // Ideally just create one instance globally

    // Note: use LinkedHashSet to maintain insertion order
    Set<Integer> generated = new LinkedHashSet<Integer>();
    while (generated.size() < numbersNeeded)
    {
        Integer next = rng.nextInt((maxNum - minNum) + 1) + minNum;

        // As we're adding to a set, this will automatically do a containment check
        generated.add(next);
    }
    return generated;
}