Link to home
Start Free TrialLog in
Avatar of Sandy209
Sandy209

asked on

Generating a random 3 digit number - Java 1.4

Hi all,

What is the cleanest way to generate a random 3 digit number in Java 1.4 ?

java.util.Random can generate 0 - 999 but doesn't seem to have anything in it's api to support generating only 3 digits.

Any suggestions?
Avatar of boing40001
boing40001
Flag of Italy image

that means that you're looking for a number between 100 and 999
just add a check on the generated number by java.util.Random  and, if lower than 100, generate a new number
Avatar of Sandy209
Sandy209

ASKER

Hi boing40001,

Not necessarily, it would be a more complete solution if say 001 was an option.  Although for lack of a better solution it would acceptable as a last resort.
001 is the same as 1 numerically.  Its only different if you want to print it/ use it as a string.
in that case stick with random
and use
String.format("%03d", randomNumber);
to make sure that it always has 3 digits
if you want codes also like 001 then why don't you generate 3 numbers in interval 0..9 and then join the three numbers ?
@robthewolf - String.format is Java 1.5

@boing40001 - I considered that solution myself, i was just hoping for something a little less hacked :-)
you can use sprintf in exactly the same way in terms of formatting output.  That must be available in 1.4
what do i need to import to use sprinf(... ) ?
i really dont know if these are in 1.4 or not but try either
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html
or
System.out.printf();
ASKER CERTIFIED SOLUTION
Avatar of Pramod Kumar
Pramod Kumar
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I think this is a clean as we can expect in Java 1.4