泊而至远

导航

 

案例介绍:模拟登录时需要输入验证码功能;

案例设计:

①   证码由4个字符组成;

②   验证码只能由数字和大写字母组成;

③   每次输入的字符各不相同,不能重复;

 1 import java.util.Random;
 2 public class RandomGenDemo{
 3     public static void main(String []args){
 4         System.out.println("验证码如下:"+RandomGen.codeGen());
 5     }
 6 }
 7 
 8 class RandomGen{
 9     //生成4位不重复的验证码
10     public static String codeGen(){
11         char[] codeSequence={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'};
12         Random random=new Random();
13         StringBuilder sb=new StringBuilder();//动态字符串
14         int count=0;
15         while(true){
16             //随机产生一个下标,通过下标取出字符数组中对应的字符
17             char c= codeSequence[random.nextInt(codeSequence.length)];
18             //假设取出的字符在动态字符串中不存在,代表没有重复
19             if(sb.indexOf(c+"")==-1){
20                 sb.append(c);//追加到动态字符串中
21                 count++;
22                 if(count==4){
23                     break;
24                 }
25             }
26         }
27         return sb.toString();
28     }
29 }

 

posted on 2016-03-29 21:26  积_跬步  阅读(203)  评论(0编辑  收藏  举报