vedi0boy
vedi0boy

Reputation: 1040

Weird error with 2d arrays

I'm a beginner programmer in java and I encountered an error that I think is very bizarre. Here's the error when I run the program:

java.lang.ExceptionInInitializerError
Caused by: java.lang.ArrayIndexOutOfBoundsException: 0
at test.mob.<init>(mob.java:14)
at test.test.<clinit>(test.java:21)
Exception in thread "main" Java Result: 1

I program in NetBeans and the error doesn't show up in the IDE, it only shows up when I run the program. Here is my code from the mob class to see if you can find the problem.

package test;

public class mob {
    int counter = 0;
    int[][] mob;
    int loopCount = 0;
    int loopCount2 = 0;

    public mob(){
    //0: x pos
    //1: y pos

     mob = new int[counter][1];
     mob[counter][0]=test.width;         
     mob[counter][1]=test.height/2;
     counter++;
}
public void mobLoop(){
    while(loopCount <=counter){
        while(loopCount2<2){
        mob[loopCount][0]--;
        loopCount2++;
        }
        loopCount2 = 0;
        loopCount++;
    }
    return;
    }

}

Upvotes: 1

Views: 65

Answers (1)

Kon
Kon

Reputation: 10810

Arrays are indexed from zero in Java. You are creating an Array of sizes [0][1], which has ZERO elements in the first dimension, and one in the second. Therefore, when you try to access the array on this line:

mob[counter][1]=test.height/2;

You are going out of bounds on both dimensions. You will need to add 1 to both dimensions to preserve bounds based on the code I see.

Upvotes: 1

Related Questions