Home > Java > javaTutorial > How to randomly generate random integers in java

How to randomly generate random integers in java

下次还敢
Release: 2024-04-27 01:51:14
Original
502 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 the java.util.Random class, which provides the following methods:

<code class="java">int nextInt(int bound): 生成 [0, bound) 范围内的随机整数
int nextInt(): 生成 [-2^31, 2^31) 范围内的随机整数</code>
Copy after login

Example:

Generate a random integer between 0 and 99 :

<code class="java">Random random = new Random();
int randomNumber = random.nextInt(100);</code>
Copy after login

Generate a random integer between 10 and 100:

<code class="java">int randomNumber = random.nextInt(91) + 10; // 101 - 100 = 91</code>
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 the nextInt() method is an open interval.
  • For the same Random instance, calling the nextInt() method multiple times will produce a seemingly random but actually deterministic sequence. Therefore, it is recommended to use the SecureRandom class 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 Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template