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.