需求:定义方法实现随机产生一个5位的验证码,每位可能是数字、大写字母、小写字母。
分析:
1.定义一个方法,生成验证码返回:方法参数是位数,方法的返回值类型是String。
2.在方法内部使用for循环生成指定位数的随机字符,并连接起来。
3.把连接好的随机字符作为一组验证码进行返回。
package com.itheima;
import java.util.Random;
public class Test3 {
public static void main(String[] args) {
//4.调用获取验证码的方法得到一个随机的验证码
String code = createCode(6);
System.out.println("随机验证码: " + code);
}
//1.定义一个方法
public static String createCode(int n){
//3.定义一个字符串变量记录生成的随机字符
String code = "";
Random r = new Random();
//2.定义for循环
for (int i = 0; i < n; i++) {
//3.生成一个随机字符:英文大写、英文小写、数字 0 1 2
int type = r.nextInt(3);
switch(type){
case 0:
//大写字母(65-90)
char ch = (char) (r.nextInt(26) + 65);
code += ch;
break;
case 1:
//小写字母(97-122)
char ch1 = (char) (r.nextInt(26) + 97);
code += ch1;
break;
case 2:
//数字
code += r.nextInt(10);//0-9
break;
}
}
return code;
}
}