Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate a random long with 4 digits in java? [duplicate]

Tags:

java

random

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.

like image 778
Louise Lin Avatar asked Nov 07 '15 00:11

Louise Lin


People also ask

How do I get a 4 digit UUID?

int num = -1; ArrayList<Integer> arNumber = new ArrayList<Integer>(); for(int x = 0; x < 10; x++) { arNumber. add(x); } Collections. shuffle(arNumber); String strNum = ""; for(int i = 0; i < 4; i++) strNum = strNum + arNumber. get(new Random().

How do you generate a random long in Java?

In order to generate Random long type numbers in Java, we use the nextLong() method of the java. util. Random class. This returns the next random long value from the random generator sequence.

How do you generate a 3 digit random number in Java?

Random random = new Random(); int randomNumber = random. nextInt(900) + 100; Now randomNumber must be three digit.


1 Answers

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));
like image 84
Grogi Avatar answered Oct 08 '22 00:10

Grogi