Java provides a class for obtaining random numbers (Math)
The Math class is a very useful mathematical help class and is very simple to use. This class It is quite special. First of all, it is decorated with final like the String class, so it cannot have subclasses. Also, its construction method is private, that is, we cannot construct Math objects in other classes through the new method, then we How to call its methods? It turns out that all its methods are static methods, that is, you can access the methods directly using the class name.
To generate random numbers, use the method under the Math class: the return value of the random() method is [0.0 - 1.0)
1. Get the random number in the above range:
1 |
|
Note: If the above formula is written as follows, then the value of i will only be 0; because Math.random The range of random numbers generated by () is [0.0 - 1.0). At this time, no matter what the random number is, when it is converted to int, the value will only be 0
1 |
|
2 .Get a random number between 1 and 100 (int type)
1 |
|
3. Get a Random integer (int type) between any range (n~m)
1 |
|
Note: The decimal must be subtracted from the large number
Example:
For more java knowledge, please pay attention to the java basic tutorial column.
The above is the detailed content of How to generate random numbers in java. For more information, please follow other related articles on the PHP Chinese website!