Java实现随机验证码的生成

发布时间 2024-01-11 17:52:05作者: 糖糖8888

import java.util.Random;
public class HelloWorld {
public static void main(String []args) {
String code = createCode(5);
System.out.println("验证码为:" + code);
}
public static String createCode(int n){
Random r = new Random();
String code = "";
for(int i = 0;i < n;i++){
int type = r.nextInt(3);
switch(type){
case 0:
//随机一个数字字符
code += r.nextInt(10);;
break;
case 1:
//随机生成一个大写字符 A:65
char ch1 = (char)(r.nextInt(26)+65);
code += ch1;
break;
case 2:
//随机生成一个小写字符 a:97
char ch2 = (char)(r.nextInt(26)+97);
code += ch2;
break;
}
}
return code;
}
}