How to generate any random number of any Length in Java? Like, to generate a number of width 3, it should be between 100 to 999. So how to code this?
In image below:
I want to solve second problem.
This is what I written for first problem:
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;
}
Suppose I take parameter length
and return String
. How can I do this?
We use String
for create number and the convert it to a BigInteger
. I think the the best way for handle large number is to use BigInteger
but if you need String
just return that.
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());
}
I hope this is what you want.
Since you already have the actual bounded random number generation logic in your question, I assume your struggling with the calculation of the bounds.
You can calculate the minimum and maximum values by using powers of 10:
So, for example, for a number length of 3, this will give you a minimum of 100, and a maximum of 999.
Here's a complete example:
import java.util.Random;
public class Randoms {
public static void main(String args[]) {
System.out.println(generateRandom(3));
}
private static String generateRandom(int length) {
int min = (int) Math.pow(10, length - 1);
int max = (int) Math.pow(10, length); // bound is exclusive
Random random = new Random();
return Integer.toString(random.nextInt(max - min) + min);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With