记录下自己写的一个获取随机整数的方法。如果有什么不好的地方或更好的方法,请指正。
public static String getNRandomNum(int digit) {
digit = checkDigit(digit);
if (digit == 1)
return get1RandomNum();
int maxDigit = 18;
double operand;
StringBuffer sb = new StringBuffer();
/*
* 如果超过最大位数.则每maxDigit(默认18)位计算一次随机数.
*/
if (digit > maxDigit) {
operand = Math.pow(10, maxDigit - 1);
for (int i=0; i<digit / maxDigit; i++) {
long num = (long) (Math.random() * 9 * operand + operand);
sb = sb.append(num);
}
operand = digit % maxDigit;
if (operand != 0)
sb = sb.append(getNRandomNum((int) operand));
}
else {
operand = Math.pow(10, digit - 1);
long num = (long) (Math.random() * 9 * operand + operand);
sb = sb.append(num);
}
return sb.toString();
}
public static String get1RandomNum() {
return String.valueOf((int)(Math.random() * 10));
}
private static int checkDigit(int digit) {
if (digit < 0)
digit = Math.abs(digit);
else if (digit == 0)
digit = 1;
return digit;
}
下面的方法是使用BigDecimal实现的
public static String getNRandomNum(int digit) {
digit = checkDigit(digit);
String num;
if (digit == 1)
num = get1RandomNum();
else {
BigDecimal operand = new BigDecimal(10).pow(digit - 1);
BigDecimal randomNum = new BigDecimal(Math.random());
MathContext mc = new MathContext(digit, RoundingMode.DOWN);
num = randomNum.multiply(new BigDecimal(9)).multiply(operand).add(operand, mc).toString();
}
return num;
}