|
In Java we can use the Java.util.Random class to produce a random number generator. It has two forms of constructors, each of which is random () and random (long Seed). Random () uses the current time, System.currenttimemillis () as the seed of the generator, and random (long Seed) uses the specified seed as the seed of the generator.
After the random number generator (randomness) object is produced, different types of random numbers are obtained by calling different Method:nextint (), Nextlong (), Nextfloat (), nextdouble (), and so on.
1> Generating Random numbers
Random random = new random ();
Random random = new random (100);//Specify seed number 100
Random calls a different method to get the stochastic number.
Assuming that 2 random objects use the same seed (for example, 100) and call the same function in the same order, the return value is exactly the same. The output of the two random objects in the following code is completely 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> a random number within a specified range
Random number control within a range, using the modulo operator%
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 negative, using math.abs to make the obtained data range non-negative
3> gets the non-repeating random number 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 a 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]);
}
}
} |