Measure the test taker's knowledge about how to process random numbers in j2s.

Source: Internet
Author: User
Tags abs current time
Generate random numbers in the program, and compare their usefulness, such as in the field of artificial intelligence. Here we will make a simple arrangement for the operation of generating random numbers in j2s, hoping to help everyone.
Unlike J2SE, you cannot use the random of the Math class to generate Random numbers. You can only use the random class of the java. util package to generate Random numbers.
1. Create a Random object:
Random random = new Random ();
Random random = new Random (10010010 );
The above two methods are used to create a Random object. The first method uses the default constructor, which is equivalent to the following code:
Random random = new Random (System. currentTimeMillis ());
It is equivalent to using the current time as the seed number for creation.
The second method is to specify the seed number by yourself.
You can use either of the above two methods as needed.
2. Generate random numbers:
After a random object is created, we can generate a random number:
Generate a random integer:
Int k = random. nextInt ();
Generate a random long integer:
Long l = random. nextLong ();
3. Generate numbers in the specified range:
For example, generate a random number between 0 and 10:
Int k = random. nextInt ();
Int j = Math. abs (k % 10 );
First, generate a random integer k, then use k and 10 to obtain the remainder, and finally use the abs method of the Math class to obtain the absolute value and random numbers between 0 and 10.
Obtain a random number between 0 and 15, for example:
Int k = random. nextInt ();
Int j = Math. abs (k % 15 );
Obtain a random number between 10 and 20:
Int k = random. nextInt ();
Int j = Math. abs (k % 10) + 10;

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.