方法一:
public class RandomTest extends TestCase {
public void testRandom1() throws Exception {
String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char[] c = s.toCharArray();
Random random = new Random();
for( int i = 0; i < 8; i ++) {
System.out.println(c[random.nextInt(c.length)]);
}
}
}
方法二:
public void testRandom2() throws Exception {
Random random = new Random();
for( int i = 0; i < 8; i ++) {
int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写还是小写
System.out.println((char)(choice + random.nextInt(26)));
}
}
public String randomString(){
return randomString(50);
}
public String randomString(int length){
if(length<=0){
length = 10;
}else if(length >50){
length = 50;
}
StringBuilder s = new StringBuilder(50);
Random random = new Random();
for( int i = 0; i < length; i ++) {
int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写还是小写
s.append((char)(choice + random.nextInt(26)));
}
return s.toString();
}
转自:http://www.cnblogs.com/jdonson/archive/2009/12/05/1617562.html