Browse Today's favorites or All time favorites.
Please Sign In or Register to share and submit your questions.
Java Queries
Complete java interview questions library
Home » Java Tutorials » Core Java Tutorials » How do I generate a random number between 0 and some integer n
How do I generate a random number between 0 and some integer n
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);
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);
Your clothes are your image, check the mirror and see what others see
It is better to be overdressed than underdressed
Write a comment