生成一個四位數的隨機驗證碼


 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

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com