获取指定长度的字符串(数字或字母)
/**
* 获取含义大小写字母和数字指定长度的字符串
* @param length
* @return
*/
public static String getCharAndNumr(int length)
{
String val = "";
Random random = new Random();
for(int i = 0; i < length; i++)
{
String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字
if("char".equalsIgnoreCase(charOrNum)) // 字符串
{
int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; //取得大写字母还是小写字母
val += (char) (choice + random.nextInt(26));//此处26表示26个字母
}
else if("num".equalsIgnoreCase(charOrNum)) // 数字
{
val += String.valueOf(random.nextInt(10));
}
}
return val;
}
/**
* 获取只有数字指定长度的字符串
* @param length
* @return
*/
public static String getNum(int length){
Random random = new Random();
String str="";
for (int j = 0; j < length; j++) {
int i = random.nextInt(10);
str+=i;
}
return str;
}
/**
* 获取含大小写字母指定长度的字符串
* @param length
* @return
*/
public static String getChar(int length){
Random random = new Random();
String str = "";
for (int i = 0; i < length; i++) {
int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; //取得大写字母还是小写字母
str += (char) (choice + random.nextInt(26));
}
return str;
}
输出:
PQO7f2175
24573
LLqCx