Java random number Math. random () function usage

Source: Internet
Author: User
Tags current time generator rand

1. The static (static) method random () in the Math library ()

This method is used to generate a double value between 0 and 1 (including 0, but not 1.

The code is as follows: Copy code

Double rand = Math. random ();

2. Through the Random class object

The program can generate many different types of random numbers. The procedure is simple. You only need to call the nextInt () and nextFloat () methods (or call nextLong () or nextDouble ()). The parameter passed to nextInt () sets the upper limit of the generated random number, and the lower limit is 0.

If no parameters are passed during the creation of the Random object, Java uses the current time as the seed of the Random number generator, and thus produces different output during each execution of the program. If a seed is provided when a Random object is created (for the initialization value of the Random number generator, the Random number generator always generates the same Random number sequence for a specific seed value ), the same random number can be generated every time the program is executed, so the output is verifiable.

Example: generate a random number between 1 and 100

The code is as follows: Copy code

Import java. util. Random;

Public class Radom {
Public static void main (String [] strs ){
Random rand = new Random ();
System. out. println (rand. nextInt (99) + 1 );
    }
}

Set the seed. In the following example, set the seed as needed:

The code is as follows: Copy code

Random rand = new Random (47 );

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.