一. 验证码需求
1.随机产生一个指定位数的验证码。
2.必须包含大写字母,小写字母,数字。
3.每位都可能包含大写字母,小写字母,数字。
二.分析
1.定义一个方法,生成验证码返回,方法参数为int,返回值类型为String.
2.用Random方法随机出0,1,2三个数字,0代表数字,1代表大写字母,2代表小写字母.
3.用switch做选择
case:0则在0~9中任意取一个值
case:1则取在ascii表中大写字母的对应值,并强转成char类型
case:2则取在ascii表中小写字母的对应值,并强转成char类型
三.代码实现
public class Demo02 {
public static void main(String[] args) {
// 调用Code方法,并给定验证码长度
System.out.println("请输入验证码的长度");
Scanner in =new Scanner(System.in);
int n = in.nextInt();
String code = Code(n);
System.out.println("验证码为:" +code);
}
//定义Code方法
public static String Code(int a) {
// 定义一个空字符串
String code = "";
// 创建Random对象
Random r = new Random();
for (int i = 0; i < a; i++) {
// 确定字符类型(0代表数字,1代表大写字母,2代表小写字母)
int type = r.nextInt(3);
switch (type) {
case 0:
// 随机生成一个0~9数字
code += r.nextInt(10);
break;
case 1:
// 随机生成一个65~90的数字,然后强转为大写字母
code += (char) (r.nextInt(26) + 65);
break;
case 2:
// 随机生成一个97~122的数字,然后强转为小写字母
code += (char) (r.nextInt(26) + 97);
break;
}
}
return code;
}
}
四.总结
验证码在互联网的各个领域都用的上,能有效防止AI介入影响用户体验,是用户安全的一个强有力的保障。