CodeGym /Java Blog /Toto sisi /Java Math.random()方法實例
John Squirrels
等級 41
San Francisco

Java Math.random()方法實例

在 Toto sisi 群組發布

Java 中的 Math.random() 方法是什麼?

java.lang.Math.random() 方法傳回一個偽隨機的「double」型別數字,範圍從 0.0 到 1.0。
因此,Java使用內建方法產生的隨機數總是在0和1之間。
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

解釋

要獲得某個範圍內的隨機數,您需要從最大值減去最小值來計算範圍。然後,在使用Math.rand()計算範圍乘積後,您需要新增最小數。將 double 轉換為 int 後,您將獲得指定範圍內的隨機數。

結論

在本文結束時,我們希望您已經熟悉Java 中的Math.random()方法。繼續練習以更深入地掌握這個概念。到那時,繼續成長,繼續發光!
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION