后端java生成验证码

验证码生成代码

package com.inspur;

import java.util.Scanner;

/**
 * @author l
 * @time 2020.11.12 9:17
 * @ 产生一个区分大小写的四位数字字母组合验证码
 */
public class Captcha {
    /**
     * @return 产生一个0~9的数字
     */
    private int math() {
        return (int) (Math.random() * (9 - 0 + 1));
    }

    //产生一个0~9的数字
    private int math2() {
        return (int) (Math.random() * 10);
    }

    //产生一个a~z的字母(97-122)
    private char math3() {
        //其实此处直接换成26也可以
        return (char) (Math.random() * (122 - 97 + 1) + 97);
    }

    //产生一个A~Z的字母(65-90)
    private char math4() {
        //其实此处直接换成26也可以
        return (char) (Math.random() * (90 - 65 + 1) + 65);
    }

    public static boolean createCode() {
        Captcha c = new Captcha();
        //保存随机产生一个1-4的数字
        int temp;
        //初始化验证码
        String code = "";
        for (int i = 0; i < 4; i++) {
            //随机选择数字或字母
            temp = (int) (Math.random() * (4) + 1);
            switch (temp) {
                case 1:
                    int a = c.math();
                    code += a;
                    break;
                case 2:
                    String b = String.valueOf(c.math2());
                    code += b;
                    break;
                case 3:
                    String d = String.valueOf(c.math3());
                    code += d;
                    break;
                case 4:
                    String e = String.valueOf(c.math4());
                    code += e;
                    break;
                default:
            }
        }
        System.out.println(code);
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入验证码(区分大小写)");
        String code2 = scanner.next();
        if (code.equals(code2)) {
            System.out.println("验证成功");
            return true;
        } else {
            System.out.println("验证码输入失败");
            return false;
        }
    }

}

`
Main类测试

package com.inspur;
/*
在浪*公司的时候没事就整了个验证码生成,项目中可以传到前台进行使用
感觉还有点不完美的地方是没有加密算法,传到前台再进行反转和随机背景
 */
public class Main {

    public static void main(String[] args) {
	// write your code here
        boolean b=Captcha.createCode();
        System.out.println(b);
    }
}

效果还不错,记录一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值