user2007843
user2007843

Reputation: 609

How to properly use a 2-D array to store the results of split() of multiple strings?

I am trying to write a loop that goes over several lines of text, splitting each line - each string - into two elements, with the result populating a two-dimensional array. I am currently getting a java.lang.ArrayIndexOutOfBoundsException: 0 error with the code below, triggered on the split() line. I want to take the result of the split() call and use that with the rest of my program. Also, if I don't put an integer in the 2nd array box I get a compilation error - an argument is expected there.

String[][] arr = new String[numLines.size()][];

for(int i = 0 ; i < numLines.size(); i++) {
    arr[i][1].split("--", 2); 
    /* ... */
}

Upvotes: 2

Views: 989

Answers (2)

einpoklum
einpoklum

Reputation: 131515

You don't need to allocate the inner arrays yourself, String.split() does that for you. The reason you're getting the exception is that you're applying square brackets twice, i.e. you expect arr[i] to be a non-null array (and of size at least 2) so that you can assign to arr[i][1] - and that's not the case.

The thing is, you don't even need to use arr[i][whatever]. I think what you want to be doing is the following:

ArrayList<String> lines;

/*
 * you add your lines to the 'lines' here somehow.
 */

String[][] arr = new String[lines.size()][];

for(int i = 0; i < lines.size(); i++) {
        arr[i] = lines.get(i).split("--", 2); 
        /* etc. */
}

Upvotes: 3

Fritz
Fritz

Reputation: 10045

There's an issue with the definition of your array:

String[][] arr = new String[numLines.size()][];

The second dimention of your array is uninitialized. You can't access index 1 with your current setup. Try to load the array's data before trying to access it.

After defining it, you should populate it with (I presume) each "line" (whatever it is) from the data holder (say, a list, a reader, a file, you name it) that you get your numLines number from.

Edit

As einpoklum correctly spotted, the actual allocation of the array was done by the very split() method. Indeed, you were accessing a null reference

arr[i][1].split("--", 2); //NPE since arr[i] returns null

but the population was done on that same iteration (I'm taking ):

arr[i] = lines.get(i).split("--", 2); 

Upvotes: 5

Related Questions