java小项目-验证码的生成以及验证

来源:互联网 发布:linux 百度云盘同步 编辑:程序博客网 时间:2024/05/20 18:42

蛤

public class ValidateCode {    //方法一    public String genCode1() {        /*初始化种子库*/        int[] chars = new int[62];        int index = 0;        for (int i = 48; i <= 122; i++) {            if((i > 57 && i<65) || (i > 90 && i< 97)){                continue;            }               chars[index++] = i;        }        /*生成验证码*/        String code = "";        Random r = new Random();        for (int i = 0; i < 4; i++) {            code += (char)chars[r.nextInt(chars.length)];        }        return code;    }    //方法二    public String genCode2(){        String code = "";        String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";        Random r = new Random();        for (int i = 0; i < 4; i++) {            code += chars.charAt(r.nextInt(chars.length()));        }        return code;    }    public void validate(){        //生成一个验证码        String code = genCode1();        startValidate(code);    }    private void startValidate(String code) {        System.out.println(code);        System.out.println("请输入验证码");        Scanner sc = new Scanner(System.in);        String inputCode = sc.nextLine();        if(code.equalsIgnoreCase(inputCode)){            System.out.println("验证成功!");            return;        }        System.out.println("验证码输入错误,请重新输入");        startValidate(code);    }    public static void main(String[] args) {        new ValidateCode().validate();    }}

就这么简单啦~

原创粉丝点击