0
点赞
收藏
分享

微信扫一扫

java实现随机生成验证码

进击的包籽 2023-08-09 阅读 95
import java.util.concurrent.ThreadLocalRandom;

/*
生成验证码的工具
可动态配置验证码长度
 */
public class CodeUtils {
    public static void main(String[] args) {
        //随机生成5个长度为4的验证码
        for (int i = 0; i < 5; i++) {
            System.out.println(CodeUtils.getCode(4));
        }
        for (int i = 0; i < 5; i++) {
            System.out.println(CodeUtils.getCode(6));
        }
    }
    public static String getCode(int len){
        //验证码生成范围
        String s = "0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        char[] c = s.toCharArray();
        StringBuffer str = new StringBuffer("");
        ThreadLocalRandom current = ThreadLocalRandom.current();
        for (int i = 0; i < len; i++) {
            char code = c[current.nextInt(0,s.length())];
            str.append(code);
        }
        return str.toString();
    }
}

运行结果:
在这里插入图片描述

举报

相关推荐

0 条评论