Three Methods of Generating Random Numbers in java

  • 2021-10-16 01:33:34
  • OfStack

Category 1 of the catalogue
Type 2
Type 3

The generation of random numbers is very common in 1 code, and we must master it. There are three main methods to generate random numbers in java:

Type 1: new Random () Type 2: Math. random () Type 3: currentTimeMillis ()

Type 1

The first requires the java. util. Random class to generate a random number generator, which is also the most commonly used one. There are two constructors, Random () and Random (ES22seed). The first is to take the current time as the default seed, and the second is to take the specified seed value. After generation, different types of numbers are generated by different statements.

Seed is to generate the first use value of random numbers. The mechanism is to transform the value of this seed into a certain point in the random number space through a function, and the generated random numbers are evenly scattered in the space. The random numbers generated in the future are all related to the previous random number. Take code as an example.


    public static void main(String[] args)
    {
        Random r = new Random(1);
        for(int i=0 ; i<5 ;  i++)
        {
              int ran1 = r.nextInt(100);
              System.out.println(ran1);
        }
    }

The five numbers generated under my compiler are all 85, 88, 47, 13, 54. If you use Random r = new Random (), the random numbers generated are different, which is the result of determining seeds.

Type 2

The value returned by the second method is [0.0, 1.0] double type value. Because the precision of double class number is very high, it can be regarded as random number at a certain degree. With the help of (int), integer random number can be obtained by type conversion. The code is as follows.


public static void main(String[] args)
{    
    int max=100,min=1;
    int ran2 = (int) (Math.random()*(max-min)+min); 
    System.out.println(ran2);
}


Type 3

As for the third method, although it is not commonly used, it is also a way of thinking. The method returns the milliseconds of one long type from 0:00:0 on January 1, 1970 (which is related to UNIX system) to the present, and the random numbers in the required range can be obtained after taking the module.


public static void main(String[] args)
{    
    int max=100,min=1;
    long randomNum = System.currentTimeMillis();  
    int ran3 = (int) (randomNum%(max-min)+min);  
    System.out.println(ran3);
    
}

Related articles: