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

在使用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;
    }
}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值