java left logo
java middle logo
java right logo
 

Home arrow Java SE Tips
 
 
Main Menu
Home
Java Tutorials
Book Reviews
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Java Network
Java Forums
Java Blog




Most Visited Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews
Top Rated Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews


Statistics
Registered Users: 4091
Java SE Tips: 614
Java ME Tips: 202
Java EE Tips: 183
Other API Tips: 779
Java Applications: 298
Java Libraries: 209
Java Games: 16
Book Reviews:
 
 
 
How do I generate a random number between 0 and some integer n E-mail
User Rating: / 123
PoorBest 

First you would need to create an instance of Random class:

   Random random = new Random();

Then, you can get your random number by calling:

   int pick = random.nextInt(maxvalue);

This would return a value from 0 (inclusive) to maxvalue (exclusive).

For a more cryptographically strong pseudo random generator you may check out java.security.SecureRandom class. Here the caller may specify the algorithm name and (optionally) the package provider. Here is a sample code of using SecureRandom class:

   SecureRandom random = SecureRandom.getInstance("SHA1PRNG")
   random.setSeed(seed)
   int randInt = random.nextInt(maxvalue);

 Related Tips

 
< Prev   Next >
 
       
         
     
 
 
 
   
 
 
java bottom left
java bottom middle
java bottom right
RSS 0.91 FeedRSS 1.0 FeedRSS 2.0 FeedATOM FeedOPML Feed

Home - About Us - Privacy Policy
Copyright 2005 - 2008 www.java-tips.org
Java is a trademark of Sun Microsystems, Inc.