• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Random Number generation

 
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1143
1
Eclipse IDE Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Use the "java.lang.Math.abs()" method (maybe?).
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
This one time, at bandcamp, I had relations with a tiny ad.
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic