功能
给定一个参数n,nextInt(n)将返回一个大于等于0小于n的随机数,即:0 <= nextInt(n) < n。
函数实现
/**
* Returns a pseudo-random uniformly distributed {@code int}
* in the half-open range [0, n).
*/
public int nextInt(int n) {
if (n <= 0) {
throw new IllegalArgumentException("n <= 0: " + n);
}
if ((n & -n) == n) {
return (int) ((n * (long) next(31)) >> 31);
}
int bits, val;
do {
bits = next(31);
val = bits % n;
} while (bits - val + (n - 1) < 0);
return val;
}
————————————————