不重复的随机数
- 需求:
编写一个程序,获取10个1-20之间的随机数,要求随机数不能重复,并在控制台输出 - 思路:
- ①创建Set集合对象
- ②创建随机数对象
- ③判断集合的长度是不是小于10
是:产生一个随机数,添加到集合;
回到3继续循环添加; - ④遍历集合
public class SetDemo {
public static void main(String[] args) {
// Set<Integer> set = new HashSet<>();//无序,不会排序
Set<Integer> set = new TreeSet<>();// 有序,会排序
Random r = new Random();
while (set.size() < 10) {
int number = r.nextInt(20) + 1;
set.add(number);
}
for (Integer i : set) {
System.out.print(i + " ");
}
}
}