Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate 6 digit random number [duplicate]

Tags:

java

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.

like image 631
Kraken Avatar asked Jul 13 '18 10:07

Kraken


People also ask

What is the probability that a randomly selected 6 digit number has 6 unique digits?

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.

How many 6 digit numbers can be formed with repetition?

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.


2 Answers

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);
}
like image 101
Dev Sabby Avatar answered Sep 29 '22 04:09

Dev Sabby


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)
like image 40
Karol Dowbecki Avatar answered Sep 29 '22 06:09

Karol Dowbecki