编写一个验证码(可以通过键盘输入需要获取验证码的位数):
public class IdentifyingCode { public static void main(String[] args) { //验证码的编写 IdentifyingCode identifyingCode = new IdentifyingCode(); //扫描键盘输入 Scanner scanner = new Scanner(System.in); //通过键盘输入需要的验证码位数 System.out.print("请输入需要的验证码位数:"); int num = scanner.nextInt(); //打印 String s = identifyingCode.codeS(num); System.out.println("验证码是:" + s); } public String codeS(int n){ //1.定义一个空字符串用来接收验证码 String code = ""; //2.使用随机数 Random random = new Random(); //3.循环几次代表编写几位的验证码 for (int i = 0; i < n; i++) { //4.验证码的类型为数字,小写字母,大写字母三种情况因此随机出三种情况中的一种 int type = random.nextInt(3); switch (type){ //随机出数字 case 0: int num = random.nextInt(10); code += num; break; //随机出小写字母:97 - 97+25 case 1: char xiaoxie = (char) (random.nextInt(26)+ 97); code += xiaoxie; break; //随机出大写字母:65 - 65+25 case 2: char daoxie = (char) (random.nextInt(26)+ 65); code += daoxie; break; } } return code; } }
结果: