標籤:java 隨機數
【方法一】
調用 util 中的 Random 類:定義Random的對象 rand,用 rand.nextInt()產生隨機整數
或者將 next 後面的Int改為 Double,Float , Long,分別對應了雙精確度,單精確度和長整形)
注意只有 nextInt( ) 可以帶參數,例如: rand.nextInt(10) 則隨機產生0到9的隨機數;
import java.util.Random;public class Test{public static void main(String[] args){Random xx=new Random();for(int i=0;i<10;i++){int number=xx.nextInt(10);System.out.println("random number are "+ number);}Random x2=new Random();for(int i=0;i<10;i++){int number=x2.nextInt(10);System.out.println("random number are "+ number);}}}
這時申請的兩個隨機數對象產生的隨機數的確是“隨機的”;
帶種子的Random產生的隨機數 例如:Random rand=Random(10) 種子為10,每次產生的隨機數就是一樣的了。
也可以可以用 rand.setSeed(n) 來重設種子;
import java.util.Random;public class Test{ public static void main(String[] args) { Random r=new Random(10); for(int i=0;i<10;i++){ System.out.println(r.nextInt(10)); } System.out.println(); Random r2=new Random(10);//種子都是10; for(int i=0;i<10;i++){ System.out.println(r2.nextInt(10));//輸出了相同的兩個序列 } } }
總結:
Random對象根據種子產生隨機數,種子相同的Random對象,無論何時運行它,也無論它在那台機器上,產生的隨機數序列都是相同的,種子不同的Random對象,產生的隨機數序列是不一樣的。
使用沒帶參數的Random建構函式產生的隨機數序列是當前系統時間的毫秒數。
【方法二】
1、Math庫裡的static(靜態)方法random()
該方法的作用是產生0到1之間(包括0,但不包括1)的一個double值。
double rand = Math.random();
public class Test{public static void main(String[] args){int a=(int)(Math.random()*1000);//用強制轉換的方法就可以實現確定範圍的隨機數了(代碼所示為0~999的隨機數)System.out.println(a);}}
java產生隨機數的兩種方式