22

how to generate a long that is in the range of [0000,9999] (inclusive) by using the random class in java? The long has to be 4 digits.

Louise Lin
  • 225
  • 1
  • 2
  • 8

2 Answers2

52

If you want to generate a number from range [0, 9999], you would use random.nextInt(10000).

Adding leading zeros is just formatting:

String id = String.format("%04d", random.nextInt(10000));
Grogi
  • 2,099
  • 17
  • 13
11

A Java int will never have leading 0(s). You'll need a String for that. You could use String.format(String, Object...) or (PrintStream.printf(String, Object...)) like

Random rand = new Random();
System.out.printf("%04d%n", rand.nextInt(10000));

The format String %04d is for 0 filled 4 digits. And Random.nextInt(int) will be [0,10000) or [0,9999].

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249