随机生成6位数字(包括字母和数字)
可用于生成验证码
public static void main(String[] args) {
// 生成一个由大写字母和数字组成的6位随机字符串,并且字符串不重复
char[] letters = {'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'};
boolean[] flags = new boolean[letters.length];
char[] cha = new char[6];
for (int i = 0; i < cha.length; i++) {
int index;
do {
index = (int) (Math.random()*(letters.length));
}while (flags[index]);//判断生成的字符串是否重复
cha[i] = letters[index];
flags[index] = true;
}
System.out.println(cha);
}
效果图: