Java random generation of digital methods

Source: Internet
Author: User
Tags abs current time

1, create the random type of object:

Random Random = new Random ();

Random Random = new Random (10010010);

Both of these are ways to create random objects, the first of which uses the default construction method, and is completely equivalent to the following code actions:

Random Random = new Random (System. Currenttimemillis ());

Rather, it is created using the current time as the seed number.

The second way is to create a seed number by specifying it yourself.

You can use either of these two methods as needed.

2. Generate Random Numbers:

Once we have created random objects, we can generate random numbers:

Generate random integers:

int k = Random.nextint ();

Generate Random long integers:

Long L = Random.nextlong ();

3, generate the specified range of numbers:

For example, to generate a random number between 0-10:

int k = Random.nextint ();

Int J = Math.Abs (k% 10);

First, we generate a random integer k, then use K and 10 to get the remainder, and finally use the ABS method of the math class to take the absolute value and obtain the random number between 0-10.

Get a random number between 0-15, like this:

int k = Random.nextint ();

Int J = Math.Abs (k% 15);

Get a random number between 10-20:

int k = Random.nextint ();

Int J = Math.Abs (k% 10) + 10;

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.