实例 随机生成验证码
需求:定义一个方法实现随机产生5位的验证码,每一位可能是数字、大写字母、小写字母
package hello.practise;
import java.util.Random;
import java.util.Scanner;
public class Demo4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入验证码位数:");
int num = sc.nextInt();
System.out.println(createCode(num));
}
//1、定义一个方法生成n位验证码:是否需要返回值类型声明? String 是否需要声明形参?int
public static String createCode(int n){
//3、定义一个字符串变量生成随机字符串
String code = "";
Random r = new Random();
//2、定义一个循环,循环n次,生成验证码
for (int i = 0; i < n; i++) {
//4、生成一个随机字符:大写字母、小写字母、数字 ( 0 1 2 )
int type = r.nextInt(3);
switch(type){
case 0:
//大写字母 65-65+25———0-25+65
char ch = (char) (r.nextInt(26)+65);
code += ch;
break;
case 1:
//小写字母 97-97+25———0-25+97
char ch1 = (char) (r.nextInt(26)+97);
code += ch1;
break;
case 2:
code += r.nextInt(10);
break;
}
}
return code;
}
}