玩具:加减法验证码(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]);
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-07-17 00:18  土豆条  阅读(428)  评论(0编辑  收藏  举报