Home >Java >Javagetting Started >Three ways to generate random numbers in java
There are three ways to generate random numbers:
1. Through the Math.random() method
2. Obtained through the System.currentTimeMillis() method Number of milliseconds
3. Through the Random class
The first method: the common method Math.random() method is to obtain the double type decimal between 0-1, and then pass the int type wall Brick example:
Use the Math.random method to directly generate a 16-digit decimal between 0 and 1, and then directly obtain it through m * 10/100 through strong conversion to int How many digits are desired.
(Recommended tutorial: java quick start)
Second type: System.currentTimeMillis() calculation method is actually a time function, which can also be used as a random number. Returns the current time in milliseconds as a long. Example:
Third method: Use the Random class to obtain two constructors. We only use the most commonly used method to demonstrate, because the Random class is powerful and we only operate randomly. Count this piece, example:
Create an object through Random to obtain the memory object, and get the corresponding random number during transformation. The method of this class has the same principle as the first one. What Math.random calls in the source code is the method in the Random class.
Related video tutorial sharing: java video tutorial
The above is the detailed content of Three ways to generate random numbers in java. For more information, please follow other related articles on the PHP Chinese website!