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;