我试图找到一种方法来生成一个非常大的随机数。我在网上看了但是找不到我要找的东西。我需要生成一个介于1111111111111111111111和9999999999999999999999之间的随机数;这个数字是22位数。 如果你知道怎么做,请告诉我。 感谢
答案 0 :(得分:2)
以下是满足您需求的快速测试解决方案:
public void generateNumber(){
BigInteger min = new BigInteger("1111111111111111111111");
BigInteger max = new BigInteger("9999999999999999999999");
System.out.println(random(min, max));
}
protected static Random RANDOM = new Random();
public static BigInteger random(BigInteger min, BigInteger max) {
if(max.compareTo(min) < 0) {
BigInteger tmp = min;
min = max;
max = tmp;
} else if (max.compareTo(min) == 0) {
return min;
}
max = max.add(BigInteger.ONE);
BigInteger range = max.subtract(min);
int length = range.bitLength();
BigInteger result = new BigInteger(length, RANDOM);
while(result.compareTo(range) >= 0) {
result = new BigInteger(length, RANDOM);
}
result = result.add(min);
return result;
}
答案 1 :(得分:0)
我之前有过一些我曾经使用过的东西
public class RandomString {
private static final Random random = new Random();
public static String numeric(int count) {
if (count == 0) {
return "";
} else if (count < 0) {
throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
}
int end = 'z' + 1;
int start = ' ';
char[] buffer = new char[count];
int gap = end - start;
while (count-- != 0) {
char ch;
ch = (char) (random.nextInt(gap) + start);
if (Character.isDigit(ch)) {
if (ch >= 56320 && ch <= 57343) {
if (count == 0) {
count++;
} else {
// low surrogate, insert high surrogate after putting it in
buffer[count] = ch;
count--;
buffer[count] = (char) (55296 + random.nextInt(128));
}
} else if (ch >= 55296 && ch <= 56191) {
if (count == 0) {
count++;
} else {
// high surrogate, insert low surrogate before putting it in
buffer[count] = (char) (56320 + random.nextInt(128));
count--;
buffer[count] = ch;
}
} else if (ch >= 56192 && ch <= 56319) {
// private high surrogate, no effing clue, so skip it
count++;
} else {
buffer[count] = ch;
}
} else {
count++;
}
}
return new String(buffer);
}
}
你可以像这样打电话给这个班级
RandomString.numeric(22);
它会做你想做的事情