1. The static (static) method random () in the Math library ()
This method is used to generate a double value between 0 and 1 (including 0, but not 1.
The code is as follows: |
Copy code |
Double rand = Math. random (); |
2. Through the Random class object
The program can generate many different types of random numbers. The procedure is simple. You only need to call the nextInt () and nextFloat () methods (or call nextLong () or nextDouble ()). The parameter passed to nextInt () sets the upper limit of the generated random number, and the lower limit is 0.
If no parameters are passed during the creation of the Random object, Java uses the current time as the seed of the Random number generator, and thus produces different output during each execution of the program. If a seed is provided when a Random object is created (for the initialization value of the Random number generator, the Random number generator always generates the same Random number sequence for a specific seed value ), the same random number can be generated every time the program is executed, so the output is verifiable.
Example: generate a random number between 1 and 100
The code is as follows: |
Copy code |
Import java. util. Random; Public class Radom { Public static void main (String [] strs ){ Random rand = new Random (); System. out. println (rand. nextInt (99) + 1 ); } } |
Set the seed. In the following example, set the seed as needed:
The code is as follows: |
Copy code |
Random rand = new Random (47 ); |