Home > Java > javaTutorial > How to generate different random numbers in java

How to generate different random numbers in java

王林
Release: 2023-04-28 15:49:06
forward
1459 people have browsed it

1.java.lang.Math

In the Math class, the random method returns a double value in the range [0.0,1.0). The following code can get a random number between min and max:

int randomWithMathRandom = (int) ((Math.random() * (max - min)) + min);
Copy after login

2, java.util.Random

Before Java1.7, the most popular random number The generation method is nextInt. This method provides two versions: with parameters and without parameters. When called without parameters, nextInt can return any int value with similar probability, so negative numbers can be obtained:

Random random = new Random();
int randomWithNextInt = random.nextInt();
Copy after login

3. Java 8 introduces a new ints method that returns java.util. stream.IntStream, let's see how to use it.

The ints method without parameters will return an int stream:

IntStream unlimitedIntStream = random.ints();
Copy after login

The above is the detailed content of How to generate different random numbers in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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