This chapter first explains several ways to generate Java random numbers, and then demonstrates them through examples.
Broadly speaking, there are three ways to generate random numbers in Java:
(01). Use System.currentTimeMillis() to get a long-type number of milliseconds of the current time.
(02). Return a double value between 0 and 1 via Math.random().
(03). Generate a random number through the Random class. This is a professional Random tool class with powerful functions. The first method uses System.currentTimeMillis() to obtain random numbers
Get the random number through System.currentTimeMillis(). It is actually getting the current milliseconds number, which is of type long. How to use it is as follows:
final long l = System.currentTimeMillis();
To get an integer of type int, just convert the above result to type int. For example, get an int integer between [0, 100). The method is as follows:
final long l = System.currentTimeMillis();final int i = (int)( l % 100 );
The second method uses Math.random() to obtain random numbers
Get random numbers through Math.random(). In fact, it returns a double value between 0 (inclusive) and 1 (not included). How to use it is as follows:
final double d = Math.random();
To get an integer of type int, just convert the above result to type int. For example, get an int integer between [0, 100). The method is as follows:
final double d = Math.random();final int i = (int)(d*100);
The third type uses Random class to get random numbers
Get random numbers through the Random class.
How to use it is as follows:
(01) Create a Random object. There are two ways to create a Random object, as follows:
Random random = new Random();//Default constructor Random random = new Random(1000);//Specify seed number
(02) Get random numbers through Random objects. Random supports random value types: boolean, byte, int, long, float, double.
For example, get an int integer between [0, 100). The method is as follows:
int i2 = random.nextInt(100);
Random's Function Interface
// Constructor (I): Create a new random number generator. Random() // Constructor (II): Create a new random number generator using a single long seed: public Random(long seed) { setSeed(seed); } next method uses it to save the state of the random number generator. Random(long seed) boolean nextBoolean() // Returns the next "boolean type" pseudo-random number. void nextBytes(byte[] buf) // Generate random bytes and place them in byte array buf. double nextDouble() // Returns a random number of "double type between [0.0, 1.0)". float nextFloat() // Returns a random number of "float type between [0.0, 1.0)". int nextInt() // Returns the next "int type" random number. int nextInt(int n) // Returns a random number of "int type between [0, n)". long nextLong() // Returns the next "long type" random number. synchronized double nextGaussian() // Returns the next "double type" random number, which is a double value in a Gaussian ("normally") distribution, with an average value of 0.0 and a standard deviation of 1.0. synchronized void setSeed(long seed) // Set the seed of this random number generator using a single long seed.Get random number example
eg1:
The following is an example to demonstrate the above three ways to get random numbers. The source code is as follows (RandomTest.java):
import java.util.Random;import java.lang.Math;/** * java random number testing program. There are 3 ways to get random numbers: * (01), use System.currentTimeMillis() to obtain a long-type number of milliseconds in the current time. * (02), Return a double value between 0 and 1 through Math.random(). * (03) Generate a random number through the Random class. This is a professional Random tool class with powerful functions. * * @author skywang * @email [email protected] */public class RandomTest{ public static void main(String args[]){ // Return the random number testSystemTimeMillis() through System's currentTimeMillis(); // Return the random number testMathRandom() through Math's random(); // Create a new Random object with "seed of 1000" and test Random API through this seed testRandomAPIs(new Random(1000), " 1st Random(1000)"); testRandomAPIs(new Random(1000), " 2nd Random(1000)"); // Create a "default seed" Random object and test Random's API through this seed testRandomAPIs(new Random(), " 1st Random()"); testRandomAPIs(new Random(), " 2nd Random()"); } /** * Return a random number -01: Test System's currentTimeMillis() */ private static void testSystemTimeMillis() { // Final long l = System.currentTimeMillis(); // Get a [0, Integer final int i = (int)( l % 100 ); System.out.printf("/n---- System.currentTimeMillis() ---/nl=%si=%s/n", l, i); } /** * Return a random number-02: Test Math's random() */ private static void testMathRandom() { // Return a double-type random number through Math's random() function, range [0.0, 1.0) final double d = Math.random(); // Get an integer between [0, 100) final int i = (int)(d*100); System.out.printf("/n----- Math.random() ---/nd=%si=%s/n", d, i); } /** * Return random number-03: Test Random's API */ private static void testRandomAPIs(Random random, String title) { final int BUFFER_LEN = 5; // Get random boolean value boolean b = random.nextBoolean(); // Get random array buf[] byte[] buf = new byte[BUFFER_LEN]; random.nextBytes(buf); // Get a random Double value, range [0.0, 1.0) double d = random.nextDouble(); // Get a random float value, range [0.0, 1.0) float f = random.nextFloat(); // Get a random int value int i1 = random.nextInt(); // Get a random int value between [0,100) int i2 = random.nextInt(100); // Get a random Gaussian distribution double g = random.nextGaussian(); // Get a random long value long l = random.nextLong(); System.out.printf("/n--- %s ----/nb=%s, d=%s, f=%s, i1=%s, i2=%s, g=%s, l=%s, buf=[", title, b, d, f, i1, i2, g, l); for (byte bt:buf) System.out.printf("%s, ", bt); System.out.println("]"); }}
eg2:
Problem: Generate random numbers between (-10,10) with two digits retained after the decimal point.
Solution:
1. Random number generation function Random r=new Random(); r.nextFloat();// Generate floating point random numbers between (0,1). Multiply the above random number by 10 to obtain a random number between (0,10).
2. Generate a Boolean-type random number to control the positive and negative of the number: r.nextBoolean();
3. The method to retain two decimal places: Math.floor(n*100+0.5)/100; the obtained number is double type.
The code is as follows:
import java.util.*; public class CreateRandom { public float numRandom(){ float num; Random r=new Random(); float value = (float) (Math.floor(r.nextFloat()*1000+0.5)/100); Boolean b = r.nextBoolean(); if(b){ num = value; } else{ num=0-value; } return num; } public static void main(String[] args) { CreateRandom cr = new CreateRandom(); float num = cr.numRandom(); System.out.print(num); } }