思路:1.利用for循环,循环5次产生5个随机码。
2.随机码中数字调用random来实现,大小写字母也采用random来实现,最后利用ASCII把它转化为字母。
随机产生的是数字,小写字母还是大写字母呢?
利用switch来对应,case值有三个:0,1和2。
利用random产生0,1,2三个随机数。
3.定义一个空字符串,将随机产生的数字和字母添加进去,最后打印输出。
public static void main(String[] args) {
System.out.println("随机验证码为:" + create(5));
}
//生成验证码的方法
public static String create(int n ){
//使用for循环随机生成数字或字母。
String code = "";
for (int i = 0; i < n; i++) {
Random r = new Random();
//随机生成一个数
int type = r.nextInt(3);
//设置一个变量用来接收验证码
switch(type){
case 0:
int num = r.nextInt(9);
code += num;
break;
case 1:
//A的ascII为65,Z为65+25
char c = (char)(r.nextInt(26) + 65);
code += c;
break;
case 2:
//小写字母a为97,z为97+25
char c1 = (char)(r.nextInt(26) + 97);
code += c1;
break;
}
}
return code;
}
结果: