• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Random Number generation

 
John Lincoln
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1141
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use the "java.lang.Math.abs()" method (maybe?).
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic