How to use the random () class for Java

Source: Internet
Author: User

// randomly generates an integer        between 1~100 int randomnumber = (int) (Math.random () * +) + 1;        System.out.println (randomnumber);

This is a method of generating random numbers directly using the Math.random () method.

There is also a way to use the random class.

Random (): Creates a new random number generator.

Random (Long Seed): Creates a new random number generator with a single long seed.

The first method of construction is to use the default current system time as the number of milliseconds to seed: random r1 = new Random ();

Random random = new random ();
int randomnumber1= random.nextint (100);

The second method is to use the number of seeds that you specify

Random random1 = new random (100);
for (int i = 0; i < i++) {
System.out.print (Random1.nextint (10) + "");
}

It is found that as long as the number of seeds is consistent with the parameters in Nextint (), the random number generated each time is the same (so this is a pseudo-random number).

System.out.println ("\ n uses the same seed to generate random numbers as follows:");
Random random2 = new random (100);
for (int i = 0; i < i++) {
System.out.print (Random2.nextint (10) + "");
}

As follows:

How to use the random () class for Java

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.