java【随机验证码功能】

public class RandomGenDome{
    public static  void  main(String []args){
        System.out.printf("四位验证码如下:\n" + RandomGen.codeGen());
    }
}

class RandomGen{
    //生成四位不重复的验证码
    public String codeGen(){
        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','Y','Z'};
        Random random = new Random();
        StringBuilder sb = new StringBuilder();    //动态字符串
        int count++;
        while(true){
            //随机产生一个下标,通过下标取出字符数组中的对应字符
            char c = codeSequence[random.nextInt(codeSequence.length)];
            //假设取出的字符在动态字符串中不存在,代表没有重复的
            if(sb.indexOf(c + " ") ==-1){
                sb.append(c);    //追加到动态字符串中
                count++;
                if(count ==4){
                    break;
                }
            }
        }
         return sb.toString();
    }
}

 

你可能感兴趣的:(Java)