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


i'm trying implement a* pathfinding algorithm in java. create grid , user requested give dimensions. problem when width!=height, program throws exception. example, grid 5x5 created without problems, whereas grid 5x7 not. i'm not sure how can fix it. here 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=" + + " j="+ j);            gridcell[j][i] = new gridcell();            gridcell[j][i].setposition(new point(j,i));            add(gridcell[j][i]);         }     } } 

so see, i'm printing , j in each loop see problem is. , result (when try create 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     @ map.<init>(map.java:32) 

where line 32 is:

gridcell[j][i] = new gridcell(); 

if me i'd grateful!

p.s. ignore greek! :-d

on line create 2d array rowsnum colsnum

gridcell gridcell[][] = new gridcell[rowsnum][colsnum]; 

however here use if colsnum rowsnum.

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

i goes between 0 , rowsnum(exclusive) goes in dimention between 0 , colsnum(exclusive)

j goes between 0 , colsnum(exclusive) goes in dimention between 0 , rowsnum(exclusive).

solution

either i , j wrong way round in gridcell[j][i] (and elsewhere) or rowsnum , colsnum wrong way round in new gridcell[rowsnum][colsnum]. depends on you're trying achieve, although conventionally array(rows,columns); implying , j wrong way round


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -