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


 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM