利用HashSet 只能存放不同的值 public class zuo { public static void main(String[] args) { HashSet<Integer> set = new HashSet<>(); int min = 2, max = 200, n = 10; randomSet(min, max, n, set); } public static void randomSet(int min, int max, int n, HashSet<Integer> set) { if (n > (max - min + 1) || max < min) return; for (int i = 0; i < n; i++) { int num = (int) (Math.random() * (max - min)) + min; set.add(num);//将不同的数存入HashSet中 } int setSize = set.size();//存入的数不够 递归调用再生成随机数 if (setSize < n) { randomSet(min, max, n - setSize, set); } for (Object obj:set){ System.out.println(obj); } } }
生成不重复的随机数
最新推荐文章于 2024-06-20 16:42:54 发布