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 a Random number 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 testRandom1 () test //");} // generate a random number within a certain range. // For example, a random number must be generated in [0-n. // Note: Contains 0 and does not contain 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 testRandom2 () test ///////");} // generate random numbers that are not repeated within a certain range // the random numbers generated in testRandom2 may be repeated. // avoid this issue 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);} else {System. out. println ("this number has been added and cannot be added again") ;}} System. out. println ("// The above is testRandom3 () test ///////");}}
Main. xml is as follows: