I just want to generate 6 digit random number, and the range should be start from 000000 to 999999.
new Random().nextInt(999999)
is returning me number but it is not in 6 digit.
The probability of a 6 digits number with no repeats is basically the number of permutations of 6 digits with no repetitions among the set of all possible numbers, so the probability is given by P(E)=P(10,6)106=0.1512.
So, starting from the left, you would have 9 choices for the leftmost digit (not allowing 0), then 9 choices again for the next digit (0 is now allowable but not the previous digit), then 8 choices for the next digit and so on, for a result of 9*9*8*7*6*5 = 136080.
Its as simple as that, you can use your code and just do one thing extra here
String.format("%06d", number);
this will return your number in string format, so the "0" will be "000000".
Here is the code.
public static String getRandomNumberString() {
// It will generate 6 digit random Number.
// from 0 to 999999
Random rnd = new Random();
int number = rnd.nextInt(999999);
// this will convert any number sequence into 6 character.
return String.format("%06d", number);
}
If you need a six digit number it has to start at 100000
int i = new Random().nextInt(900000) + 100000;
Leading zeros do not have effect, 000000
is the same as 0
. You can further simplify it with ThreadLocalRandom
if you are on Java 7+:
int i = ThreadLocalRandom.current().nextInt(100000, 1000000)
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