feat(class42): 添加生成随机验证码的工具类和测试类- 新增 CodeUtils 类,包含两种生成随机验证码的方法:
- getCode: 生成由小写字母、大写字母和数字组成的验证码 - getCode2: 使用字典字符串生成随机验证码 - 新增 StringTest2 类,用于测试 CodeUtils 类的功能
This commit is contained in:
35
src/class42/CodeUtils.java
Normal file
35
src/class42/CodeUtils.java
Normal 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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
17
src/class42/StringTest2.java
Normal file
17
src/class42/StringTest2.java
Normal 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);
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user