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