package test200.checkCode; /* 需求: 定义方法实现随机产生一个5位的验证码,每位可能是数字、大写字母、小写字母。 分析: 定义一个方法,生成验证码返回:方法参数是位数、方法的返回值类型是String。 在方法内部使用for循环生成指定位数的随机字符,并连接起来。 把连接好的随机字符作为一组验证码进行返回。 */ import java.util.Random; public class check { public static void main(String[] args) { System.out.println("随机验证码为:" + CheckCode(4)); } //定义方法随机生成5位验证码返回 public static String CheckCode(int n) { Random r = new Random(); //设置变量接收生成验证码 String code = ""; //定义for循环 循环n次 依次生成随机字符 for (int i = 0; i <= n; i++) { int type = r.nextInt(3); //0 1 2 switch (type) { case 0: //大写字母(A 65 - Z 65+25)(0-25)+65 //char ch = (char)(r.nextInt(26)+65); char ch = (char) (r.nextInt(26) + 65); code += ch; break; case 1: //小写 97 - 122 char ch2 = (char) (r.nextInt(26) + 97); code += ch2; break; case 2: //数字 int ch3 = r.nextInt(10); //数字不需要强转char code += ch3; break; } } return code; } }
使用IDEA实现java生成随机验证码
最新推荐文章于 2024-04-07 20:10:34 发布