1. Classes that use Java.lang.Math
The Math.random () method produces a random number, the resulting random number is a double between 0-1 and we can multiply it by a certain number, for example, by 100, which is a random number within 100.
2. Classes that use Java.util.Random
The Java.util.Random class is built in two ways: with seeds and without seeds
Without seeds:
This way will return random numbers, each running a different result
public class Randomtest {
public static void Main (string[] args) {
Java.util.Random r=new java.util.Random ();
for (int i=0;i<10;i++) {
System.out.println (R.nextint ());
}
}
With seeds:
This way, no matter how many times the program runs, the result is the same
public static void Main (string[] args) {
Java.util.Random r=new Java.util.Random (10);
for (int i=0;i<10;i++) {
System.out.println (R.nextint ());
}
}
The difference between the two approaches is that
(1) First Open the Java Doc, and we'll see a description of the Random class:
An instance of this class is used to generate a pseudo-random number stream, which uses a 48-bit seed that can be modified with a linear congruence formula (see Donald Knuth's "The Art of computer programming, Volume 2", section 3.2.1).
If you create two Random instances with the same seed, the same method call sequence is made for each instance, and they will generate and return the same sequence of numbers. To ensure this, we specify a specific algorithm for the class random. For the full portability of Java code, the Java implementation must have the class Random use all the algorithms shown here. However, subclasses of the Random class are allowed to use other algorithms as long as they conform to the general contract of all methods.
(2) If no seed number is provided, the seed number of the random instance will be the number of milliseconds of the current time, which can be obtained by System.currenttimemillis () to obtain the current time in milliseconds.
3. Using the system time
In our system class there is a Currenttimemillis () method, which returns a number of milliseconds from January 1, 1970 0:0 0 seconds to the current one, the return type is long, we can take him as a random number, we can take him to some number modulo, You can confine him to a range.
Java generates random numbers