1.需求
验证码开发,用户可根据自己的需求,随机生成n位验证码
2.代码
import java.util.Random;
/**
* 项目需求:验证码开发
* 定义方法实现随机产生一个五位的验证码,每位可能是数字,大写字母,小写字母
*/
public class Test4 {
public static void main(String[] args) {
System.out.println(creteCode(5));
}
//定义一个方法返回一个随机验证码
public static String creteCode(int n){
String code = "";
Random random = new Random();
//定义一个for循环,循环n次,依次生产随机字符
for (int i = 0; i < n; i++) {
int type = random.nextInt(3);//0,1,2
// System.out.println(type);
switch (type){
case 0:
//大写字符(A 65+0 - Z 65+25)
char ch = (char) (random.nextInt(25) + 65);
code+=ch;
break;
case 1:
//小写字符(a 97+0 - z 97+25) (0-25)+97
char ch1 = (char)(random.nextInt(25)+97);
code += ch1;
break;
case 2:
//数字字符
int ch3 = random.nextInt(9);
code += ch3;
}
}
return code;
}
}
3.考点
Random的使用
random.nextInt(n),生成0~n范围内的数字,不包括n
使用数组存储生成的字符
A ~ Z范围是65~65+25
a ~ z范围是97~97+25