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

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

王林
Release: 2023-05-02 19:28:05
forward
5431 people have browsed it

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);
Copy after login

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

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

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);
Copy after login

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!

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