随机生成指定长度的验证码(非图片版)

public static String builderVerificationCode(int codeLength){
        String verificationCode = "";
        Random random = new Random();
        if(codeLength <= 0){
            return verificationCode;
        }
        //生成6位验证码
        for(int i = 0; i < codeLength; i++) {
            //0为字符,1为数字
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";  
            if( "char".equalsIgnoreCase(charOrNum) ) {
                //大写或者小写
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;  
                verificationCode += (char)(random.nextInt(26) + temp);  
            } else if( "num".equalsIgnoreCase(charOrNum) ) {//数字  
                verificationCode += String.valueOf(random.nextInt(10));  
            }  
        }
        return verificationCode;
    }

你可能感兴趣的:(Java)