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

How to randomly generate random integers in java

下次还敢
下次还敢Original
2024-04-27 01:51:14446browse

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>

Example:

Generate a random integer between 0 and 99 :

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

Generate a random integer between 10 and 100:

<code class="java">int randomNumber = random.nextInt(91) + 10; // 101 - 100 = 91</code>

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!

Statement:
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