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

当前回答

我想知道Apache Commons Math库提供的任何随机数生成方法是否符合要求。

例如:RandomDataGenerator.nextInt或RandomDataGenerator.nextLong

其他回答

你可以使用

RandomStringUtils.randomNumeric(int count)

该方法也来自Apache Commons。

使用这些方法可能很方便:

此方法将返回提供的最小值和最大值之间的随机数:

public static int getRandomNumberBetween(int min, int max) {
    Random foo = new Random();
    int randomNumber = foo.nextInt(max - min) + min;
    if (randomNumber == min) {
        // Since the random number is between the min and max values, simply add 1
        return min + 1;
    } else {
        return randomNumber;
    }
}

并且该方法将从所提供的最小值和最大值返回随机数(因此生成的数也可以是最小值或最大值):

public static int getRandomNumberFrom(int min, int max) {
    Random foo = new Random();
    int randomNumber = foo.nextInt((max + 1) - min) + min;

    return randomNumber;
}

下面是一个函数,它按照用户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);
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;
    }
}

一般使用java.utilforRandom。

您可以定义最小和最大范围以获得这些结果。

Random rand=new Random();
rand.nextInt((max+1) - min) + min;