如何在特定范围内生成随机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`.
这将生成范围(最小值-最大值)不重复的随机数列表。
generateRandomListNoDuplicate(1000, 8000, 500);
添加此方法。
private void generateRandomListNoDuplicate(int min, int max, int totalNoRequired) {
Random rng = new Random();
Set<Integer> generatedList = new LinkedHashSet<>();
while (generatedList.size() < totalNoRequired) {
Integer radnomInt = rng.nextInt(max - min + 1) + min;
generatedList.add(radnomInt);
}
}
希望这对你有所帮助。