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
Randomly generate random integers in Java
Generating random integers in Java can Use thejava.util.Random
class, which provides the following methods:
int nextInt(int bound): 生成 [0, bound) 范围内的随机整数 int nextInt(): 生成 [-2^31, 2^31) 范围内的随机整数
Example:
Generate a random integer between 0 and 99 :
Random random = new Random(); int randomNumber = random.nextInt(100);
Generate a random integer between 10 and 100:
int randomNumber = random.nextInt(91) + 10; // 101 - 100 = 91
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.Random
instance, calling thenextInt()
method multiple times will produce a seemingly random but actually deterministic sequence. Therefore, it is recommended to use theSecureRandom
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!