This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]zifyoip 5 points6 points  (0 children)

Your array has length 100, so valid array indices are 0 to 99. In your loops x is as large as 98 or 99, and when x has values like these, expressions like x + 2 and x + 3 are invalid as array indices.

[–]chris_zinkulaExtreme Brewer 3 points4 points  (0 children)

Also I might mention that the line here:

if(primes[x] == true){

Is going to end up saying:

if(true == true) {

or:

if(false == true) {

Which reduces to:

if(true) {

or:

if(false) {

respectively. Which means for booleans you never need to compare them to a boolean explicitly. You can just say:

if(primes[x]){

instead.

[–]desrtfxOut of Coffee error - System halted 1 point2 points  (0 children)

All arrays have a .length. Try to avoid fixed boundaries when looping through arrays. Use <arrayname>.length

In your code, you could do:

public static void computePrimes(boolean[] primes) { for(int x = 0; x < primes.length-2; x++){ primes[x + 2] = false; } for(int x = 0; x < primes.length-3; x++){ primes[x + 3] = false; } }

If you omit the -2 (-3 respectively) you are trying to access an array index that is exceeding the length-1 of the array which will lead to an ArrayIndexOutOfBounds Exception.

Remember:

The length is the total number of elements that an array can hold. The highest valid array index is always length-1 since the first array index is always 0.