Random, randomly

Source: Internet
Author: User

Random, randomly
Several Methods for java to generate random numbers

I. in j2se, we can use Math. the random () method is used to generate a random number. the random number is a double between 0 and 1. int is required for forced conversion. We can multiply it by a certain number, for example, multiplied by 100, it is a random value of less than 100, which is not found in j2s.

The java. util. Random class can be constructed in either of the following ways: With or without seeds

1. No seed

1 int ran = (int) (Math. random ());

* Math. random () must be enclosed in parentheses; otherwise, 0 is returned, because the int is forcibly converted to 1 int ran = (int) Math. random (); // error example

2. Seed

Int ran = (int) (Math. random () * 10); // 0 ~ Number between 10
Int ran = (int) (Math. random () * 10 + 5); // generates 5 ~ Between 10

 


II. in java. the util package provides a Random class. We can create a new Random object to generate a Random number. It can generate Random integers, Random float, Random double, Random long, this is also a method that we often use to retrieve random numbers in the j2's program.

Random ran = new Random (10); // nextInt () returns the next Random number ran. nextInt ();

10 does not affect the range of random numbers,

Ran. nextInt (10); // generate 0 ~ Random Number of 10

Error example: generate a random number between 5 and 10

ran.nextInt(10)+5;

Correct example: generate a random number between 10 and 50

1 int ran = new Random (). nextInt (50) + 10;


III. there is a currentTimeMillis () method in our System class. This method returns a millisecond value from 00:00:00, January 1, January 1, 1970. The return type is long. We can use it as a random number, we can use him to modulo some numbers to limit him to a certain range.

In fact, the default construction method of Random also uses the third method to generate Random numbers.

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.