Generate a random integer with a specified number of digits Java
This question already has an answer here:
private long generateRandomNumber(int n) {
long min = (long) Math.pow(10, n - 1);
return ThreadLocalRandom.current().nextLong(min, min * 10);
}
nextLong
produces random numbers between lower bound inclusive and upper bound exclusive so calling it with parameters (1_000, 10_000)
for example results in numbers 1000 to 9999. Old Random
did not get those nice new features unfortunately. But there is basically no reason to continue to use it anyways.
public static int randomInt(int digits) {
int minimum = (int) Math.pow(10, digits - 1); // minimum value with 2 digits is 10 (10^1)
int maximum = (int) Math.pow(10, digits) - 1; // maximum value with 2 digits is 99 (10^2 - 1)
Random random = new Random();
return minimum + random.nextInt((maximum - minimum) + 1);
}
You can simply disregard the numbers that are not in the required range. That way your modified pseudo random number generator guarantees that it generates a number in the given range uniformly at random:
public class RandomOfDigits {
public static void main(String[] args) {
int nd = Integer.parseInt(args[0]);
int loIn = (int) Math.pow(10, nd-1);
int hiEx = (int) Math.pow(10, nd);
Random r = new Random();
int x;
do {
x = r.nextInt(hiEx);
} while (x < loIn);
System.out.println(x);
}
}
链接地址: http://www.djcxy.com/p/17676.html
上一篇: 得到一个从100到999的随机数
下一篇: 用指定的位数Java生成一个随机整数