获取10个1-20之间的随机数,要求不能重复

需求:获取10个1-20之间的随机数,要求不能重复

/** * 分析: * A:创建产生随机数的对象 * B:创建一个存储随机数的集合。 * C:定义一个统计变量。从0开始。 * D:判断统计遍历是否小于10 * 是:先产生一个随机数,判断该随机数在集合中是否存在。 * 如果不存在:就添加,统计变量++。 * 如果存在:就不搭理它。 * 否:不搭理它 * E:遍历集合 */

<span style="font-size:18px;">public class SetTest {
		public static void main(String[] args) {
			 Random random = new Random();
			int count = 0;
			List<Integer>  list = new ArrayList<Integer>();
			while(count<10){
				int randomNumber = random.nextInt(20)+1;
				if(!list.contains(randomNumber)){
					list.add(randomNumber);
					count++;
				}
			}
			for(int i=0;i<list.size();i++){
				System.out.println(list.get(i));
			}
		}
}</span>

这是使用List集合,如果大家对Set集合有个特点就是不能重复,那么我就都不需要对加入到集合中的数据进行判断

<span style="font-size:18px;">public class SetTest {
		public static void main(String[] args) {
			 Random random = new Random();
			HashSet<Integer>  set = new HashSet<Integer>();
			
			while(set.size()<10){
				int randomNumber = random.nextInt(20)+1;
				set.add(randomNumber);
			}
			
			for(Integer i:set){
				System.out.println(i);
			}
		}
}</span>


经验分享 程序员 微信小程序 职场和发展