The generation of random numbers is very commonly used in some codes, and it is also something we must master. There are three main ways to generate random numbers in java:
The first one: new Random()
The second type: Math.random()
The third type: currentTimeMillis()
The first type requires the help of java.util.Random Class to generate a random number generator is also the most commonly used one. There are two constructors, Random() and Random(long seed). The first one uses the current time as the default seed, and the second one uses the specified seed value. After generation, different types of numbers are generated with the help of different statements.
The seed is the first value used to generate a random number. The mechanism is to use a function to convert the value of this seed into a certain point in the random number space, and the generated random numbers are evenly distributed in space. The random numbers generated in the future are related to the previous random number. Take code as an example.
public static void main(String[] args) { Random r = new Random(1); for(int i=0 ; i<5 ; i++) { int ran1 = r.nextInt(100); System.out.println(ran1); } }
The five numbers generated by my compiler are all 85,88,47,13,54. If Random r = new Random() is used, the random numbers generated will be different. This is determined The result of the seed.
And The value returned by the second method is a double value of [0.0, 1.0). Since double numbers have high precision, they can be regarded as random numbers to a certain extent. By using (int) to perform type conversion, you can get an integer random number. The code is as follows.
public static void main(String[] args) { int max=100,min=1; int ran2 = (int) (Math.random()*(max-min)+min); System.out.println(ran2); }
As forThe third method is not commonly used, but it is also an idea. The method returns a long millisecond number from 0:00:00 on January 1, 1970 (this is related to the UNIX system) to the present. After taking the modulo, a random number within the required range can be obtained.
public static void main(String[] args) { int max=100,min=1; long randomNum = System.currentTimeMillis(); int ran3 = (int) (randomNum%(max-min)+min); System.out.println(ran3); }
The above is the detailed content of Three ways of generating random numbers in java. For more information, please follow other related articles on the PHP Chinese website!