feat(class42): 添加生成随机验证码的工具类和测试类- 新增 CodeUtils 类,包含两种生成随机验证码的方法:

- getCode: 生成由小写字母、大写字母和数字组成的验证码
  - getCode2: 使用字典字符串生成随机验证码
- 新增 StringTest2 类,用于测试 CodeUtils 类的功能
This commit is contained in:
2025-08-06 13:36:02 +08:00
parent a3786fd82b
commit 900a9908c8
2 changed files with 52 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
package class42;
public class CodeUtils {
public static String getCode(int n) {
StringBuilder code = new StringBuilder();
int Index;
for (int i = 0; i < n; i++){
//随机0-2
Index = (int)(Math.random() * 3);
switch ( Index){
case 0:
code.append((char) (Math.random() * 26 + 'a'));
break;
case 1:
code.append((char) (Math.random() * 26 + 'A'));
break;
case 2:
code.append((int) (Math.random() * 10));
break;
}
}
return code.toString();
}
public static String getCode2(int n){
String dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String code = "";
for (int i = 0; i < n; i++) {
int index = (int)(Math.random() * dict.length());
code += dict.charAt(index);
}
return code;
}
}

View File

@@ -0,0 +1,17 @@
package class42;
public class StringTest2 {
public static void main(String[] args) {
String code= CodeUtils.getCode(4);
System.out.println(code);
String code2 = CodeUtils.getCode2(4);
System.out.println(code2);
}
}