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);
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();
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();
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!