Tuesday, 24 May 2016

How to generate 4 digit random numbers in java from 0000 to 9999





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.


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...