Home >Java >Javagetting Started >Three ways to generate random numbers in java

Three ways to generate random numbers in java

王林
王林forward
2020-03-16 20:33:363956browse

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:

Three ways to generate random numbers in java

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:

Three ways to generate random numbers in java

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:

Three ways to generate random numbers in java

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete