GeeCON Prague 2014*
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


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: 10426
    
    8

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: 39084
    
  23
. . . or myRandom.nextInt(900) + 100
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10426
    
    8

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: 39084
    
  23
You're welcome
 
GeeCON Prague 2014
 
subject: How can I fix the size of randomly generated numbers ?