1. Requirements: Get 10 random numbers between 1-20 and require no repetition
An array is implemented, but the length of the array is fixed and the length is not OK.
So we use a collection implementation.
Analysis:
• Create an object that produces a random number
• Create a collection that stores random numbers.
• define a statistical variable. Starting from 0.
• Determine if the statistical traversal is less than 10
is: A random number is generated to determine whether the random number exists in the collection.
If it does not exist: Add, Statistics variable + +.
If there is: do not respond to it.
No: Ignore it.
• iterating through the collection
2. Code implementation:
1 Packagecn.itcast_02;2 3 Importjava.util.ArrayList;4 ImportJava.util.Random;5 6 /*7 * Get a random number between 10 and 1-20, which requires no repetition8 * 9 * Implemented with an array, but the length of the array is fixed and the length is not OK. Ten * So we use the set implementation. One * A * Analysis: - * A: Create an object that produces a random number - * B: Create a collection that stores random numbers. the * C: Define a statistical variable. Starting from 0. - * D: Determine if the statistical traversal is less than ten - * Yes: A random number is first generated to determine if the random number exists in the collection. - * If not present: Add, Statistics variable + +. + * If there is: do not respond to it. - * No: Ignore it + * E: Traversing the collection A */ at Public classRandomdemo { - Public Static voidMain (string[] args) { - //create an object that produces a random number -Random r =NewRandom (); - - //creates a collection that stores random numbers. inarraylist<integer> array =NewArraylist<integer>(); - to //defines a statistic variable. Starting from 0. + intCount = 0; - the //determine if the statistical traversal is less than ten * while(Count < 10) { $ //generate a random number firstPanax Notoginseng intNumber = R.nextint (20) + 1; - the //determines whether the random number exists in the collection. + if(!array.contains (number)) { A //If it does not exist: Add, Statistics variable + +. the Array.add (number); +count++; - } $ } $ - //iterating through the collection - for(Integer i:array) { the System.out.println (i); - }Wuyi } the}
The results are as follows:
Java Basic Knowledge Hardening Collection Framework Note 35:list exercise generates random numbers between 10 1~20 (requires: Random numbers cannot be duplicated)