问题描述:生成一个六位数的验证码(包含大写字母、小写字母、数字,并且不允许重复)?
参考代码如下:
import java.util.Arrays;
import java.util.Random;
public class VerifCode{
public static void main(String[] args) {
//1. 生成验证码能取到的所有合法字符的数组
String[] letters={"0","1","2","3","4","5","6","7","8","9",
"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",
"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"};
int len=letters.length;
//2.定义一个数组,用来标识letters数组中已经被使用过的字符,被使用过的字符不能够被再次使用
boolean[] flags=new boolean[len]; //注意:boolean类型的数组每一项的默认值为false
Random ran=new Random();
//3.定义一个数组,用来存放生成的验证码
String[] chs=new String[6];
for(int i=0;i<chs.length;i++){
int num=0;
//生成一个没有被使用过的字符
do{
num=ran.nextInt(len);
}while(flags[num]);
chs[i]=letters[num];
flags[num]=true;
}
System.out.println("生成的六位的验证码为:"+Arrays.toString(chs));
}
}