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
4
u/Spare-Plum May 19 '26
Ah ok this is better defined.
You have two options -
Generate a number from 0 to 10 X times and put them all together.
If they input 5, use a loop 5 times and do random.nextInt(10), appending each value to a string
Generate a single number from 0 to 10^X
If they input 5, then you would have a range from 0 to 10*10*10*10*10. You can use Math.exp to perform this calculation, or you can multiply it out in a loop to keep it as an integer
The downside of this is that the size of your generated number is bounded to 18 digits for longs
To fix this, either throw an error if the user input a size too big, or append them together using strings.