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.