如何在特定范围内生成随机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`.
下面是一个函数,它按照用户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);