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

Three ways to generate random numbers in java

王林
Release: 2020-03-16 20:33:36
forward
3949 people have browsed it

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template