Java n must be positive
I receive t开发者_C百科he 'n must be positive error' on this for
loop:
for(int i = 0; i < 8; i++){
array2[i] = CS2004.numbers.get(rand.nextInt(randomNumbers.size()));
}
Whenever I change it to the following, however, it seems to work well.
for(int i = 0; i < 8; i++){
array2[i] = CS2004.numbers.get(rand.nextInt(1000 + randomNumbers.size()));
}
Brief background on the method: it reads in a file containing the first 1000 prime numbers and then randomly adds them to an array of size 8.
Also, if I add the number 1 in place of 1000, it provides me with an answer of 2.0
for every index in the array. If I change it to 10, then the following is the output: [29.0, 29.0, 17.0, 11.0, 5.0, 19.0, 29.0, 2.0]
. For the sake of completing the example, when 100
is entered, the following is the result: [61.0, 107.0, 433.0, 193.0, 257.0, 29.0, 463.0, 127.0]
.
Does the number (10, 100, 1000, ..., n)
'tell' the result that it can add numbers which are up to the length of n? Or is it another explanation altogether?
Can anybody tell me why this error comes up?
Thank you.
The first time rand.nextInt() is called I assume randomNumbers.size() is 0. You are saying you want a random number from 0, which is less than 0 (the number you gave) which is non-sense. You have to give it a positive number so it can give you a sensible result.
My guess is the line should read
array2[i] = CS2004.numbers.get(rand.nextInt(CS2004.numbers.size()));
Here is what JavaDoc has to say about Random#nextInt(int)
Note that the pseudo code has if (n <= 0) throw new IllegalArgumentException("n must be positive");
quoting the excerpts here:
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All n possible int values are produced with (approximately) equal probability. The method nextInt(int n) is implemented by class Random as if by:
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; }
精彩评论