需求
定义方法实现随机产生一个5位的验证码,每位可能是数字,大写字母,小写字母。
分析
1.定义一个方法,生成验证码返回:方法参数是位数,方法的返回值类型是String;
2.在方法内部使用for循环生成指定位数的随机字符,并连接起来;
3.把连接好的随机字符作为一组验证码进行返回。
正文:
导入生成随机数的包
import javax.lang.model.element.NestingKind;import java.util.Random;
定义一个方法返回一个随机验证码:(需要申明返回值类型:String ,需要申明参数:int n)
public static String createRandomCode (int n) {}
1.定义一个字符串变量记录生成的随机字符,创建一个随机数对象
String code = "";Random r = new Random();
2.定义一个for循环,循环n次,依次生成随机字符
for (int i = 0; i < n; i++) {}
3.在循环内部,每次循环生成一个随机字符:英文大写 小写 数字 (0, 1, 2)
int type = r.nextInt(3); //0, 1, 2switch (type) {case 0://大写字符 (A 65 - Z 65 + 25) (0 - 25) + 65char ch1 = (char) (r.nextInt(26) + 65);code += ch1;break;case 1://小写字符 (a 97 - Z 97 + 25) (0 - 25) + 97char ch2 = (char) (r.nextInt(26) + 97);code += ch2;break;case 2://大写字符 (A 65 - Z 65 + 25) (0 - 25) + 65int ch3 = r.nextInt(10);code += ch3;break;
4.循环结束后,返回String类型的变量即是所求的验证码结果。
return code;
定义一个主方法(main)接口,调用生成验证码的方法,输出结果。
public static void main(String[] args) {//调用获取验证码的方法得到一个随机的验证码String code = createRandomCode(5);System.out.println("随机验证码:" + code);}
完整代码:
/*需求:定义方法实现随机产生一个5位的验证码,每位可能是数字,大写字母,小写字母*/import javax.lang.model.element.NestingKind;import java.util.Random;public class Demo3 {public static void main(String[] args) {//调用获取验证码的方法得到一个随机的验证码String code = createRandomCode(5);System.out.println("随机验证码:" + code);}/*1.定义一个方法返回一个随机验证码:是否需要申明返回值类型:String 是否需要申明参数:int n*/public static String createRandomCode (int n) {//3.定义一个字符串变量记录生成的随机字符String code = "";Random r = new Random();//2.定义一个for循环,循环n次,依次生成随机字符for (int i = 0; i < n; i++) {//3.生成一个随机字符:英文大写 小写 数字 (0, 1, 2)int type = r.nextInt(3); //0, 1, 2switch (type) {case 0://大写字符 (A 65 - Z 65 + 25) (0 - 25) + 65char ch1 = (char) (r.nextInt(26) + 65);code += ch1;break;case 1://小写字符 (a 97 - Z 97 + 25) (0 - 25) + 97char ch2 = (char) (r.nextInt(26) + 97);code += ch2;break;case 2://大写字符 (A 65 - Z 65 + 25) (0 - 25) + 65int ch3 = r.nextInt(10);code += ch3;break;}}return code;}}
运行结果展示:
总结:
1.定义一个String类型的变量存储验证码字符;
2.定义一个for循环,循环n次;
3.随机生成0,1,2的数据,依次代表当前位置要生成数字,大写字母,小写字母;
4.把0,1,2交给switch生成对应类型的随机字符,把字符交给String变量;
5.循环结束后,返回String类型的变量即是所求的验证码结果。