java基础知识点拾遗 随机数的用法

  • 随机数的运用,原文https://www.cnblogs.com/swiftma/p/5808954.html 原理与解析
  • 简单六位随机密码
@Test
    public void sixRandomNum() {
        Random random = new Random();
        char[] chars = new char[6];
        int lendgth = 6;
        for (int i = 0; i < lendgth; i++) {
            // char型 0 = int 型的 48
            //random,nextInt 取值范围是[0,9] ,其对应的'0'+[0,9] 默认int型,范围是[48,57]
            //int 型的[48,57] 强转 char 型范围 [0,9]
            //chars[i] = '0'~'9';
            chars[i] = (char) ('0' + random.nextInt(10));
        }
        System.out.println(new String(chars));

        // 为什么不直接这样拼接呢??
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = lendgth ; i > 0; i--) {
            stringBuilder.append(random.nextInt(10));
        }
        System.out.println(stringBuilder);
    }
  • 简单8位密码(可能由大写,小写,数字,特殊符号组成)
 @Test
    public  void randomPassword(){
        char[] chars = new char[8];
        Random rnd = new Random();
        int length = 8;
        for(int i=0; i<length; i++){
            chars[i] = nextChar(rnd);
        }
        System.out.println(new String(chars));
    }


    //配置特殊符号
    private static final String SPECIAL_CHARS = ".[]-+~<>";
    private static char nextChar(Random rnd){
        switch(rnd.nextInt(3)){
            case 0:
                return (char)('a'+rnd.nextInt(26));
            case 1:
                return (char)('A'+rnd.nextInt(26));
            case 2:
                return    (char)('0'+rnd.nextInt(10));
            default:
                return SPECIAL_CHARS.charAt(rnd.nextInt(SPECIAL_CHARS.length()));
        }
    }
  • 复杂8位密码(至少一个大写字母,一个小写字母,一个特殊符号,一个数字)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值