Files
2025ClassOfJava/C10-Swing/src/utils/CaptchaUtils.java
2025-11-20 17:01:56 +08:00

54 lines
1.8 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package utils;
import java.util.Random;
/**
* 验证码工具类
*/
public class CaptchaUtils { // final修饰类不能被继承
// 【任务1】静态常量字符集全局固定
static final String CHAR_SET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// 【任务2】静态常量验证码长度全局固定
static final int CAPTCHA_LENGTH=4;
// 【任务3】私有构造方法禁止创建实例工具类无需实例化
private CaptchaUtils(){
}
/**
* 【任务4】
* 静态方法generateCaptcha 生成随机验证码
* @return String 返回生成的随机验证码字符串
*/
public static String generateCaptcha(){
Random random = new Random();
//生成随机验证码
StringBuilder sb = new StringBuilder();
for(int i=0;i<CAPTCHA_LENGTH;i++){
//生成随机数索引
int index = random.nextInt(CHAR_SET.length());
//根据索引获取随机字符
sb.append(CHAR_SET.charAt(index));
}
return sb.toString();
}
/**
* 【任务5】
* 静态方法verifyCaptcha 验证验证码
* @param inputCaptcha 用户输入的验证码
* @param systemCaptcha 系统生成的验证码
* @return boolean 验证结果true表示验证通过false表示验证失败
*/
public static boolean verifyCaptcha(String inputCaptcha,String systemCaptcha){
return inputCaptcha.equalsIgnoreCase(systemCaptcha);
}
public static void main(String[] args) {
for(int i=0;i<10;i++)
System.out.println(generateCaptcha());
System.out.println(CaptchaUtils.verifyCaptcha(generateCaptcha(), generateCaptcha()));
}
}