0

I tried the following

int number = ThreadLocalRandom.current().nextInt(1000, 9999 + 1);

But it won't generate 4 digit numbers like 0004,0035 and so on...

I searched for similar questions but none solved, they were different from what I need, if there's already an existing question please let me know.

I need no genarate numbers like 1485 and 0180, not only numbers starting with 0.

Goun2
  • 417
  • 1
  • 11
  • 22

2 Answers2

2

This should work:

    Random r = new Random();
    String randomNumber = String.format("%04d", r.nextInt(1001));
    System.out.println(randomNumber);

EDIT1

    Random r = new Random();
    String randomNumber = String.format("%04d", Integer.valueOf(r.nextInt(1001)));
    System.out.println(randomNumber);

EDIT2

    Random r = new Random();
    String randomNumber = String.format("%04d", (Object) Integer.valueOf(r.nextInt(1001)));
    System.out.println(randomNumber);

All three versions should work.

tuxdna
  • 8,257
  • 4
  • 43
  • 61
1

The integer values you generate will be correct for what you need. If you want to always have four characters, you can simply write the value to a String with leading zeros, like so;

String.format("%04d", number);
Badgerman
  • 11
  • 1
  • 2