我与夏风皆过客,惟愿博肖揽星河!

xzwyb

导航

java Random验证码

import java.util.Random;
public class RandomCreateCode {
    public static String createCode() {
        //字符库
        char[] chs = {'1', '2', '3', '4', 'a', 'b', 'c', 'd', '博', '君', '一', '肖'};
        //创建StringBuilder对象
        StringBuilder sb = new StringBuilder();
        //随机4位字符库中的字符,随机索引值
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            //随机索引值:正整数,不能大于数组长度
            int randomIndex = random.nextInt(chs.length);
            char ch = chs[randomIndex];
            sb.append(ch);
        }
        //转换为字符串
        String code = sb.toString();
//        System.out.println(code);
        return code;
    }

    public static void main(String[] args) {
        String code = RandomCreateCode.createCode();
        System.out.println("random code is:" + code);
    }
}

 

posted on 2022-04-09 18:25  B2328X  阅读(36)  评论(0编辑  收藏  举报