在Java中生成随机数通常使用 " java.util.Random " 类。
import java.util.Random;
public class Main {
public static void main(String[] args) {
// 创建一个Random对象
Random random = new Random();
// 生成一个随机整数
int randomNum = random.nextInt();
System.out.println("随机整数:" + randomNum);
// 生成一个随机双精度浮点数
double randomDouble = random.nextDouble();
System.out.println("随机双精度浮点数:" + randomDouble);
}
}
生成一个指定范围内的整数:
import java.util.Random;
public class Main {
public static void main(String[] args) {
// 创建一个Random对象
Random random = new Random();
// 生成一个 [0, 99] 的随机整数
int randomNum1 = random.nextInt(100);
System.out.println("[0, 99] 的随机整数:" + randomNum1);
// 生成一个 [10, 99] 的随机整数
int randomNum2 = random.nextInt(90) + 10;
System.out.println("[10, 99] 的随机整数:" + randomNum2);
// 生成一个 [87, 101] 的随机整数
int randomNum3 = random.nextInt(101 - 87 + 1) + 87;
System.out.println("[87, 101] 的随机整数:" + randomNum3);
// 生成一个 (87, 101) 的随机整数
int randomNum4 = random.nextInt(100 - 88 + 1) + 88;
System.out.println("(87, 101) 的随机整数:" + randomNum4);
}
}
通过上述例子,我们得出结论,如果要生成 [min, max] 范围内的随机整数:
int randomNum = random.nextInt(max - min + 1) + min;
1918

被折叠的 条评论
为什么被折叠?



