Home  >  Article  >  Java  >  How to generate random numbers in java

How to generate random numbers in java

尚
Original
2019-12-28 15:41:164192browse

How to generate random numbers in java

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:

double d = Math.random();

How to generate random numbers in java

How to generate random numbers in java

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

int i = (int)(Math.random());

How to generate random numbers in java

2 .Get a random number between 1 and 100 (int type)

int num = (int)(Math.random()*100+1);

How to generate random numbers in java

How to generate random numbers in java

3. Get a Random integer (int type) between any range (n~m)

int num = (int)(Math.random()*(m-n+1)+m);

Note: The decimal must be subtracted from the large number

Example:

How to generate random numbers in java

How to generate random numbers in java

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn