java简单的验证码

 public static void main(String[] args) {
//调用方法
        String code = creatCode(5);
        System.out.println("生成的验证:" + code);

    }

    public static String creatCode(int n){
        String code = "";
        Random r = new Random();

        //定义一个for循环,循环n次,依次生成随机字符
        for (int i = 0; i < n; i++) {
            //生成一个随机字符,字母大写,字母小写,数字
            int type = r.nextInt(3);
            switch (type){
                case 0:
                    char ch = (char) (r.nextInt(26)+65);
                    code += ch;
                    break;
                case 1:
                    char ch1 = (char) (r.nextInt(26) + 97);
                    code += ch1;
                    break;
                case 2:
                    code += r.nextInt(10);
                    break;
            }
        }
        return code;
    }

方法二

 public static void main(String[] args) {
        String datas = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRXTUVWXYZ0123456789";

        String verCode = "";

        //生成随机数
        Random r = new Random();

        for (int i = 0; i < 5; i++) {
            //随机一个索引
            int index = r.nextInt(datas.length());
            //获取某个索引处的字符
            char c = datas.charAt(index);
            verCode += c;
        }
        //输出字符串变量
        System.out.println(verCode);
    }

猜你喜欢

转载自blog.csdn.net/qq_44765534/article/details/126694715