Random Functions in Java

Source: Internet
Author: User

A random number is required for a recent project. A random number is randomly selected between 1 and 9 integers.

As a result, many people told Google to use math. Random (). The result is written as follows: int P = (INT) (math. Random () * 9); the result is that 1 and 9 are never random. This is wrong. It's too bad.

So I checked the javase docs. For this function, we will talk about it as follows:

ReturnsDoubleValue with a positive sign, greater than or equal0.0And less1.0.

Because less than 1.0 is forced to be converted to an integer, the above P will never be 9. 0 can be random, because the integer will be removed during forced conversion.

Finally, find the function random. nextint (int n:

Returns a random udorandom, uniformly distributedIntValue between 0 (random) and the specified value (exclusive)

For example, the appeal requirement can be written as: Random ran = new random (); int P = ran. nextint (9) + 1; to get the desired result.

If you want to random the range of any input positive integers, then:

Int createrandom (INT min, int max) {random = new random (); Return random. nextint (max-min + 1) + min ;}

It was very simple, but I copied the code on the network before, and the result was a tragedy, debugging for half a day. In the future, it is better to see the official docs.

 

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.