| 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: 8430
|
|
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
|
[Donate a pint, save a life!] [How to ask questions] [Onff-turn it on!]
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32599
|
|
|
. . . or myRandom.nextInt(900) + 100
|
 |
Maneesh Godbole
Saloon Keeper
Joined: Jul 26, 2007
Posts: 8430
|
|
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: 32599
|
|
You're welcome
|
 |
 |
|
|
subject: How can I fix the size of randomly generated numbers ?
|
|
|