Java擷取隨機數

來源:互聯網
上載者:User

標籤:import   logs   lis   package   static   pack   exti   author   結果   

      Java中產生隨機數的方式

  1、System.currentTimeMillis()方法,該方法返回從1970年1月1號0點0分0秒到目前的一個long型的毫秒 數,可作為一個隨機數,還可以將其對某些數模數,就能限制隨機數的範圍;此方式在迴圈中同時產生多個隨機數時,會是相同的值,有一定的局限性! 

package 隨機數;/** * @author yyx 2017年6月24日 */public class CurrentTimeMill {    public static void main(String[] args) {       for(int i=0;i<5;i++){           //擷取從1970年1月1號0點0分0秒到目前的一個long型的毫秒 數           System.out.println(System.currentTimeMillis()+" ");       }    }}
運行結果:

1498288338862
1498288338862
1498288338862
1498288338862
1498288338862

  2、通過Math.random()返回一個 [0,1)之間的double值

package 隨機數;/** * @author yyx 2017年6月24日 */public class MathRandom {    public static void main(String[] args) {        // 迴圈產生5個小於100的正整數        // Math.random()返回一個 [0,1)之間的double值        for (int i = 0; i < 5; i++) {            // 強制轉換            System.out.println((int) (Math.random() * 100)+" "+Math.random());        }    }}
運行結果:

82 0.7843678627543349
81 0.27864491675273717
5 0.4861832936232885
50 0.9897001939511756
85 0.299979261363151

  3、通過Random類來產生一個隨機數,這個是專業的Random工具類,功能強大

package 隨機數;import java.util.Random;/** * @author yyx 2017年6月22日 */public class RandomExample {    public static void main(String[] args) {        produceRandom();    }    /**     * 隨機產生小於100的五個整數     */    public static void produceRandom() {        Random r = new Random();        for (int j = 0; j < 5; j++) {            System.out.println(r.nextInt(100));        }    }}

 

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.