案例:产生1~20之间10个不重复的随机数

public class Demo14 {
public static void main(String[] args){
//创建随机数对象
Random r = new Random();
//创建集合对象
HashSet<Integer> it = new HashSet<>();
//判断长度是否小于10,在范围内就把随机数添加到集合中去
while(it.size()<10){
int num = r.nextInt(20)+1;
it.add(num);
}
//遍历集合
for (Integer x: it){
System.out.println(x);
}
}
}

输出结果:

1
2
19
5
7
8
10
12
13
15

猜你喜欢

转载自www.cnblogs.com/WTBK/p/9424970.html