java如何生成随机数
使用 java.util.Random 类
Random 类是 Java 中最基础的随机数生成工具,可以生成整数、浮点数等类型的随机值。
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
Random random = new Random();
// 生成 0 到 99 的随机整数
int randomInt = random.nextInt(100);
System.out.println("Random Integer: " + randomInt);
// 生成 0.0 到 1.0 的随机浮点数
double randomDouble = random.nextDouble();
System.out.println("Random Double: " + randomDouble);
// 生成随机布尔值
boolean randomBoolean = random.nextBoolean();
System.out.println("Random Boolean: " + randomBoolean);
}
}
使用 Math.random() 方法
Math.random() 返回一个 double 类型的伪随机数,范围在 [0.0, 1.0) 之间。如果需要整数,可以结合类型转换使用。
public class MathRandomExample {
public static void main(String[] args) {
// 生成 0.0 到 1.0 的随机浮点数
double randomDouble = Math.random();
System.out.println("Random Double: " + randomDouble);
// 生成 0 到 99 的随机整数
int randomInt = (int)(Math.random() * 100);
System.out.println("Random Integer: " + randomInt);
}
}
使用 ThreadLocalRandom 类(Java 7+)
ThreadLocalRandom 是 Random 类的线程安全优化版本,适用于多线程环境。
import java.util.concurrent.ThreadLocalRandom;
public class ThreadLocalRandomExample {
public static void main(String[] args) {
// 生成 0 到 99 的随机整数
int randomInt = ThreadLocalRandom.current().nextInt(100);
System.out.println("Random Integer: " + randomInt);
// 生成 10 到 99 的随机整数(指定范围)
int boundedInt = ThreadLocalRandom.current().nextInt(10, 100);
System.out.println("Bounded Random Integer: " + boundedInt);
}
}
使用 SecureRandom 类(加密安全)
SecureRandom 提供更强的随机性,适用于密码学或安全敏感场景。
import java.security.SecureRandom;
public class SecureRandomExample {
public static void main(String[] args) {
SecureRandom secureRandom = new SecureRandom();
// 生成 0 到 99 的随机整数
int randomInt = secureRandom.nextInt(100);
System.out.println("Secure Random Integer: " + randomInt);
// 生成随机字节数组
byte[] randomBytes = new byte[16];
secureRandom.nextBytes(randomBytes);
System.out.println("Random Bytes: " + Arrays.toString(randomBytes));
}
}
生成指定范围的随机数
如果需要生成某个范围内的随机数,可以使用以下方式:
int min = 10;
int max = 20;
int randomInRange = ThreadLocalRandom.current().nextInt(min, max + 1);
System.out.println("Random in Range: " + randomInRange);
生成随机字符串
结合随机数和字符集可以生成随机字符串:
import java.util.Random;
public class RandomStringExample {
public static void main(String[] args) {
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuilder sb = new StringBuilder(10);
for (int i = 0; i < 10; i++) {
int index = random.nextInt(characters.length());
sb.append(characters.charAt(index));
}
System.out.println("Random String: " + sb.toString());
}
}






