package com.qfx.util;
import java.util.Random;
public class CharacterUtils {
// 得到一个随机数,length是要产生的随机数的长度
public static String getRandomString(int length) {
String str = "abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ1234567890";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
// 从1-62的字符中随机取出一位
int number = random.nextInt(62);
sb.append(str.charAt(number));
}
return sb.toString();
}
// 得到一个随机数
public static String getRandomString2(int length) {
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(3);
long result = 0;
switch (number) {
case 0:
// 随机得到大写字母A-Z一个字符
result = Math.round(Math.random() * 25 + 65);
sb.append(String.valueOf((char) result));
break;
case 1:
// 随机得到小写字母a-z一个字符
result = Math.round(Math.random() * 25 + 97);
sb.append(String.valueOf((char) result));
break;
case 2:
// 随机得到0-9之间的一个数
sb.append(String.valueOf(new Random().nextInt(10)));
break;
}
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(getRandomString(10));
System.out.println(getRandomString2(10));
}
}