自從JDK最初版本發布起,我們就可以使用java.util.Random類產生隨機數了。在JDK1.2中,Random類有了一個名為nextInt()的方法:
public int nextInt(int n)
public int nextInt(int n)
給定一個參數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;}