生成一个四位数的随机验证码

 1 /**
 2  * 生成随机验证码
 3  * @author Administrator
 4  *
 5  */
 6 public class RandomGendemo {
 7     public static void main(String[] args) {
 8         System.out.println("生成的随机验证码:"+RandomGen.codeGen());
 9     }
10 }
11 class RandomGen{
12     //生成四位不重复的验证码
13     public static String codeGen(){
14         char[] codeSequence ={'A','B','C','D','E','F','G','H','I','J','K',
15                 'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
16                 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s',
17                 't','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'};
18         Random random = new Random();
19         //动态字符串
20         StringBuilder sb = new StringBuilder();
21         int count = 0;
22         while(true){
23             //随机产生一个下标,通过下标取出字符数组中内容
24             char c = codeSequence[random.nextInt(codeSequence.length)];
25             //假设取出来的字符在动态字符串中不存在,代表没有重复的
26             if(sb.indexOf(c+" ") == -1){
27                 //追加到动态字符串中
28                 sb.append(c);
29                 count++;
30                 if(count == 4){
31                     break;
32                 }
33             }
34         }
35         return sb.toString();
36     }
37 }
View Code

 

posted @ 2017-09-16 11:05  高木子  阅读(2214)  评论(0编辑  收藏  举报