MainActivity is as follows:
package cc.test; import java.util.HashSet; import java.util.Random; import android.app.Activity; import android.os.Bundle; /** * * Demo description: * Use Random to generate random numbers in Java * * References: * 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(); } //generate random numbers private void testRandom1(){ Random random=new Random(); for (int i = 0; i <5; i++) { System.out.println("random.nextInt()="+random.nextInt()); } System.out.println("/////The above is the test of testRandom1()///////"); } //Generate random numbers within a certain range. //For example, here it is required to generate random numbers within [0 - n). //Note: include 0 but not 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("/////The above is the test of testRandom2()///////"); } //Generate non-repeating random numbers within a certain range // The random numbers generated in testRandom2 may be duplicated. // avoid the problem here 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("Generated randomInt="+randomInt); if (!integerHashSet.contains(randomInt)) { integerHashSet.add(randomInt); System.out.println("randomInt="+randomInt added to HashSet); }else { System.out.println("The number has been added and cannot be added repeatedly"); } } System.out.println("/////The above is the test of testRandom3()///////"); } }