java生成4位不重复的随机数

方法一:

import java.util.Random;

public class Demo01 {
    public static void main(String[] args) {
        Random random = new Random();
        int code = random.nextInt(9000) + 1000;
        System.out.println(code);
    }
}

方法二:

import java.util.UUID;

public class Demo02 {
    public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 4);
        System.out.println(uuid);
    }
}

方法三:

public class Demo03 {
    public static void main(String[] args) {
        int[] array=new int[4];
        for (int i = 0; i < 4; i++) {
            array[i]=(int)(Math.random()*10);
            for(int j=0;j<i;j++){
                if(array[i]==array[j]){
                    i--;
                }
            }
        }
        for (int i = 0; i < 4; i++) {
            System.out.print(array[i]);
        }
    }
}

方式四:

import java.util.Random;

public class Demo04 {
    public static void main(String[] args) {
        //定义一个字符串(A-Z,a-z,0-9),一共62为
        String str="abcdefghijklmnopqrstuvwzyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        //由Random生成随机数
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        //长度为几就循环几次
        for (int i = 0; i <4 ; i++) {
            //产生0-61的数字
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        System.out.println(sb.toString());
    }
}

方式五:

public class Demo5 {
    public static void main(String[] args) {
        String str="ABCDEF0123456789";
        char[] chars = str.toCharArray();
        StringBuffer sb=new StringBuffer();
        for (int i = 0; i <4 ; i++) {
            int index=(int)(Math.random()*chars.length);
            sb.append(chars[index]);
        }
        System.out.println(sb.toString());
    }
}

方式六:

import java.util.HashSet;
import java.util.Set;

public class Demo6 {
    public static void main(String[] args) {
        Set<Integer> set=new HashSet<Integer>();
        int code;
        while (set.size()<4){
            code=(int)(Math.random()*10000);
            set.add(code);
        }
        for (Integer i:set) {
            System.out.println(i);
        }
    }
}

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值