如何在Java中生成任意长度的任意随机数?比如,要生成一个宽度为3的数字,它应该在100到999之间。那么如何编码呢?
在下图中:
我想解决第二个问题。
这是我为第一个问题写的:
public int getRandomNumberReturntypediff(int min,int max) {
Random rand = new Random();
int n = rand.nextInt(1000) + 1;
Integer.toString(n);
System.out.println("get Random Number with return type STRING" + n);
return n;
}
假设我采用参数 length
并返回 String
。我该怎么做?
最佳答案
我们使用 String
创建数字并将其转换为 BigInteger
。我认为处理大数的最佳方法是使用 BigInteger
但如果您需要 String
只需返回它。
static List<Character> NUMBERS_WITHOUT_ZERO = List.of('1', '2', '3', '4', '5', '6', '7', '8', '9');
static List<Character> NUMBERS_WITH_ZERO = List.of('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
private static final SecureRandom random = new SecureRandom();
public static BigInteger randomNumber(int length) {
StringBuilder res = new StringBuilder(length);
res.append(NUMBERS_WITHOUT_ZERO.get(random.nextInt(NUMBERS_WITHOUT_ZERO.size())));
for (int i = 2; i <= length; i++)
res.append(NUMBERS_WITH_ZERO.get(random.nextInt(NUMBERS_WITH_ZERO.size())));
return new BigInteger(res.toString());
}
希望这就是你想要的。
关于java - 在 Java 中生成任意长度的任意随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53001757/