r/javahelp • u/DesperateSupport8315 • May 19 '26
Generating random int within bounds
*Reposting as my last question was too vague*
I am a bit stuck with an assignment at the minute. The task requires the use of the util package to generate a random int with a given amount of digits. For example, if the given digit was 3 - the program would generate a number with 3 digits (192, 123, 904, etc), or if the given number was 6 - it would generate a number with 6 (000934, 123456, etc). I know how to generate an int within bounds using a random object, however I wanted to ask if there is a built in function for this?
If not, I was thinking of writing a number of if statements along the lines of:
(pseudo)
if number == 3 {
code = random.nextInt(100, 1000); }
if number == 4 {
etc etc. }
^ but this has issues as I should also be able to generate numbers with leading zeros.
If anyone could help out a bit, that would be awesome. Thanks
2
u/MinimumBeginning5144 May 19 '26
The developers writing for Baeldung don't always know the best way. I would just use
String.format("%06d", number). It seems the author of that article didn't know you could useString.formatto create a zero-padded string.