java產生隨機數的兩種方式

來源:互聯網
上載者:User

標籤: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產生隨機數的兩種方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.