需求:
编写一个程序,获取10个1-100之间的随机数,要求随机数不能重复,并在控制台打印输出
有两种方法:
1、使用HashSet集合实现
2、使用TreeSet集合实现 (在控制台按大小打印输出)
两中方法只有创建Set对象的时候有区别
1、用HashSet集合实现:
//测试类
import java.util.*;
public class work11{
public static void main(String[] args){
//创建Set对象
Set<Integer> set = new HashSet<>();
//创建随机数对象
Random r = new Random();
//判断set集合中的元素个数是否小于10
while (set.size()<10){
int x = r.nextInt(100)+1; //生成随机数的范围[1-101]
set.add(x);
}
//用增强for循环实现遍历
for(Integer i:set){
System.out.println(i);
}
}
}
结果:
2、用TreeSet实现(在控制台上会按大小输出):
//测试类
import java.util.*;
public class work11{
public static void main(String[] args){
//创建Set对象
Set<Integer> set = new TreeSet<>();
//创建随机数对象
Random r = new Random();
//判断set集合中的元素个数是否小于10
while (set.size()<10){
int x = r.nextInt(100)+1; //生成随机数的范围[1-101]
set.add(x);
}
//用增强for循环实现遍历
for(Integer i:set){
System.out.println(i);
}
}
}
结果:
本人新手菜鸡一枚,请大佬们多多指教。
如果感觉此篇文章对你有帮助的话,请帮博主点一个免费的赞,谢谢大家!