Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a Random Pin of 5 Digits

Tags:

java

I would like to generate Unique Pins based on a random number I have found this on Stack Overflow How to generate a random five digit number Java. That Question uses time to generate the numbers so therefore you get a lot of duplicates.

Here is my code

public int createRandomPin() {
    int k = random.nextInt(Integer.SIZE);
    k = (k + 1) * 9999;
    if (9999 > k || k > 99999) {
        //then regenerate 
    } else {
        return k;
    }
}

My Question

Java Compiler then gives a warning missing "return". As well I need to restructure the code so that if it isn't a 5 digit pin it generates again before it "returns k".

like image 629
Craig Avatar asked Nov 21 '15 18:11

Craig


1 Answers

I would suggest to generate random number using SecureRandom class and then as it needs to be of 5 digits create a random number between 0 and 99999 using random.nextInt(100000) , here 0 is inclusive and 100000 is exclusive and then format it into 5 digit by appending zero.

SecureRandom random = new SecureRandom();
int num = random.nextInt(100000);
String formatted = String.format("%05d", num); 
System.out.println(formatted);

I hope this solves your problem

Edit: This post incorrectly said 10,000, has been edited to say 100,000

like image 91
Naruto Avatar answered Nov 14 '22 21:11

Naruto