2016/1/14 Java random number generation

Source: Internet
Author: User

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

The function of this method is to produce a double value between 0 and 1 (including 0, but not 1).

double rand = Math.random ();

2, through the Random class object

A program can generate many different types of random numbers, which is simple, just call methods Nextint () and Nextfloat () (or call Nextlong () or nextdouble ()). The argument passed to Nextint () sets the upper limit of the resulting random number, and its lower bound is 0.

If no arguments are passed during the creation of the random object, Java will seed the current time as a random number generator and thus produce a different output each time the program executes. If the random object is created with a seed (used for the initialization value of the random number generator, which always produces the same sequence of random numbers for a particular seed value), the same random number can be generated each time the program executes, so its output is verifiable.

Example: Generate random numbers from 1 to 100

 1  import   Java.util.Random;  2   Public  class   radom{ 4  public  static  void   main (string[] strs) { 5  Rand Om rand = new   Random ();  6  System.out.println (Rand.nextint () +17   " 8 } 

To set the seed, the seeds in the following example can be arbitrarily set:

New Random (47);

2016/1/14 Java random number generation

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.