How to generate random numbers in Java

Source: Internet
Author: User

Use the math class method math. Random (); Use the random class in the Java. util package. Of course, the latter

It looks more professional and has a wider applicability.

1. Math. Random ()
Public static double random () // generates a random number from 0.0 to 1.0.

If we want to generate a random number of integer types, it is also feasible to use forced type conversion.
The following is a demo that generates a random number between 1 and 10.
Package
Framework;
Import java. util .*;
Public class demo {
Public static
Void main (string [] ARGs ){
System. Out. println ("generate a random number from 0 to 10 :");
For
(INT I = 0; I <10; I ++)
System. Out. Print (INT) (math. Random () * 10)
+ "");
// If You Want To generate a number between 0 and 100, it will be * 100, and so on.
}
}

2. Random class

In Java, you can use the java. util. Random class to generate a random generator. It has two constructor methods:

① Random () // use the current time, namely system. currenttimemills (), as the generator Seed
② Random (int
Seed) // use the specified seed as the generator Seed

After a random number generator is generated for a random object, different methods such as nextint (), nextlong (), and nextfloat () can be called to obtain different types of random numbers. Taking the int type as an example, there are two methods for overloading:

Int nextint ()
Int nextint (int n) // generates an integer random number from 0 to n

Example programs with the same functions as above:

Package framework;
Import java. util .*;
Public class demo {

Public static void main (string [] ARGs ){

System. Out. println ("generate a random number from 0 to 10 :");
Random random = new random ();

For (INT I = 0; I <10; I ++)

System. Out. Print (random. nextint (10) + ""); // to generate a random number in other ranges, you only need to change the N value.
}

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.