Search code examples
javaarraysexceptiongridcell

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3


I'm trying to implement an A* pathfinding algorithm in java. So I create a grid and the user is requested to give its dimensions. The problem is that when width!=height, the program throws that exception. For example, a grid 5x5 is created without problems, whereas a grid 5x7 is not. I'm not sure how I can fix it. Here is the code:

JFrame frame = new JFrame();
String rows =  JOptionPane.showInputDialog(frame,
                "Συμπληρώστε τον αριθμό γραμμών του πλέγματος: \n",
                "Δημιουργία πλέγματος",
                JOptionPane.PLAIN_MESSAGE);
String cols =  JOptionPane.showInputDialog(frame,
                "Συμπληρώστε τον αριθμό στηλών του πλέγματος: \n",
                "Δημιουργία πλέγματος",
                JOptionPane.PLAIN_MESSAGE);
int rowsnum = Integer.parseInt(rows); 
int colsnum = Integer.parseInt(cols);
transient Image buffer; 

GridCell gridCell[][] = new GridCell[rowsnum][colsnum];
public Map()
{
    super();
    //{{INIT_CONTROLS
    setLayout(new GridLayout(rowsnum,colsnum));
    //}}
    for(int i=0;i<rowsnum;i++){
        for(int j=0;j<colsnum;j++){
            System.out.println ("i=" + i + " j="+ j);
           gridCell[j][i] = new GridCell();
           gridCell[j][i].setPosition(new Point(j,i));
           add(gridCell[j][i]);
        }
    }
}

So as you see, I'm printing i and j in each loop to see where the problem is. And the result is (when I try to create a grid 3x5):

run:

i=0 j=0
i=0 j=1
i=0 j=2
i=0 j=3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at Map.<init>(Map.java:32)

Where line 32 is:

gridCell[j][i] = new GridCell();

If anyone could help me I'd be grateful!

P.S. Ignore the greek! :-D


Solution

  • On this line you create a 2D array that is rowsnum by colsnum

    GridCell gridCell[][] = new GridCell[rowsnum][colsnum];
    

    However here you use it as if it is colsnum by rowsnum.

    for(int i=0;i<rowsnum;i++){
        for(int j=0;j<colsnum;j++){
            System.out.println ("i=" + i + " j="+ j);
           gridCell[j][i] = new GridCell();
    

    i goes between 0 and rowsnum(exclusive) but goes in the dimention that is between 0 and colsnum(exclusive)

    j goes between 0 and colsnum(exclusive) but goes in the dimention that is between 0 and rowsnum(exclusive).

    Solution

    Either i and j are the wrong way round in gridCell[j][i] (and elsewhere) or rowsnum and colsnum are the wrong way round in new GridCell[rowsnum][colsnum]. Which it is depends on what you're trying to achieve, although conventionally its often array(rows,columns); implying i and j are the wrong way round