programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Liutauras Vilda
• Tim Cooke
• Jeanne Boyarsky
• Bear Bibeault
Sheriffs:
• Knute Snortum
• paul wheaton
• Devaka Cooray
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Ron McLeod
• Piet Souris
• Ganesh Patekar
Bartenders:
• Tim Holloway
• Carey Brown
• salvin francis

# Why am I getting "ArrayIndexOutOfBoundsException" and how can I avoid it?

Greenhorn
Posts: 13

I'm trying to implement "The Sieve of Eratosthenes" using the following algorithm/pseudocode "ALGORITHM Sieve(n)".

MY IMPLEMENTATION:

For n = 25, I get an array of all primes less than 25, which is good:

However, if I choose a different value for n (say for example, n = 100) I get the following error message in eclipse:

What do I have to do with my code to avoid the "ArrayIndexOutOfBoundsException" so that all prime numbers less than n are displayed, regardless of n's value.

According to the oracle docs, this error is "Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array."

I'm not sure why it works for 25, but not another number sieve(100).

Sheriff
Posts: 24632
56

Jim Gallagher wrote:... The index is either negative or greater than or equal to the size of the array.

The entries of an array of size n are numbered from 0 to n-1, is what that means. So if you attempt to use entry number n (which is what your error message says you did for n=100), you'll get an error.

I can see that your while-loop at lines 22 to 25 in your posted code has the potential of trying to set A[n] to zero -- I can't explain why it doesn't always try to set A[n] to zero but at any rate that code has a problem.

(I think that the only values of n for which the error doesn't occur are squares of primes, I suppose it might be interesting to find out if that's true but in your case it would be more useful to fix the problem.)

 Lasagna is spaghetti flvored cake. Just like this tiny ad: create, convert, edit or print DOC and DOCX in Java https://products.aspose.com/words/java