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.
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().
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.
Random random = new Random(); int randomNumber = random. nextInt(900) + 100; Now randomNumber must be three digit.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With