可指定数字个数和范围,返回不重复的随机数字
参数类型 | 参数名 | 作用 |
---|---|---|
int | scope | 需要生成的随机数字的个数,例如:8个随机数字 |
int | total | 数字范围例如:1~100 |
// 生成指定范围的随机数字【不重复】
public List<Integer> randomNum(int scope, int total) {
List<Integer> mylist = new ArrayList<>(); // 用于储存不重复的随机数
Random rd = new Random();
while (mylist.size() < scope) {
int myNum = rd.nextInt(total);
if (!mylist.contains(myNum += 1)) { // 判断容器中是否包含指定的数字
mylist.add(myNum); // 往集合里面添加数据。
}
}
return mylist;
}