Search code examples
javacsvmultidimensional-arrayindexoutofboundsexceptionstring-parsing

Can't access last element of array


I am parsing a .CSV file, line after line and i want to get the values of the columns. So as example for my .CSV file :

time;columnA;columnB,ColumnC
27-08-2013 14:43:00; this is a text; this too; same here

So what I did is store the content in an bidimensional String array (thanks to split()). My array is made as follow :

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

they are x different columns, but the name of every column is only stored on line[0][x]. they are y different lines, with the value stored as String in it.

My problem is the following, I want to get the [x] position of the data, but when i try to access the last [x] element of the array. I receive this as error-message

java.lang.ArrayIndexOutOfBoundsException: 17
    at IOControl.ReadCsvFile.getPosVar(ReadCsvFile.java:22)
    at IOControl.ReadCsvFile.<init>(ReadCsvFile.java:121)
    at en.window.Main.main(Main.java:48)

Obviously i'm reading to far, but how?

Here my code :

//Retrieves the x position of the variable var given as 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 it may be because I didn't checked that my x value was smaller than the full string. like this :

x < index[x].length

But in fact I didn't changed anything, and when I give an unknown String var it also goes too far. Why?


Solution

  • Checking the validity of index before using it is also a good idea:

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

    Your while loop should look more like 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 the position found.
        }
        x++;
    }
    return -1;
    

    Using a for loop (which I 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 the position found.
        }
    }