How to create a random five digit Java number

Possible duplicate:
Java: generating a random number in a range

I need a little help.

What code would I use to create a random number 5 digits long and starting with 1 or 2?

for use as an identifier for company employees.

Thanks!!

+7
source share
1 answer

Depending on how you approach the problem, something like this:

public int gen() { Random r = new Random( System.currentTimeMillis() ); return 10000 + r.nextInt(20000); } 

Or something like that (you probably want to instantiate the Random object for the method, but I just just have it here for simplicity):

 public int gen() { Random r = new Random( System.currentTimeMillis() ); return ((1 + r.nextInt(2)) * 10000 + r.nextInt(10000)); } 

The idea is that 1 + nextInt (2) always gives 1 or 2. Then you multiply it by 10000 to satisfy your requirement, and then add the number between [0..9999].

Here is an example output:

 14499 12713 14192 13381 14501 24695 18802 25942 21558 26100 29350 23976 29045 16170 23200 23098 20465 23284 16035 18628 
+29
source

All Articles