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如下:
标签:android