java自定义随机数(实例)

时间:2023-03-08 16:21:47
import java.util.Random;

/**
*
* @author mengzw
* @since 3.0 2014-5-22
*/
public class RandomTest { /**
* 生成随机字符串
*
* @param length
* 要生成字符串的长度
* @param stringType
* 字符源的类型。0:字母+数字(已把数字中的易混淆字符去除), 1:纯字母, 2:纯数字。默认为字母+数字
* @param caseType
* 大小写的类型。0:大小写混合, 1:纯大字, 2:纯小写。默认为纯大写
* @param specialString
* 特殊字符 如果需要生成的字符串中包含特殊字符,可把需要添加的特殊字符传进来。该参数为null或""都没关系
* @return
*/
public static String getRandomString(int length, int stringType, int caseType, String specialString) {
String type0 = "abcdefghijkmnopqrstuvwxyz23456789";
String type1 = "abcdefghijkmnopqrstuvwxyz";
String type2 = "0123456789";
String characterStore = "";
switch (stringType) {
case 0:
characterStore = type0;
break;
case 1:
characterStore = type1;
break;
case 2:
characterStore = type2;
break;
default:
characterStore = type0;
break;
}
characterStore += specialString; Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(characterStore.length());
char c = characterStore.charAt(number);
switch (caseType) {
case 0:
c = random.nextBoolean() ? Character.toUpperCase(c) : Character.toLowerCase(c);
break;
case 1:
c = Character.toUpperCase(c);
break;
case 2:
c = Character.toLowerCase(c);
break;
default:
c = Character.toUpperCase(c);
break;
}
sb.append(c);
}
return sb.toString();
} public static void main(String[] args) {
System.out.println(getRandomString(5,0,0,""));
}
}

制定自己需要的随机数