随机生成6位的字符串验证码,要求包含数字、大小写字母

老师讲的方法

package com.homework;

public class Password {
    public static String getCode(int length){
        String code = "";
        for(int i=0;i<length;i++){
            boolean boo = (int)(Math.random()*2)==0;
            if(boo){
                code += String.valueOf((int)(Math.random()*10));
            }else {
                int temp = (int)(Math.random()*2)==0?65:97;
                char ch = (char)(Math.random()*26+temp);
                code += String.valueOf(ch);
            }
        }
        return code;
    }

    public static void main(String[] args) {

        System.out.println(Password.getCode(6));
        System.out.println("-----------------");
        System.out.println(Password.getVerify(6));
    }

    public static String getVerify(int length){
        String code = "";
        String str = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASFGHJKLZXCVBNM";
        String[] strs = str.split("");
        for(int i = 0;i<length;i++){
            code += strs[(int)(Math.random()*strs.length)];
        }
        return code;
    }
}

网上找的方法

package cn.meiju;

public class Password {
        public static void main(String[] args) {
            char[] arr = {48,49,50,51,52,53,54,55,56,57,//从0到9的数字 
                    65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,//从A到Z的数字 
                    97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122//从a到z的数字 
            }; 
            int i=1; 
            while(i++<=6){ 
                //循环六次,得到六位数的验证码 
            char msg =arr[(int)(Math.random()*62)]; 
            System.out.print(msg); 
            } 
            
        }
}

 

转载于:https://www.cnblogs.com/lev1/p/11267058.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值