Java 生成任意长度的验证码的两个方法

|--需求说明

1、要求生成任意长度的验证码

2、验证码要求包含大小写英文字母和数字

|--实现方式

采用随机数的方式,分别在数字,大小写英文字母里面抽取字符,抽取次数由for循环控制

|--代码内容

 1 package com.work.work3;
 2 
 3 /**
 4  * @auther::9527
 5  * @Description: 验证码生成器
 6  * @program: shi_yong
 7  * @create: 2019-07-30 20:45
 8  */
 9 public class Method {
10     //采用char对照表生成验证码
11     public static String verCode1(int num) {
12         String code = "";  //设置一个变量,用来接收验证码
13         for (int i = 0; i < num; i++) {
14             //使用一个布尔变量,判定单个验证码是数字还是英文字母
15             boolean choose = ((int) (Math.random() * 2) == 0) ? true : false;
16             if (choose) {
17                 //如果choose为真,则选取数字做单个验证码并连接到code里面
18                 code += (int) (Math.random() * 10); //在0-9之间选择一个数字做验证码
19             } else {
20                 //如果choose为假,则选取英文字母做单个验证码并连接到code里面
21                 //用char对照表里面的序号,确认本次英文字母是采用大写还是小写,
22                 // 65是大写英文字母开头,97是小写英文字母开头
23                 int temp = ((int) (Math.random() * 2) == 0) ?65:97;
24                 char ch = (char)((Math.random()*26)+temp);
25                 code += ch;
26             }
27         }
28         //返回一个字符串
29         return code;
30     }
31 
32     public static String verCode2(int num){
33         String code="";
34         //采用变量string接收所有0-9,a-z,A-Z的字符
35         String string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
36         //将字符串拆分成字符串数组
37         String[] str= string.split("");
38         for (int i = 0; i <num ; i++) {
39             //在数组里面用下标随机出字符串
40             code += str[(int)(Math.random()*str.length)];
41         }
42         return code;
43     }
44 
45     public static void main(String[] args) {
46         System.out.println("对照表法:"+Method.verCode1(6));
47         System.out.println("split分割字符串法:"+Method.verCode2(6));
48 
49     }
50 }
随机的方法及程序入口

|--运行结果

扫描二维码关注公众号,回复: 6906085 查看本文章

猜你喜欢

转载自www.cnblogs.com/twuxian/p/11272810.html
今日推荐