18

Possible Duplicate:
Java: generating random number in a range

I need a little help.

What code would I use to create a random number that is 5 digits long and starts with either 1 or 2?

In order to use as a company employees ID?

Nompumelelo
  • 929
  • 3
  • 17
  • 28
Binyomin
  • 367
  • 2
  • 7
  • 20

1 Answers1

36

Depending on how you approach the problem something like that:

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

Or something like that (you probably want the instantation of the Random object of of the method but I just put 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) shall always give 1 or 2. You then multiply it by 10000 to satisfy your requirement and then add a number between [0..9999].

Here's are some example output:

14499
12713
14192
13381
14501
24695
18802
25942
21558
26100
29350
23976
29045
16170
23200
23098
20465
23284
16035
18628
ArtKorchagin
  • 4,801
  • 13
  • 42
  • 58
TacticalCoder
  • 6,275
  • 3
  • 31
  • 39
  • 1
    Please do not use this method. In my experience this is not generating random numbers. Refer to this thread for reliable solutions https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java – vepzfe Feb 28 '19 at 13:28