1. Generation of random numbers
The first way: Use the toolkit java.lang.util.Random to generate
Private Static void Suiji () { random R=New random (); int ival; for (int i=0;i<10;i++) { ival=r.nextint (); System.out.println (ival); } }
The code means: generate 0-50 random numbers, there are duplicates.
The second way: using the Math class
Private Static voidSuiji2 () {DoubleDval; Longlval; intival; for(inti=0;i<10;i++) {Dval=math.random () *100; //1. Rounding with the math function//Ival=math.round (Dval); //2. Convert double to int with type castIval= (int) Math.Round (dval); System.out.println (ival); } }
The code uses the method provided by math to get a floating-point number between 0-1. Then multiply by how much to get the corresponding range of numbers, such as 100, the decimal point to the right two bits, get the number between 0-100, but get a floating-point, with a decimal, and then use the rounding function round or int forced type conversion to get an integer, but also contains the number of duplicates.
The third type: the use of UUID code generation:
Private Static void Suiji3 () { for (int i=0;i<10;i++) { String uuid=uuid.randomuuid (). ToString (); SYSTEM.OUT.PRINTLN (UUID); } }
Code generation never repeats the UUID code.
We now generate non-repeating random numbers for the first two implementations.
private static void Suiji4 (int n,int m) {Integer arr[]=new integer[n]; Random r=new random (), int index=0;int Ival;while (True) {Boolean tag=false;ival=r.nextint (M); for (int i=0;i<index;i+ +) {if (arr[i] = = ival) {tag=true;break;}} if (!tag) {arr[index++]=ival;} if (index = = N) {break;}} Arrays.sort (arr); for (int a:arr) {System.out.println (a);}}
The use of a tag bit Boolean tag to determine whether the array contains the random number just generated, not added to the array, there is a new generation, pass two parameters, print N m range of non-repeating random number.
Java Learning Diary