7

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".

Craig
  • 167
  • 1
  • 3
  • 13

3 Answers3

15

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

Joe C
  • 15,324
  • 8
  • 38
  • 50
Naruto
  • 4,221
  • 1
  • 21
  • 32
  • If you use String.format,then everytime you will get 5 digit number,i.e. zero will be appended if the number is having fewer digits than five. – Naruto Nov 22 '15 at 13:22
  • I have tried your way of generating pins far better than the other ways. I need to add something which can test whether or not the pin is of 5 digits if it isn't it regenerates.Else it returns it. – Craig Nov 22 '15 at 13:22
  • @User In my case always number generated will be of 5 digits as "0" will be padded if it is less than 5 digit number. – Naruto Nov 22 '15 at 13:25
1

Integer.SIZE yields the number in bits of the int data type. This nothing has to do with the range span for a random value.

Using it as the argument of Random.nextInt doesn't make any sense (actually it generates a random value in range [0,32)).

Just generate a int value = random.nextInt(100000) so that you will obtain a value in [0,99999].

Now your definition of 5 digits pin is not precise, 40 could be interpreted as 00040 so it's still 5 digits if you pad it. You must take this thing into account, since forcing 5 "visible" digits implies generating a number in range [10000,99999] but this is just an awkward solution.

Jack
  • 131,802
  • 30
  • 241
  • 343
0

RandomUtils.randomNumeric(int count) or RandomUtils.randomNumeric(int inLength, int maxLength) from apache common lang3 can also be used for the same purpose.

Bridge
  • 29,818
  • 9
  • 60
  • 82
Rohit
  • 339
  • 1
  • 5
  • 16