Java Math random()方法返回一個(gè)大于或等于0.0且小于1.0的值。
該andom()方法的語法為:
Math.random()
注意:random()方法是靜態(tài)方法。因此,我們可以使用類名Math直接調(diào)用該方法。
Math.random()方法不帶任何參數(shù)。
返回介于0.0和1.0之間的偽隨機(jī)值
注意:返回的值不是真正隨機(jī)的。 取而代之的是,數(shù)值是通過滿足某種隨機(jī)性條件的確定的計(jì)算過程來生成的。 因此稱為偽隨機(jī)值。
class Main { public static void main(String[] args) { // Math.random() // 第一隨機(jī)值 System.out.println(Math.random()); // 0.45950063688194265 // 第二隨機(jī)值 System.out.println(Math.random()); // 0.3388581014886102 // 第三隨機(jī)值 System.out.println(Math.random()); // 0.8002849308960158 } }
在上面的示例中,我們可以看到random()方法返回三個(gè)不同的值。
class Main { public static void main(String[] args) { int upperBound = 20; int lowerBound = 10; //上限20也將包括在內(nèi) int range = (upperBound - lowerBound) + 1; System.out.println("10到20之間的隨機(jī)數(shù):"); for (int i = 0; i < 10; i ++) { //生成隨機(jī)數(shù)。 //(int)將雙精度值轉(zhuǎn)換為int。 //Math.round()生成0.0到1.0之間的值 int random = (int)(Math.random() * range) + lowerBound; System.out.print(random + ", "); } } }
輸出結(jié)果
10到20之間的隨機(jī)數(shù): 15, 13, 11, 17, 20, 11, 17, 20, 14, 14,
class Main { public static void main(String[] args) { //創(chuàng)建數(shù)組 int[] array = {34, 12, 44, 9, 67, 77, 98, 111}; int lowerBound = 0; int upperBound = array.length; //array.length不包括在內(nèi) int range = upperBound - lowerBound; System.out.println("隨機(jī)數(shù)組元素:"); //訪問5個(gè)隨機(jī)數(shù)組元素 for (int i = 0; i <= 5; i ++) { // get random array index int random = (int)(Math.random() * range) + lowerBound; System.out.print(array[random] + ", "); } } }
輸出結(jié)果
隨機(jī)數(shù)組元素: 67, 34, 77, 34, 12, 77,