Getting to Know Java (Java Number Processing Class - Random Number)

1. Random numbers

    The use of generating random numbers in actual development is common, so it is very important to generate random numbers in the program. There are mainly two ways to generate random numbers in Java, namely calling the random() method of the Math class and the method provided by the Random class to generate random numbers of various data types.    

    1.1 Math.random() method 

    There is a random method in the Math class, which is used to generate random numbers. This method generates double random numbers greater than or equal to 0.0 and less than 1.0 by default, that is, 0 <= Math.random() < 1.0, although the Math.random() method only Double-type numbers between 0 and 1 can be generated. In fact, as long as the Math.random() statement is slightly processed, this method can be used to generate random numbers in any range.

(int)(Math.Random() * n) returns a random number greater than or equal to 0 and less than n
m + (int)(Math.Random() *n) returns a random number greater than or equal to m and less than m+n (excluding m+n)

    eg : Create a class, write the GetEvenNum() method in the class to generate a random number between two numbers, and output the random number in the main method.

public class MathRandom {
    /**
     * Define a method to generate even numbers
     * @param num1 starting range parameter
     * @param num2 end range parameter
     * @return a random even number in the range
     */
    public static int GetEvenNum(double num1 , double num2) {
        //Generate random numbers between num1 ~ num2
        int s = (int)num1 + (int)(Math.random() * (num2-num1));
        if(s%2 == 0) { //Check whether the random number is even
        	return s; //return
        }else { //The result is odd
        	return s + 1; // return the result + 1
        }
    }
    public static void main(String[] args) {
        //call the method to generate random numbers
        System.out.println("Any even number between 2 and 32:"+GetEvenNum(2, 32));
    }
}

    The running result is: 

Any even number between 2 and 32: 6

    The results of each run are different, which realizes the function of randomly generating data, and the values ​​generated by the ward are even numbers each time. In order to achieve this function, a method GetEvenNum() is defined here, and the residual flowers of this method are the upper and lower limits of generating random numbers. Because the m+(int)(Math.random()*n) statement can obtain random numbers between m ~ m+n, so " 2+(int)(Math.random()*(32-2)) ", This expression can find random numbers between 2 and 32. When you need to determine whether the number is an even number after obtaining the random number in this interval, you can do the remainder operation on the number by 2. If the number is odd, add 1 to the odd number and return to get an even number.

    Using the random() method of the Math class can also generate characters randomly, you can use the following code to generate characters between a~z 

(char)('a' + Math.random()*('z' - 'a' + a));

    Through the above expression, more random characters can be obtained, such as random characters between A ~ Z, and then random characters between any two characters can be inferred, which can be expressed by the following statement:

(char)(char1 + Math.random()*(char2 - char1 + 1));

     eg : Create a class, write the GetReandomChar() method in the class to generate random characters, and output the characters in the main method.

public class MathRandomChar {
    //Define to get random characters between any characters
    public static char GetRandomChar(char char1, char char2) {
        return (char)(char1 + Math.random()*(char2 - char1 + 1));
    }
    public static void main(String[] args) {
        //Get random characters between a~z
        System.out.println("Any lowercase character:" + GetRandomChar('a', 'z'));
        //Get random characters between A~Z
        System.out.println("Any uppercase character:" + GetRandomChar('A', 'Z'));
        //Get random characters between 0 and 9
        System.out.println("Any numeric character from 0 to 9:" + GetRandomChar('0', '9'));
    }
}

    The running result is:

Any lowercase character: l
Any uppercase character :P
0 to 9 any numeric character: 1

    The value returned by the random() method is actually a pseudo-random number, which obtains a series of numbers through complex operations. This method uses the current time as the parameter of the random number generator, so each time the program is executed, a different random number will be generated.

    1.2 Random class

    In addition to the random() method in the Math class that can obtain random numbers, Java also provides a way to obtain random numbers, which is the java.util.Random class. A random number generator can be created by instantiating a Random object.

    The syntax is as follows:

Random r = new Random();

    where: r refers to the Random object.

    When instantiating an object in this way, the Java compiler seeds the random number generator with the current time of the system, since the time cannot be the same every moment, the random number generated will be different, but if it runs too fast, It also generates random numbers with the same result in both runs.

    You can also set the seed of the random number generator when instantiating the Random object.

    The syntax is as follows:

Random r = new Random(seedValue);
    r : Random class object

    seedValue : the seed of the random number generator

    The Random class provides methods for obtaining random numbers of various data types. Here are a few commonly used methods:

public int nextInt() : returns a random integer
public int nextInt(int n) : returns a random integer greater than or equal to 0 and less than n
public long nextLong() : returns a random long value
public boolean nextBoolean() : returns a random boolean value
public float nextFloat() : returns a random float value
public double nextDouble() : returns a random double value
public double nexGaussian() : returns a double value with a probability density of Gaussian distribution

    eg: Create a class, create a Random object in the tired main method, use this object to generate various types of random numbers, and output the result.

import java.util.Random; //import package
public class RandomDemo {
public static void main(String[] args) {
Random random = new Random(); //Instantiate a Random class
System.out.println("Randomly generate an integer: " + random.nextInt());
System.out.println("Randomly generate an integer greater than or equal to 0 and less than 10: " + random.nextInt(10));
System.out.println("Randomly generate a boolean value: " + random.nextBoolean());
System.out.println("Randomly generate a double value: " + random.nextDouble());
System.out.println("Randomly generate a floating point value: " + random.nextFloat());
System.out.println("Randomly generate a double-precision value with a probability density of Gaussian distribution: " + random.nextGaussian());
}
}

    The running result is:

Randomly generate an integer greater than or equal to 0 and less than 10: 5
Randomly generate a boolean value: false
Randomly generate a double value: 0.4923202923804435
Randomly generate a float value: 0.6521005
Randomly generates a double value with a Gaussian distribution with probability density: -0.2458356560206751




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325605479&siteId=291194637