package com.itheima.demo;
import java.util.Random;
public class Test3 {
public static void main(String[] args) {
// 需求:生成一个由大写字母 小写字母 数字组成的一个五位数的随机验证码
String code = creatcode(5);
System.out.println("随机验证码是" + code);
}
//1.定义一个方法返回一个随机码,返回值类型String
public static String creatcode(int n) {
String code = "";
Random r = new Random();
//2.定义一个For循环 循环n次,一依次生成随机字符
for (int i = 0; i < n; i++) {
//i= 0 1 2 3 4
//3.生成一个随机字符:大写字符 小写字符 数字字符
int type = r.nextInt(3);//0 1 2
switch (type) {
case 0:
//大写字符(A 65 - Z 65+25 )
char ch = (char) (r.nextInt(26) + 65);
code += ch;
break;
case 1:
//小写字符(a 97 - z 97+25)
char ch1 = (char) (r.nextInt(26) + 97);
code += ch1;
break;
case 2:
//数字字符
code += r.nextInt(10);
break;
}
}
return code;
}
}
09-04
266
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-14
09-08
1859
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-18