java的Random()類使用方法

來源:互聯網
上載者:User

標籤:print   span   建立   參數   color   sys   random   new   隨機   

//隨機產生1~100之間的一個整數        int randomNumber = (int)(Math.random() * 100) + 1;        System.out.println(randomNumber);

這是直接使用Math.random()方法產生隨機數的方法。

還有使用Random類的方法。

Random():建立一個新的隨機數產生器。

Random(long seed):使用單個 long 種子建立一個新的隨機數產生器。

第一種構造方法是使用預設當前系統時間的毫秒數作為種子數:Random r1 = new Random();

Random random = new Random();
int randomNumber1= random.nextInt(100);

第二種方法是使用自己指定的種子數

Random random1 = new Random(100);
for(int i = 0; i < 10; i++){
System.out.print(random1.nextInt(10) + " ");
}

發現只要種子數和nextInt()中的參數一致的話,每次產生的隨機數都是一樣的(所以這是偽隨機數)。

System.out.println("\n使用同一種子產生的隨機數如下:");
Random random2 = new Random(100);
for(int i = 0; i < 10; i++){
System.out.print(random2.nextInt(10) + " ");
}

如下:

 

java的Random()類使用方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.