1 public class Demo {
2
3 public static void main(String[] args) {
4 // 调用验证码方法获取验证码、输出
5 String code = authCode(5);
6 System.out.println(code);
7 }
8
9 /**
10 * 定义一个方法返回一个随机验证码:是否需要返值类型申明?String 是否需要申明形参:int n
11 */
12 public static String authCode(int n){
13
14 // 定义一个变量用于存储验证码
15 String code = "";
16
17 Random random = new Random();
18 // 定义一个循环,依次生成验证码
19 for (int i = 0; i < n; i++) {
20 // 生成一个随机字符:大写字母、小写字母、数字
21 int type = random.nextInt(3);
22 switch (type){
23 case 0:
24 // 大写字符 (A 65 -- Z 65+25) (0-25)+65
25 char ch = (char) (random.nextInt(26) + 65);
26 code += ch;
27 break;
28 case 1:
29 // 小写字符 (a 97 -- z 97+25) (0-25)+97
30 char ch1 = (char) (random.nextInt(26) + 97);
31 code += ch1;
32 break;
33 case 2:
34 // 数字字符
35 code += random.nextInt(10);
36 break;
37 }
38 }
39 return code;
40 }
41 }