Android中利用Random產生隨機數

來源:互聯網
上載者:User

MainActivity如下:

package cc.test;import java.util.HashSet;import java.util.Random;import android.app.Activity;import android.os.Bundle;/** *  * Demo描述: * Java中利用Random產生隨機數 *  * 參考資料: * 1 http://blog.csdn.net/herrapfel/article/details/1885016 * 2 http://blog.csdn.net/yuxuepiaoguo/article/details/4195198 * 3 http://blog.csdn.net/zhongyili_sohu/article/details/7906125 * 4 http://www.csdn.net/article/2012-03-22/313407 *   Thank you very much */public class TestRandomActivity extends Activity {    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        testRandom1();        testRandom2();        testRandom3();    }                //產生隨機數    private void testRandom1(){    Random random=new Random();    for (int i = 0; i <5; i++) {System.out.println("random.nextInt()="+random.nextInt());}    System.out.println("/////以上為testRandom1()的測試///////");    }                //在一定範圍內產生隨機數.    //比如此處要求在[0 - n)內產生隨機數.    //注意:包含0不包含n    private void testRandom2(){    Random random=new Random();    for (int i = 0; i <10; i++) {System.out.println("random.nextInt()="+random.nextInt(20));}    System.out.println("/////以上為testRandom2()的測試///////");    }            //在一定範圍內產生不重複的隨機數    //在testRandom2中產生的隨機數可能會重複.    //在此處避免該問題    private void testRandom3(){    HashSet integerHashSet=new HashSet();    Random random=new Random();    for (int i = 0; i <10; i++) {    int randomInt=random.nextInt(20);    System.out.println("產生的randomInt="+randomInt);    if (!integerHashSet.contains(randomInt)) {    integerHashSet.add(randomInt);    System.out.println("添加進HashSet的randomInt="+randomInt);}else {System.out.println("該數字已經被添加,不能重複添加");}}    System.out.println("/////以上為testRandom3()的測試///////");    }    }


main.xml如下:

    


聯繫我們

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