Home  >  Article  >  Java  >  How to generate a random integer within a specified range in java

How to generate a random integer within a specified range in java

王林
王林forward
2023-05-02 19:28:055360browse

1. Math.random() will generate a random return value of 0-1 [0, 1), that is, greater than or equal to 0.0 and less than 1.0.

For example: 0.5105802498623931.

Use this feature to derive the following random numbers in a specific range:

(1) Generate random integers from 0 to n, that is, return value [0, n]

int num=(int)(Math.random()*(n+1);

(2) Generate a random integer from a to b, that is, return value [a, b]

int num=a+(int)(Math.random()*(b-a+1));

2. Use nextInt(intorigin,intbound) of the java.util.concurent.ThreadLocalRandom class method.

The returned random number ranges from origin (inclusive) to bound (exclusive)

For example, to generate numbers from 10 (inclusive) to 99 (inclusive), the code is as follows :

int randomNum = ThreadLocalRandom.current().nextInt(10, 99 + 1);

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

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