Home > Java > javaTutorial > What is the method to generate random numbers in java

What is the method to generate random numbers in java

王林
Release: 2022-01-12 15:10:26
Original
30969 people have browsed it

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.

What is the method to generate random numbers in java

#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();
Copy after login

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());
Copy after login

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

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

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!

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