在 Java 中,可以使用 java.util.Random 类或 Math.random() 方法来生成 1 到 100 的随机数,以下是几种常见的方法:

方法 1:使用 java.util.Random 类(推荐)
Random 类提供了更灵活的随机数生成方式,适合需要复杂随机数生成的场景。
import java.util.Random;
public class RandomNumberExample {
public static void main(String[] args) {
Random random = new Random();
// 生成 1 到 100 的随机数(包含 1 和 100)
int randomNumber = random.nextInt(100) + 1;
System.out.println("随机数: " + randomNumber);
}
}
说明:
random.nextInt(100)生成[0, 99]范围的随机数。- 加
1后范围变为[1, 100]。
方法 2:使用 Math.random()(简单场景)
Math.random() 返回 [0.0, 1.0) 的 double 值,适合简单的随机数需求。
public class MathRandomExample {
public static void main(String[] args) {
// 生成 1 到 100 的随机数(包含 1 和 100)
int randomNumber = (int)(Math.random() * 100) + 1;
System.out.println("随机数: " + randomNumber);
}
}
说明:
Math.random() * 100生成[0.0, 100.0)的浮点数。- 强制转
int后取整,得到[0, 99]。 - 加
1后范围变为[1, 100]。
方法 3:使用 ThreadLocalRandom(多线程环境)
如果代码运行在多线程环境中,推荐使用 ThreadLocalRandom 以提高性能。
import java.util.concurrent.ThreadLocalRandom;
public class ThreadLocalRandomExample {
public static void main(String[] args) {
// 生成 1 到 100 的随机数(包含 1 和 100)
int randomNumber = ThreadLocalRandom.current().nextInt(1, 101);
System.out.println("随机数: " + randomNumber);
}
}
说明:
nextInt(1, 101)直接生成[1, 100]的随机数(左闭右开区间)。
| 方法 | 适用场景 | 特点 |
|---|---|---|
Random |
通用 | 功能全面,适合复杂随机数生成 |
Math.random() |
简单场景 | 代码简洁,但不适合高性能需求 |
ThreadLocalRandom |
多线程 | 性能更好,避免竞争 |
选择合适的方法即可满足需求!


