Generating a Random Number

Random rand = new Random(); // Random integers int i = rand.nextInt(); // Continually call nextInt() for more random integers ... // Random integers that range from from 0 to n int n = 10; i = rand.nextInt(n+1); // Random bytes byte[] bytes = new byte[5]; rand.nextBytes(bytes); // Other primitive types boolean b = rand.nextBoolean(); long l = rand.nextLong(); float f = rand.nextFloat(); // 0.0 <= f < 1.0 double d = rand.nextDouble(); // 0.0 <= d < 1.0 // Create two random number generators with the same seed long seed = rand.nextLong(); rand = new Random(seed); Random rand2 = new Random(seed);

Comments

3 Feb 2010 - 9:25am by Gervase (not verified)

I loved your example. I use them about once a week.

This example would be even better if you added the following

//Create a dice throw

//Create a random String

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.