Java 中的 Math.random() 方法是什么?
0.0 ≤ random < 1.0
请注意,随机数大于或等于 0.0且小于 1.0。
如何在 Java 中使用 Math.random()?
即使对于初学者来说,使用Math.random()方法也非常简单。实施例1
让我们看一个基本示例以便清楚地理解。public class RandomTest {
public static void main(String[] args) {
double random1 = Math.random();
double random2 = Math.random();
System.out.println("First Random Number: " + random1);
System.out.println("Second Random Number: " + random2);
}
}
输出
第一个随机数:0.5486939400685561 第二个随机数:0.23550115674999972
在范围内使用 random() 方法
调用Math.random()方法看起来非常不言自明。然而,我们对随机数的需求并不总是在0和1的范围内。对于现实生活中的问题,我们也可以在其他指定的范围内进行操作。让我们看一下对给定范围(例如 1 到 50) 使用Math.random()方法的示例。实施例2
public class RandomNumberInRange {
public static int getRandom(int min, int max) {
int range = (max - min) + 1;
int random = (int) ((range * Math.random()) + min);
return random;
}
public static void main(String[] args) {
// Let's play Ludo with 4 Players
int dieRoll = getRandom(1, 6);
System.out.println("Red's Turn: " + dieRoll);
dieRoll = getRandom(1, 6);
System.out.println("Blue's Turn: " + dieRoll);
dieRoll = getRandom(1, 6);
System.out.println("Green's Turn: " + dieRoll);
dieRoll = getRandom(1, 6);
System.out.println("Yellow's Turn: " + dieRoll);
}
}
输出
红色回合:3 蓝色回合:2 绿色回合:6 黄色回合:4
GO TO FULL VERSION