• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to generate Random No in java

 
Ranch Hand
Posts: 413
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can any one pls let me know as how can we generate random no in java with in certain range
e.g. I want to generate random no between 1 and 3
Thankx in advance
:roll:
 
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You should check out the Math.random() method in the Java API.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
And/or the java.util.Random class. Math.random() is simpler; java.util.Random has more options.
 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Gaurav Chikara:
Can any one pls let me know as how can we generate random no in java with in certain range
e.g. I want to generate random no between 1 and 3
Thankx in advance
:roll:

 
jeroen riezebeek
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Random rnd = new Random();
int value = (int)(rnd.nextDouble()*3);
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That will generate 0, 1, or 2. To get 1-3 just add 1. While we're at it, might as well use a nextInt() rather than nextDouble():
Random rnd = new Random();
int value = rnd.nextInt(3) + 1;
Or the one-line version
int value = (int) (Math.random() * 3) + 1;
 
reply
    Bookmark Topic Watch Topic
  • New Topic