Home> Java> javaTutorial> body text

How to randomly generate random integers in java

下次还敢
Release: 2024-04-27 01:51:14
Original
427 people have browsed it

To randomly generate integers in Java, you can use the java.util.Random class: nextInt(int bound): generate a random integer in the range of [0, bound) nextInt(): generate [-2^31, 2^ 31) Random integers within the range

How to randomly generate random integers in java

Randomly generate random integers in Java

Generating random integers in Java can Use thejava.util.Randomclass, which provides the following methods:

int nextInt(int bound): 生成 [0, bound) 范围内的随机整数 int nextInt(): 生成 [-2^31, 2^31) 范围内的随机整数
Copy after login

Example:

Generate a random integer between 0 and 99 :

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

Generate a random integer between 10 and 100:

int randomNumber = random.nextInt(91) + 10; // 101 - 100 = 91
Copy after login

Notes:

  • nextInt(int bound )The range of random numbers generated by the method is a closed interval, while the range of random numbers generated by thenextInt()method is an open interval.
  • For the sameRandominstance, calling thenextInt()method multiple times will produce a seemingly random but actually deterministic sequence. Therefore, it is recommended to use theSecureRandomclass when truly random numbers are required.

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

source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!