How to generate random numbers in Java?
In Java, you can use the Random class to generate random numbers. Here is an example:
import java.util.Random;
public class RandomNumberGenerator {
public static void main(String[] args) {
Random random = new Random();
// 生成一个随机整数
int randomNumber = random.nextInt();
// 生成一个指定范围内的随机整数
int randomNumberInRange = random.nextInt(100); // 生成0到99之间的随机整数
// 生成一个随机浮点数
double randomDouble = random.nextDouble();
// 生成一个随机布尔值
boolean randomBoolean = random.nextBoolean();
System.out.println("随机整数: " + randomNumber);
System.out.println("指定范围内的随机整数: " + randomNumberInRange);
System.out.println("随机浮点数: " + randomDouble);
System.out.println("随机布尔值: " + randomBoolean);
}
}
In this example, we use the nextInt() method of the Random class to generate random integers, the nextDouble() method to generate random floats, and the nextBoolean() method to generate random boolean values. You can also use the nextInt(int n) method to generate random integers within a specified range, where n is the upper limit of the range (exclusive).
Please note that instances of the Random class should only be created once and reused multiple times when generating random numbers. Otherwise, due to issues with the random number seed, duplicate random numbers may occur.