生成随机数的方法
Java中生成随机数的方法常用的有Math.random()
和random.nextInt()
.
Math.random()
是一个静态方法,方法生成[0, 1)范围内的double类型随机数,而且,这个方法是线程安全的。如果想用Math.random()
生成随机整数,可以使用(int)(Math.random()*n)
的方法生成 [0, n) 的整数。
Random类的public int nextInt(int bound)
方法返回伪随机的均匀分布的 [0, bound) 之间的整数。下面是Java对这个方法的定义,从定义中可以发现,bound只能是正数。
public int nextInt(int bound) {
if (bound <= 0)
throw new IllegalArgumentException(BadBound);
int r = next(31);
int m = bound - 1;
if ((bound & m) == 0) // i.e., bound is a power of 2
r = (int)((bound * (long)r) >> 31);
else {
for (int u = r;
u - (r = u % bound) + m < 0;
u = next(31))
;
}
return r;
}
Random类中的nextInt()
方法生成的随机数有正有负,且绝对值很大。
生成随机字符串示例
下面的两个方法分别演示如何生成n位随机数和n位数字和字母的随机组合。
/**
* 生成n位随机数字
* @param n 随机数的数字位数
* @return n位数字组成的随机数字字符串
*/
public static String getRandomNumStr(int n) {
Random random = new Random();
StringBuilder randomStr = new StringBuilder();
for (int i = 0; i < n; i++) {
randomStr.append(random.nextInt(10));
}
return randomStr.toString();
}
/**
* 生成n位随机数字和字母
* @param n 随机字符的位数
* @return n位数字和字母组成的随机字符串
*/
public static String getRandomCharStr(int n) {
String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random random = new Random();
StringBuilder randomStr = new StringBuilder();
for (int i = 0; i < n; i++) {
randomStr.append(codes.charAt(random.nextInt(62)));
}
return randomStr.toString();
}
使用上面生成数字和字母的方法生成的随机字符串中,数字少,字母多,一种最简单的处理方法就是在codes字符串中增加数字的数量。
如果对数字或者字母的个数有要求,甚至如果有特殊字符的要求,就应该分别生成。