Saturday, August 15, 2009

Generating random number

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);

source:java-tips.org

No comments:

Computers Add to Technorati Favorites Programming Blogs - BlogCatalog Blog Directory