This example shows how to generate a random number in Java.
Random class from java util package provides several methods to generate random numbers of type integer, double, long, float, byte etc.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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); |