玩具:加减法验证码(1+?=4)

遇到个小需求要写一个验证码功能,就是加减法,囧,感觉挺好玩的就顺手写了。代码简单的囧……纯属自娱自乐,凑数,Orz~~
生成图片的部分没写,逻辑都差不多。主要注意:干扰线,噪点,变形,背景色就OK。我用的现成的代码,就不发了。

/**
 * 加减法验证码
 */
public class VerifyCodeUtil {
    private final static Map<Integer, String> TYPE = new HashMap<>(2);
    private final static int SUB = 0;
    private final static int PLUS = 1;
    static {
        TYPE.put(SUB, "-");
        TYPE.put(PLUS, "+");
    }
    public static String[] generate() {
        Random random = new Random();
        int type = random.nextInt(2);
        int[] arr = new int[]{random.nextInt(50), random.nextInt(50), Integer.MAX_VALUE};
        switch (type) {
            case SUB :  // 不出现负数
                if (arr[0] < arr[1]) {
                    arr[0] ^= arr[1];
                    arr[1] ^= arr[0];
                    arr[0] ^= arr[1];
                }
                arr[2] = arr[0] - arr[1];
                break;
            case PLUS :
                arr[2] = arr[0] + arr[1];
                break;
        }
        String[] ret = new String[] {arr[0] + "", arr[1] + "", arr[2] + ""};
        // 选一随机位置为"?"
        int pos = random.nextInt(3);
        String answer = ret[pos];
        ret[pos] = "?";
        return new String[]{ret[0]+TYPE.get(type) + ret[1] + "=" + ret[2], answer};
    }

    public static void main(String[] args) {
        String[] s = generate();
        System.out.println("verify code:" + s[0]);
        System.out.println("answer:" + s[1]);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值