aspose file tools*
The moose likes Java in General and the fly likes How can I fix the size of randomly generated numbers ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "How can I fix the size of randomly generated numbers ?" Watch "How can I fix the size of randomly generated numbers ?" New topic
Author

How can I fix the size of randomly generated numbers ?

Shounak Kundu
Ranch Hand

Joined: Jul 29, 2010
Posts: 60

Hi,
I am randomly generating numbers using java.util.Random . But, I can not keep the length of the numbers fixed. Can you help me please ?

Here's my code :




Shounak
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 9990
    
    7

By length of number, I take it you mean the number of digits in the number.

Suppose you want only 3 digit numbers. The lowest would be 100 and highest would be 999
In pseudo code
1) Generate nextInt(1000)
2) Check if num >99. If yes, accept it, else reject it
3) Repeat


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36478
    
  16
. . . or myRandom.nextInt(900) + 100
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 9990
    
    7

Campbell's solution is more elegant.
Now why didn't I think of it?
Shounak Kundu
Ranch Hand

Joined: Jul 29, 2010
Posts: 60

thank you guys...... it has been solved...
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36478
    
  16
You're welcome
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How can I fix the size of randomly generated numbers ?
 
Similar Threads
A number generation program....
Find duplicate number in text file
Random number
Math.random question
Creating a random math sign