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();
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());
2 .Get a random number between 1 and 100 (int type)
int num = (int)(Math.random()*100+1);
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:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
