Java随机生成字母数字组合的验证码

import java.util.Random;

public class StringRandom {

//生成随机数字和字母,
public String getStringRandom(int length) {

String val = "";
Random random = new Random();

//参数length,表示生成几位随机数
for(int i = 0; i < length; i++) {

String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
//输出字母还是数字
if( "char".equalsIgnoreCase(charOrNum) ) {
//输出是大写字母还是小写字母
int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
val += (char)(random.nextInt(26) + temp);
} else if( "num".equalsIgnoreCase(charOrNum) ) {
val += String.valueOf(random.nextInt(10));
}
}
return val;
}

public static void main(String[] args) {
StringRandom test = new StringRandom();
//测试
System.out.println(test.getStringRandom(8));
}
}

posted @ 2016-11-02 14:41  黄小易  阅读(7187)  评论(0编辑  收藏  举报