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);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值