package yanzhenma;标签:String,System,验证码,captcha,userInput,out From: https://www.cnblogs.com/wanbeibei/p/17709699.html
import java.util.Random;
import java.util.Scanner;
public class CaptchaGenerator {
public static void main(String[] args) {
// 生成随机验证码
String captcha = generateCaptcha();
System.out.println("生成的验证码为:" + captcha);
// 接收用户输入
Scanner scanner = new Scanner(System.in);
System.out.print("请输入验证码:");
String userInput = scanner.nextLine();
// 验证用户输入的验证码
boolean isValid = validateCaptcha(captcha, userInput);
if (isValid) {
System.out.println("验证码输入正确!");
} else {
System.out.println("验证码输入错误!");
}
}
// 生成随机验证码
private static String generateCaptcha() {
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 6; i++) {
int index = random.nextInt(chars.length());
sb.append(chars.charAt(index));
}
return sb.toString();
}
// 验证验证码
private static boolean validateCaptcha(String generatedCaptcha, String userInput) {
return generatedCaptcha.equals(userInput);
}
}