代码一(包含字母):
public class Ran {
public final static String randomStr = "abcdefghijklmnopqrstuvwxyz0123456789";public static void main(String[] args) {
System.out.println(getRandomNum(4)); // 这个4 代表 生成四个 随机数。
}
/** 生成随机数
* @param pwd_len
* @return
*/
private static String getRandomNum(int pwd_len) {
final int maxNum = 36;
int i;
int count = 0;
char[] str = randomStr.toCharArray();
StringBuffer pwd = new StringBuffer("");
Random r = new Random();
while(count<pwd_len){
i = Math.abs(r.nextInt(maxNum));
if(i>0 && i<str.length){
pwd.append(str[i]);
count++;
}
}
return pwd.toString();
}
}
代码二:
public static void main(String [] args){
int max = 10000;
int min = 1000;
for(int i=0; i<10;i++){
int num = (int)((max-min)*Math.random()+min);
System.out.println(num);
}
}
代码三:
public static int getRandom(){
int max=1500;
int min=500;
Random random = new Random();
int s = random.nextInt(max)%(max-min+1) + min;
return s;
}
}
代码二和代码三的公式:(max - min) * Math.random() + min
代码四:
private String getCheckCode() {
String strInt = " ";
Integer i = new Integer((int) (Math.random() * 100000000));
strInt = String.valueOf(i);
if (strInt.length() != 8) {
return getCheckCode();
} else {
return strInt;
}
}
代码五(包含字母):
public class RandomString {
/**
* 每位允许的字符
*/
private static final String POSSIBLE_CHARS="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
/**
* 生产一个指定长度的随机字符串
* @param length 字符串长度
* @return
*/
private String generateRandomString(int length) {
StringBuilder sb = new StringBuilder(length);
SecureRandom random = new SecureRandom();
for (int i = 0; i < length; i++) {
sb.append(POSSIBLE_CHARS.charAt(random.nextInt(POSSIBLE_CHARS.length())));
}
return sb.toString();
}
/**
* @param args
*/
public static void main(String[] args) {
Set<String> check = new HashSet<String>();
RandomString obj = new RandomString();
//生成2000000个随机字符串,检查是否出现重复
for (int i = 0; i < 2000000; i++) {
String s = obj.generateRandomString(16);
if (check.contains(s)) {
throw new IllegalStateException("Repeated string found : " + s);
} else {
if (i % 1000 == 0) System.out.println("generated " + i / 1000 + "000 strings.");
check.add(s);
}
}
}
}