需求:
定义方法实现随机产生一个指定位数的验证码,每位可能是数字、大写、小写字母
分析:
定义一个方法,生成验证码返回:返回值类型是String,需要形参接收位数。
在方法内部使用for循环依次生成每位随机字符,并连接起来。
把连接好的随机字符作为一组验证码返回。
随机验证码的核心实现逻辑是如何进行的?
定义一个String类型的变量存储验证码字符。
定义一个for循环,循环5次。
随机生成0|1|2的数据,依次代表当前位置要生成数字|大写字母|小写字母。
把0、1、2交给switch生成对应类型的随机字符,把字符交给String变量。
循环结束后,返回String类型的变量即是所求的验证码结果。
代码:
public class RandomCode {
public static void main(String[] args) {
// 5、调用方法得到一个随机的验证码
Scanner sc =new Scanner(System.in);
while (true) {
String code = createCode(5);
System.out.print("随机生成的验证码为:");
System.out.println(code);
System.out.print("请输入验证码(忽略大小写):");
String inputCode = sc.next();
if (code.equalsIgnoreCase(inputCode)){
System.out.println("验证码输入正确");
return;
}else {
System.out.println("验证码输入错误!请重新输入!!!");
}
}
}
/**
* 1、定义一个方法返回一个随机验证码 返回值类型 String 形参:int n
**/
public static String createCode(int n){
// 3、定义一个字符串变量来记录生成的随机字符
String code = "";
Random r = new Random();
// 2、定义一个for循环,循环n次,依次生成随机字符
for (int i = 0; i < n; i++) {
// 4、生成一个随机字符:英文大写,英文小写,数字 (0 1 2)
// type表示当前位置要生成的随机字符的类型
int type = r.nextInt(3);
switch (type){
case 0:
// 大写字符 (A 65 - Z 65+25 ) (0-25) +65
char ch = (char)(r.nextInt(26) + 65);
code +=ch;
break;
case 1:
// 小写字符 (a 97 - z 97+25 ) (0-25) +97
char ch1 = (char)(r.nextInt(26) +97);
code +=ch1;
break;
default:
// 数字字符 (0-9)
code+=r.nextInt(10);
break;
}
}
return code;
}
}