|
In JDK5.0 there is a class import java.util.Random. *; Where the method nextInt can help you complete
First declare Random Random = new Random ();
int a = 0-random.nextInt (501)
public int nextInt (int n) returns a pseudo-random number, an int value uniformly distributed between 0 (inclusive) and the specified value (exclusive), taken from the sequence of this random number generator. The general contract of nextInt is to generate and return an int in the specified range pseudo-randomly. All n possible int values are generated with (roughly) the same probability. The Random class implements the nextInt (int n) method as follows:
public int nextInt (int n) {
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;
do {
bits = next (31);
val = bits% n;
} while (bits-val + (n-1) <0);
return val;
}
The ambiguous word "rough" was used in the previous description, just because the next method is roughly a fair source of individually selected bits. If it is the best source for randomly selecting bits, then the given algorithm should choose int values completely consistently from the starting range.
But this algorithm is slightly more complicated. It rejects values that cause an uneven distribution (because 2 ^ 31 cannot be divisible by n). The probability of a value being rejected depends on n. The worst case is n = 2 ^ 30 + 1, the probability of rejection is 1/2, and the estimated number of iterations before the loop terminates is 2.
This algorithm specifically treats cases where n is a power of two: it returns the correct high number of bits from the underlying pseudo-random number generator. In the case of no special handling, the correct low digits are returned. It is well known that linear congruence pseudorandom number generators (such as this class implements) have short periods in their low-value sequence of values. Therefore, if n is a power of two (lower power), this special case causes subsequent calls to this method to return a sequence of values whose length is greatly increased.
parameter:
n-the range of random numbers returned. Must be positive.
return:
A pseudo-random number with an evenly distributed int value between 0 (inclusive) and n (inclusive). |
|