import java.util.Random;
import java.util.Scanner;
public class Captcha {
public static void main(String[] args) {
//获取到随机字符串
String randomStr = captcha();
System.out.println("验证码为:"+ randomStr);
//创建输入对象
Scanner in = new Scanner(System.in);
System.out.print("请输入验证码:");
String str = in.next();
//判断输入字符串与随机字符串是否一致,不区分大小写
if(str.equalsIgnoreCase(randomStr)) {
System.out.println("验证成功!");
}else {
System.out.println("验证失败!");
}
}
//定义一个生成随机四位验证码的方法
public static String captcha() {
//定义一个字符数组,存放大小写字母以及0-9数字
char[] ch = new char[62];
int index = 0;
//存放0-9
for(int i = 48;i<=57;i++) {
ch[index] = (char)(i);
index++;
}
//存放大写字母
for(int i = 65;i<=90;i++) {
ch[index] = (char)(i);
index++;
}
//存放小写字母
for(int i = 97;i<=122;i++) {
ch[index] = (char)(i);
index++;
}
//定义一个空字符串,用于拼接随机字符
String str ="";
//生成四个随机字符
for(int i = 0; i < 4 ;i++) {
char c = ch[new Random().nextInt(ch.length)];
str = str + c;
}
//返回随机字符串
return str;
}
}