要求从0–9,a–z,A―Z中随机取四个数,生成验证码,比如每调用一次方法,返回类似 a8Z9 之类的值
方法一:
public class YanZhengMaTest {
public static String generateRandCode(int n) {
StringBuffer res = new StringBuffer();
String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random rnd = new Random();
for (int i = 0; i < n; i++) {
int index = rnd.nextInt(str.length());
char ch = str.charAt(index);
res.append(ch);
}
return res.toString();
}
public static void main(String[] args) {
System.out.println(generateRandCode(40));//强烈推荐这种想产生多少位的验证码都可以!!!
}
}
方法二:
public class Cccc {
public static void main(String[] args) {
test();
}
public static void test(){
Random rnd = new Random();
int a = rnd.nextInt(10);
int b = rnd.nextInt(26)+65;
int c = rnd.nextInt(26)+97;
int d = rnd.nextInt(10);
char b1 = (char) b;
char c1 = (char) c;
String des = c1+""+a+""+b1+""+d;
System.out.println(des);
}
}