Method to generate random numbers: 1. Use the [double d = Math.random();] statement to obtain a random number; 2. Use [int num = (int)(Math.random()*100 1 );] statement obtains a random number between 1 and 100.
#We can use the Math class provided in Java to generate random numbers.
The Math class is under the java.lang package, and jvm will automatically import it, so there is no need to import the package.
To generate random numbers, use the random() method under the Math class. The return value of the random() method is [0.0 - 1.0).
Video tutorial recommendation: java video
1. Get a random number within the above range:
double d = Math.random();
Note: If the above formula is written as follows , then the value of i will only be 0. Because the range of random numbers generated by Math.random() is [0.0 - 1.0), no matter what the random number is, the value will only be 0 when converted to int.
int i = (int)(Math.random());
2. Get a random number (int type) between 1 and 100
int num = (int)(Math.random()*100+1);
Recommended tutorial: Getting started with java development
The above is the detailed content of What is the method to generate random numbers in java. For more information, please follow other related articles on the PHP Chinese website!