Java随机生成验证码,并且是2+2+2类型

package Demo01;

import java.util.Random;

/*
 * 随机验证码。
 * 保证验证码是2+2+2类型
 * 随机生成十组六位字符组成的验证码。
 * 验证码由大小写字母、数字字符组成。
 */
public class main {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println("生成的随机验证码:"+GetCaptcha());
        }

    }
    public static String GetCaptcha(){
        String letter = "qwertyuioplkjhgfdsazxcvbnm";
        // 将所有待选项转转变成char数组
        char [] lower = letter.toCharArray();
        char [] capital = letter.toUpperCase().toCharArray();
        char [] integer = "0123456789".toCharArray();
        char [] result = new char[6];
        Random r = new Random();
        // 总的验证码个数计数
        int count = 0;
        // 随机数索引,0-数字,1-小写字母,2-大写字母
        int index = 0;
        // 整数计数
        int intcount = 0;
        // 小写字母计数
        int lowercount = 0;
        // 大写字母计数
        int capitalcount = 0;
        // 保证生成6位验证码
        while (count < 6) {
            index = r.nextInt(3);
            // 保证不超过2位的相同类型字符
            if (index == 0 && intcount < 2){
                result[count] = integer[r.nextInt(10)];
                intcount++;
                count++;
            }else if (index == 1 && lowercount < 2){
                result[count] = lower[r.nextInt(26)];
                lowercount++;
                count++;
            }else if (index == 2 && capitalcount < 2){
                result[count] = capital[r.nextInt(26)];
                capitalcount++;
                count++;
            }
        }
        return String.valueOf(result);
    }
}


版权声明:本文为weixin_43945332原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。