Java. util. Random class to generate a random number generator. It has two forms of constructor: Random () and random (long seed ). Random () uses the current time (system. currenttimemillis () as the generator seed, and random (long seed) uses the specified seed as the generator seed.
After a random number generator (random) object is generated, different types of random numbers are obtained by calling different methods: nextint (), nextlong (), nextfloat (), and nextdouble.
1> generate random number
Random random = new random ();
Random random = new random (100); // specify the number of seeds as 100
Random calls different methods to obtain random numbers.
If two random objects use the same seed (for example, 100) and call the same function in the same order, they return identical values. For example, the output of the two random objects in the following code is identical.
Import java. util .*;
Class testrandom {
Public static void main (string [] ARGs ){
Random random1 = new random (100 );
System. Out. println (random1.nextint ());
System. Out. println (random1.nextfloat ());
System. Out. println (random1.nextboolean ());
Random random2 = new random (100 );
System. Out. println (random2.nextint ());
System. Out. println (random2.nextfloat ());
System. Out. println (random2.nextboolean ());
}
}
2> random number within the specified range
The random number is controlled within a certain range and the modulus operator % is used.
Import java. util .*;
Class testrandom {
Public static void main (string [] ARGs ){
Random random = new random ();
For (INT I = 0; I <10; I ++ ){
System. Out. println (math. Abs (random. nextint () % 10 );
}
}
}
The obtained random number has positive and negative values. use math. ABS to make the obtained data range non-negative.
3> obtain random numbers within the specified range
Import java. util .*;
Class testrandom {
Public static void main (string [] ARGs ){
Int [] intret = new int [6];
Int intrd = 0; // store random numbers
Int COUNT = 0; // record the number of random numbers generated
Int flag = 0; // whether the flag has been generated
While (count <6 ){
Random RDM = new random (system. currenttimemillis ());
Intrd = math. Abs (RDM. nextint () % 32 + 1;
For (INT I = 0; I <count; I ++ ){
If (intret [I] = intrd ){
Flag = 1;
Break;
} Else {
Flag = 0;
}
}
If (flag = 0 ){
Intret [count] = intrd;
Count ++;
}
}
For (int t = 0; t <6; t ++ ){
System. Out. println (t + "->" + intret [T]);
}
}
}
For details, see the document