|
How to generate a random number |
|
|
This Java tip illustrates a method of generating a random number. Developer may use this
random generation in their applications such as in a quiz application for picking random
questions from a set of questions in a databse.
Random rand = new Random();
// No. 1 Random integers
int randnum = rand.nextInt();
// More random integers may be generated by
// iteratively executing previous line...
// No. 2 Generating random integers from 0 to 10
int n = 10;
randnum = rand.nextInt(n+1);
// No. 3 Generating random bytes
byte[] bytes = new byte[5];
rand.nextBytes(bytes);
// No. 4 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);
|
Related Tips
|