Method copied from the jdk src 1.4.2_03.
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
if ((n & -n) == n) // i.e. n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
boolean condition;
do {
bits = next(31);
val = bits%n;
condition = (bits - val + (n - 1) < 0);
if (confirmPositive) {
condition = (condition&&(val > 0));
}
} while (condition);
return val;