public class IdenifyingCode {
// 得到1-9 a-z A-Z的无序字符数组
public static char[] getLetter() {
// 一开始装有序的
char[] a = new char[62];
// 用来装无序的
char[] a1 = new char[62];
// 这是无序的整数数组
int[] a2 = getDisOrder();
for (int i = 48; i <= 48 + 9; i++) {
a[i - 48] = (char) i;
}
for (int i = 97; i <= 97 + 25; i++) {
a[i - 97 + 10] = (char) i;
}
for (int i = 65; i <= 65 + 25; i++) {
a[i - 65 + 36] = (char) i;
}
// 打乱
for (int i = 0; i < 62; i++) {
a1[i] = a[a2[i]];
}
return a1;
}
// 得到0-61随机不重复乱序数组(随机得到一个数后,将其置于数组末尾,减小随机范围,继续循环)
public static int[] getDisOrder() {
int[] a = new int[62];
for (int i = 0; i < a.length; i++) {
a[i] = i;
}
int index;
for (int i = 62; i > 0; i--) {
index = (int) (Math.random() * i);
swap(a, index, i - 1);
}
return a;
}
// 交换值
public static void swap(int[] a, int x, int y) {
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
// 验证码的判断
public static char[] getJudgeCode(char[] a) {
char[] a1 = new char[4];
for (int i = 0; i < 4; i++) {
a1[i] = a[(int) (Math.random() * 62)];
}
return a1;
}
// 程序入口
public static void start() {
Scanner sc = new Scanner(System.in);
char[] a = getJudgeCode(getLetter());
System.out.print("验证码:");
for (char c : a) {
System.out.print(c + " ");
}
System.out.println();
System.out.println("请输入验证码:");
String str = sc.nextLine();
boolean flag = true;
for (int j = 0; j < 4; j++) {
if (!compareIgnoreCase(str.charAt(j), a[j])) {
flag = false;
}
}
if (flag) {
System.out.println("验证成功");
} else {
System.err.println("验证码输入错误,请重新输入");
System.out.println();
start();
}
}
// 无视大小写字符判断
public static boolean compareIgnoreCase(char a, char b) {
if (a == b || a == Character.toLowerCase(b) || a == Character.toUpperCase(b)) {
return true;
}
return false;
}
public static void main(String[] args) {
start();
}
}