In my application, i want to generate 9 digit random numbers such that they r unique. Only one 9 digit random number should be generated each time i run the application and it should be unique. Later i want to save this number along with its associated data in a .txt file so that i can retrive the data associated with this unique number when required. How should i achieve this?
You could combine the Random Class & system time (or a function using system time) e.g. Random random = new Random(System. nanoTime()); int randomInt = random. nextInt(1000000000);
No, they're called pseudorandom because they're not truly random in the mathematical sense, only an approximation. A PRNG that generates distinct numbers each time it's run is still pseudorandom.
Do you want them to be truly random or truly unique? You can only have one of these.
If you want them to be truly random, then just randomly pick 9 digits from 0-9 and construct them into your number. There will be a small chance of a duplication, especially over larger numbers of iterations. It will be truly random, though.
If you want them to be truly unique, then you have to store every one in a database to ensure there are no duplicates. If you generate a duplicate, you'll need to regenerate or just increment the number and try again. If this is what you're looking for, it might be good to try just incrementing the value starting at one.
For unique number try: (new Date()).getTime()
it will never be the same unless you are generating multiple number in a sec.
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