1

I have a strange problem which I can't fix:

A field:

private boolean[][][] gaps;

Constructor (1st line):

gaps = new boolean[NOBARRICADES][WIDTH][HEIGHT];

Constructor (2nd line):

for (int i = 0; i < NOBARRICADES; i++) {

Java throws an error for the 2nd line, saying:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

Does it have anything to do with Java syntax (the mistake is in these lines of code) or I should look for the problem somewhere else?

3
  • Assuming NOBARRICADES is a constant int somewhere, it would be impossible for that for loop you posted to throw an exception, period. Can you post the actual code of what it's all doing? Commented Mar 23, 2010 at 17:55
  • 2
    Since there are no array references on the second line, I suspect that you haven't posted enough code for anyone to help you. Commented Mar 23, 2010 at 17:55
  • Can you show us the line where you're actually indexing gaps? The second line is not actually the source of the exception, your loop declaration is fine. I would assume you're referencing the wrong dimension of your array with i. Also pro-tip: Don't call loop variables simple things like i or j, call them something useful like "index" "inner_index" "first_index", anything descriptive, especially when you're going to nest loops. Commented Mar 23, 2010 at 17:57

3 Answers 3

1

You're probably misreading the error output. Your second line does not even access the array - make sure that it's not the first line of the body of the for-loop that throws the exception. Also, make sure that you use i only to index the first dimension of your array.

Sign up to request clarification or add additional context in comments.

Comments

0

sometimes the java compiler is off by a line or two. You may check the lines of code around the line that it says the error is on and see if you see anything.

2 Comments

When? In my experience the java compiler is NEVER off by "a line or two". The only difference would be if you downloaded the source file from the server it was running on and the FTP client you used inserted line breaks to format it differently.
I have this problem when I use the Java-source classes. I think it's a problem with the javadoc. The runtime gives a line number and if I check that line, it is from a completely other method.
0

Sorry, but you really don't want to do that.

Multidimensional arrays are never worth the confusion they cause--they have no positive value at all (with the POSSIBLE exception of a clear, obvious x,y array).

I suggest you try starting with either a list of two-dimensional arrays or a two-dimensional array of objects where each object contains a list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.