java - Can't access last element of array -


i parsing .csv file, line after line , want values of columns. example .csv file :

time;columna;columnb,columnc 27-08-2013 14:43:00; text; too; same here 

so did store content in bidimensional string array (thanks split()). array made follow :

array[0][x] = "time". array[y][x] = "27-08-2013 14:43:00"; 

they x different columns, name of every column stored on line[0][x]. y different lines, value stored string in it.

my problem following, want [x] position of data, when try access last [x] element of array. receive error-message

java.lang.arrayindexoutofboundsexception: 17     @ iocontrol.readcsvfile.getposvar(readcsvfile.java:22)     @ iocontrol.readcsvfile.<init>(readcsvfile.java:121)     @ en.window.main.main(main.java:48) 

obviously i'm reading far, how?

here code :

//retrieves x position of variable var given parameter. private int getposvar(string[][] index, string var) {     int x = 0;     boolean cond = false;     while((index[0][x] != null) && (cond != true))     {         if (index[0][x].contains(var) == true)         {             cond = true;         }         x++;     }     system.out.println("x = " +x+ "  val = " +index[0][x]);     return(x); } 

i thought may because didn't checked x value smaller full string. :

x < index[x].length 

but in fact didn't changed anything, , when give unknown string var goes far. why?

checking validity of index before using idea:

if ( index == null || index.length == 0 ) return -1; 

your while loop should more this:

while ( x < index[0].length ) {     if ( index[0][x] == null )     {         x++;         continue; // skip possible null entries.     }      if ( index[0][x].contains(var) )     {         system.out.println("x = " + x + ", val = " + index[0][x]);         return x; // return position found.     }     x++; } return -1; 

using loop (which prefer):

for ( int x = 0; x < index[0].length; x++ ) {     if ( index[0][x] == null )         continue; // skip possible null entries.      if ( index[0][x].contains(var) )     {         system.out.println("x = " + x + ", val = " + index[0][x]);         return x; // return position found.     } } 

Comments

Popular posts from this blog

design - Custom Styling Qt Quick Controls -

Unable to remove the www from url on https using .htaccess -