iT邦幫忙

1

[Java] Math.random() 介紹

閱讀時間: 1分鐘

Java 的 Math.random()
屬於 java.lang.Math的class
不過實際上用的是 java.util.Random()來產出隨機數。
所以不用 Math.random()也可以用 Random()來產出隨機數。

通過 Math.random() 可以獲取隨機數 ,
它返回的是一個 [0.0, 1.0) 之間的 double 值 ,但不包括1.0

例子1:
使用 Math.random()

import java.util.Random;

private static void testMathRandom() { 
double random = Math.random();
System.out.println("random = " + random); 
}

輸出的結果會是double tpye的數字,大家不妨試一下。

例子2:
直接用 new Random()

import java.util.Random;

public class RandomTest{
	public static void main(String[] args){
		Random rand=new Random();
		int i=(int)(Math.random()*100);       // 會產出範圍在 0 ~ 100 之間的數字,再轉為type = int
		int j=rand.nextInt(100);              // 直接產出範圍在 0 ~ 100 之間的數字
		System.out.println("i:"+i+"\nj:"+j); //
	}
}

由於Random()的type是double,要讓它變成Integer就需要利用casting把double type的variable變為integer。
另外,如果你想用 new Random() 又想產出一個double type的值,你可以使用nextDouble()。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言