获取十个一到二十的随机数,要求不可重复(升级版)

 相比上一个,代码简洁了很多

import java.util.HashSet;
import java.util.Random;

/*
 *编写一个程序,获取10到20个随机数,要求随机数不能重复
 *
 *分析:
 *		创建随机数对象
 *		创建set集合
 *		判断集合的长度是否小于10
 *			是:创建随机数添加
 *		遍历集合	
 */
public class HashSetDemo {
	public static void main(String[] args) {
		// 创建随机数对象
		Random r = new Random();

		// 创建集合
		HashSet<Integer> hs = new HashSet<Integer>();

		while (hs.size() < 10) {
			int num = r.nextInt(20) + 1;
			hs.add(num);
		}

		// 遍历
		for (Integer i : hs) {
			System.out.println(i);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41690324/article/details/81138099