如何在特定范围内生成随机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`.
使用这些方法可能很方便:
此方法将返回提供的最小值和最大值之间的随机数:
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);