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

当前回答

使用nexttint(n)方法为最小值和最大值的差值生成一个随机数,然后将最小值添加到结果中:

Random rn = new Random();
int result = rn.nextInt(max - min + 1) + min;
System.out.println(result);

其他回答

如果掷骰子,它将是1到6(而不是0到6)之间的随机数,因此:

face = 1 + randomNumbers.nextInt(6);
 rand.nextInt((max+1) - min) + min;

范围[最小值最大值](含)内的随机数:

int randomFromMinToMaxInclusive = ThreadLocalRandom.current()
        .nextInt(min, max + 1);

使用nexttint(n)方法为最小值和最大值的差值生成一个随机数,然后将最小值添加到结果中:

Random rn = new Random();
int result = rn.nextInt(max - min + 1) + min;
System.out.println(result);

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