java生成验证码两种方法

来源:互联网 发布:网络作家收入怎么收税 编辑:程序博客网 时间:2024/05/22 03:36
/**
* 获取6位的随机数

* @return
*/
public static String getRandom6() {
StringBuffer str = new StringBuffer();
int[] intRet = new int[6];
int intRd = 0; // 存放随机数
int count = 0; // 记录生成的随机数个数
int flag = 0; // 是否已经生成过标志
while (count < 6) {
Random rdm = new Random(System.currentTimeMillis());
intRd = Math.abs(rdm.nextInt()) % 9 + 1;
for (int i = 0; i < count; i++) {
if (intRet[i] == intRd) {
flag = 1;
break;
} else {
flag = 0;
}
}
if (flag == 0) {
intRet[count] = intRd;
str.append(intRd);
count++;
}
}
return str.toString();
}

/**
* 生成num位的数字和字母组合
* @return
*/
public static String getRandom(int num) {
StringBuffer str = new StringBuffer();
int count = 0; // 记录生成的随机数个数
String[] strs = { "0", "1", "2", "3", "4", "5", "6", "7", "8","9", 
 "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s","d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m",
 "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N","M" };

while (count < num) {
int a=(int)(Math.random()*62);
str.append(strs[a]);
count ++;
}
return str.toString();
}
原创粉丝点击