File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Random Number generation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Random Number generation " Watch "Random Number generation " New topic
Author

Random Number generation

John Lincoln
Ranch Hand

Joined: Feb 11, 2003
Posts: 192
Hi ,

Is there any way forcing random number genrated to be positive.
This is what i am doing :
Random rand = new Random(System.currentTimeMillis());
nextID = rand.nextInt();
But some time i get
main: in initialValue()
Iteration :0My id is : 15064690
main: in initialValue()
Iteration :1My id is : -25718693
main: in initialValue()
Iteration :2My id is : 67005792
main: in initialValue()
Iteration :3My id is : 41612364
main: in initialValue()
Iteration :4My id is : 25068161
main: in initialValue()
Iteration :5My id is : -300814157
main: in initialValue()
Iteration :6My id is : -326207584
main: in initialValue()
Iteration :7My id is : -231944104
main: in initialValue()
Iteration :8My id is : -262339267
main: in initialValue()
Iteration :9My id is : -189621725
Is there a way to force the numbers to be positive?
please help.
Thanks in advance.
Praveen.
Avi Abrami
Ranch Hand

Joined: Oct 11, 2000
Posts: 1134

Use the "java.lang.Math.abs()" method (maybe?).
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Try the nextInt(int) method in Random. For example
rand.nextInt(100)
would return a value from 0 to 99 - or
rand.nextInt(100) + 1
would give a value from 1 to 100. You should be able to manipulate this to whatever range you like.


"I'm not back." - Bill Harding, Twister
 
GeeCON Prague 2014
 
subject: Random Number generation