package com.yahe.myutil;
import java.util.Scanner;
/**
* 自动生成验证码及验证
*
* @author yahe
*
*/
public class VerificationCode {
* 自动生成验证码及验证
*
* @author yahe
*
*/
public class VerificationCode {
public static void main(String[] args) {
String vCode = null;
vCode = createVerificationCode(7);
System.out.println(vCode);
Scanner scr = new Scanner(System.in);
if (checkVerificationCode(vCode, scr.next())) {
System.out.println("ok");
} else {
System.out.println("error");
}
}
vCode = createVerificationCode(7);
System.out.println(vCode);
Scanner scr = new Scanner(System.in);
if (checkVerificationCode(vCode, scr.next())) {
System.out.println("ok");
} else {
System.out.println("error");
}
}
/**
* 产生指定长度的验证码
*
* @param length
* 验证码长度
* @return 验证码
*/
public static String createVerificationCode(int length) {
String vCode = "";
for (int i = 0; i < length; i++) {
int judge = (int) (Math.random() * 2);
if (judge == 0) {
vCode = vCode + (int) (Math.random() * 10);
} else {
judge = (int) (Math.random() * 2);
if (judge == 0) {
vCode = vCode + (char) (65 + (Math.random() * 24));
} else {
vCode = vCode + (char) (97 + (Math.random() * 24));
}
}
}
return vCode;
}
* 产生指定长度的验证码
*
* @param length
* 验证码长度
* @return 验证码
*/
public static String createVerificationCode(int length) {
String vCode = "";
for (int i = 0; i < length; i++) {
int judge = (int) (Math.random() * 2);
if (judge == 0) {
vCode = vCode + (int) (Math.random() * 10);
} else {
judge = (int) (Math.random() * 2);
if (judge == 0) {
vCode = vCode + (char) (65 + (Math.random() * 24));
} else {
vCode = vCode + (char) (97 + (Math.random() * 24));
}
}
}
return vCode;
}
/**
* 验证检查用户输入验证码是否正确
*
* @param sysVCode
* 系统生成的验证码
* @param userVCode
* 用户输入的验证码
* @return 如果正确返回true
*/
public static boolean checkVerificationCode(String sysVCode,
String userVCode) {
boolean result = false;
if (sysVCode.equals(userVCode.trim())) {
result = true;
}
return result;
}
}
* 验证检查用户输入验证码是否正确
*
* @param sysVCode
* 系统生成的验证码
* @param userVCode
* 用户输入的验证码
* @return 如果正确返回true
*/
public static boolean checkVerificationCode(String sysVCode,
String userVCode) {
boolean result = false;
if (sysVCode.equals(userVCode.trim())) {
result = true;
}
return result;
}
}