java Random.nextInt()方法

來源:互聯網
上載者:User

標籤:next   random   pac   ble   包含   log   and   隨機   junit   

public int nextInt(int n)

該方法的作用是產生一個隨機的int值,該值介於[0,n)的區間,也就是0到n之間的隨機int值,包含0而不包含n。

 

直接上代碼:

package org.xiaowu.random.demo;import java.util.Random;import org.junit.Test;public class RandomDemo {        @Test    public void Demo(){        Random rnd = new Random();        int code = rnd.nextInt(8999) + 1000;        System.out.println("code:"+code);    }        @Test    public void Demo1(){        Random r = new Random();        int nextInt = r.nextInt();        Random r1 = new Random(10);        int nextInt2 = r1.nextInt();        System.out.println("nextInt:"+nextInt);        System.out.println("nextInt2:"+nextInt2);    }        /**     * 產生[0,1.0)區間的小數     *      */    @Test    public void Demo2(){        Random r = new Random();        double d1 = r.nextDouble();        System.out.println("d1:"+d1);    }        /**     * 產生[0,5.0)區間的小數     *      */    @Test    public void Demo3(){        Random r = new Random();        double d2 = r.nextDouble()* 5;        System.out.println("d1:"+d2);    }        /**     * 產生[1,2.5)區間的小數     *      */    @Test    public void Demo4(){        Random r = new Random();        double d3 = r.nextDouble() * 1.5 + 1;        System.out.println("d1:"+d3);    }        /**     * 產生任意整數     *      */    @Test    public void Demo5(){        Random r = new Random();        int n1 = r.nextInt();        System.out.println("d1:"+n1);    }            /**     * 產生[0,10)區間的整數     *      */    @Test    public void Demo6(){        Random r = new Random();        int n2 = r.nextInt(10);        int n3 = Math.abs(r.nextInt() % 10);        System.out.println("n2:"+n2);        System.out.println("n3:"+n3);    }            /**     * 產生[0,10]區間的整數     *      */    @Test    public void Demo7(){        Random r = new Random();        int n3 = r.nextInt(11);        int n4 = Math.abs(r.nextInt() % 11);        System.out.println("n3:"+n3);        System.out.println("n4:"+n4);    }        /**     * 產生[-3,15)區間的整數     *      */    @Test    public void Demo8(){        Random r = new Random();        int n4 = r.nextInt(18) - 3;        int n5 = Math.abs(r.nextInt() % 18) - 3;        System.out.println("n4:"+n4);        System.out.println("n5:"+n5);    }    }

 

java Random.nextInt()方法

聯繫我們

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