Home > Java > JavaBase > body text

How to generate random numbers in java

Release: 2019-12-28 15:41:16
Original
4212 people have browsed it

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:

1

double d = Math.random();

Copy after login

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

1

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

Copy after login

How to generate random numbers in java

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

1

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

Copy after login

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)

1

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

Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!