欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java中如何生成6个不重复的随机数一次性成功!

程序员文章站 2022-05-03 23:41:03
在使用Java生成随机数时,这里有两种方式:①是使用Set的不可重复性,来生成的,下面我们来看代码:public class RandomTest{ public static void main(String[] args) { Set set = new HashSet<>(); Random rand = new Random(); int index = 0; while (tru...

在使用Java生成随机数时,这里有两种方式:
①是使用Set的不可重复性,来生成的,下面我们来看代码:

public class RandomTest{ public static void main(String[] args) { Set<Integer> set = new HashSet<>(); Random rand = new Random(); int index = 0; while (true) { int s = rand.nextInt(33)+1; if (set.contains(s)) { s = rand.nextInt(33)+1; }else{ set.add(s); index++; } if (index == 6) { break; } } for (Integer integer : set) { System.out.print(integer +","); } System.out.println(); } 

② 是通过boolean来判断当前的元素是否插入到集合中了

public class RandomTest{ public static void main(String[] args) { ArrayList<Integer> red = new ArrayList<>(); Random rand = new Random(); for (int i = 0; i < 6; i++) { int s = rand.nextInt(33) + 1; if (CunZai(red, s)) { red.add(s); }else{ //这里注意,必须得i--,要不然,集合中如果有重复的元素就会空位置,必须让它回退到前一个重新生成 i--; } } } public static boolean CunZai(ArrayList<Integer> arr ,int i){ for (int j = 0; j < arr.size(); j++) { if (arr.get(j) == i) { return false; } } return true; } } 

运行结果:
Java中如何生成6个不重复的随机数一次性成功!

本文地址:https://blog.csdn.net/weixin_42893085/article/details/107874712

相关标签: java