隨機數(shù)產(chǎn)生

1. Random產(chǎn)生

這里示例,我們產(chǎn)生20個1000以內(nèi)的整數(shù)

import java.util.Random;

public class RandomTest {
    public static void random1(){
        Random r = new Random();
        for(int i=0;i<20;i++){
            int num = r.nextInt(1000);
            System.out.print(num + " ");
        }
    }

    public static void main(String[] args) {
        random1();
    }
}
//輸出
383 205 604 568 525 418 759 558 804 728 205 723 866 567 521 592 399 434 221 68 

注:
1)這里的nextInt產(chǎn)生的數(shù),包括[0,num),也就是這里是0-999
2)Random初始化的時候,默認(rèn)是沒有參數(shù)的,也就是以當(dāng)前時間為種子,
而當(dāng)然我們也可以指定一個long的參數(shù)作為種子,
3)如果種子相同,產(chǎn)生的隨機數(shù)序列也是相同的

2. 使用Math.random產(chǎn)生

產(chǎn)生一個指定范圍的隨機數(shù)

public static void random2(){
        int min = 1;
        int max = 100;
        for(int i=0;i<20;i++){
            double d = Math.random();
            int v = (int)(d * (max-min) + min);
            System.out.print(v + " ");
        }
        System.out.println();
    }
//輸出
74 88 65 13 34 72 13 14 13 75 62 92 9 73 45 47 16 64 74 52

注:
1)Math.random會產(chǎn)生一個[0.0-1.0)之間的隨機數(shù)
2)(int)(d(max-min) + min) 產(chǎn)生[min,max)之間的數(shù),d(max-min)產(chǎn)生[0,(max-min)),
d*(max-min) +min產(chǎn)生[min,max)之間的隨機數(shù)

3. ThreadLocalRandom產(chǎn)生

public static void random3(){
        for(int i=0;i<20;i++){
            int num = ThreadLocalRandom.current().nextInt(1000);
            System.out.print(num + " ");
        }
        System.out.println();
    }
//輸出
585 971 182 919 416 505 127 223 662 944 533 340 990 763 738 863 566 970 645 996

使用方法類似于第一種

4. 使用SecureRandom產(chǎn)生

使用加密的強隨機數(shù)生成器RNG,使產(chǎn)生的種子是真正的隨機數(shù),保證輸出的不確定性

public static void random4() throws NoSuchAlgorithmException {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        for(int i=0;i<20;i++){
            int num = random.nextInt(1000);
            System.out.print(num + " ");
        }
    }
//輸出
788 72 159 367 254 9 157 681 367 8 636 34 695 202 530 960 832 489 439 215
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容