1

Whilst I can get it to work on a 1 dimension array (String array[] = str.split(blah)), I have trouble on 2D arrays. I'm using a loop that goes through each row of the 2D array and assigns it whatever str.split(\t) has.

For example:

John\tSmith\t23
James\tJones\t21

My 2D array will look like this: {{John, Smith, 23}, {James, Jones, 21}} I've only begun Java so I'm not too sure about some of the syntax for 2D arrays.

EDIT: Some code as requested

String str;
int row = 0;
String array[][];
while ((str = br.readLine()) != null)   {
    array[row] = str.split("\t");
    System.out.println(array[row][0]);
    row++;
}
Baz
  • 36,440
  • 11
  • 68
  • 94
meiryo
  • 11,157
  • 14
  • 47
  • 52
  • 2
    What have you tried so far? What error are you getting? Can we see some code please? – Brian Sep 11 '12 at 15:50
  • Do you mean `array[0] = "John\tSmith\t23".split("\t");`? Are you getting a NullPointerException? If so did you allocate any space to the array? – Peter Lawrey Sep 11 '12 at 15:52
  • 1
    You cave to initialize your array before using it. You just declared it so far. – Baz Sep 11 '12 at 15:54
  • @Peter and Baz What if the data I want to put in the array is dynamic? This was my previous question on SO it might add some context: http://stackoverflow.com/questions/12370657/convert-a-string-last-tfirst-tage-to-an-array-with-elements-last-first-age – meiryo Sep 11 '12 at 15:54
  • 3
    @meiryo Then don't use arrays. Use a `List` instead, like [`ArrayList`](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html). – Baz Sep 11 '12 at 15:56

3 Answers3

4

You need to initialize your array as follows:

int rowCount = ...;
String array[][] = new String[rowCount][];

or in case you don't know the number of rows, you may use ArrayList instead:

List<String[]> list = new ArrayList<String[]>();
String str;
while((str = br.readLine()) != null)
{
    String[] array = str.split("\t");
    list.add(array);
}
String[][] array2D = new String[list.size()][];
list.toArray(array2D);
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
1

You have to use str.split("\\\\t"); The split method accepts a regular expression.
Check this post for more details

Community
  • 1
  • 1
basiljames
  • 4,777
  • 4
  • 24
  • 41
1

Your String array[][] must be initialized before use it.

If you can, move your code to use Lists to make it work:

List<List<String>> array = new ArrayList<List<String>>();
while ((str = br.readLine()) != null)   {
    array.add(Arrays.asList(str.split("\t")));
}

In case you must not use List, then initialize your array

final int SIZE = ...; //some value that would be the max size of the array of arrays
String array[][] = new String[SIZE][];
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332