1. 程式人生 > >玩具:加減法驗證碼(1+?=4)

玩具:加減法驗證碼(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]); } }