要求:生成一个随机n位数验证码
思路:1.定义一个string类型的变量储存验证码字符串
2.定义一个for循环循环n次
3.把生成的数字和大小写字母交给对应的switch,生成随机的字符
4.然后把随机的字符拼接到string变量
5.循环结束后返回string类型的变量既是验证码结果
代码段:
public class hm_anli_01 {
public static void main(String[] args) {
String code= creat(5);
System.out.println("验证码是:"+code);
}
//定义一个方法生成随机验证码
public static String creat(int n) {
String code="";
Random r=new Random();
//定义for循环依次生成随机字符
for (int i = 0; i < n; i++) {
int type =r.nextInt(3);
switch (type) {
case 0:
//大写字符
char ch=(char)(r.nextInt(26)+65);
code+=ch;
break;
case 1:
//小写字符
char ch1=(char)(r.nextInt(26)+97);
code+=ch1;
break;
case 2:
//数字
code+=r.nextInt(10);
break;
}
}
return code;
}
}