1

虽然我可以让它在 1 维数组 ( String array[] = str.split(blah)) 上工作,但我在 2D 数组上遇到了麻烦。我正在使用一个循环遍历 2D 数组的每一并为其分配任何str.split(\t)内容。

例如:

John\tSmith\t23
James\tJones\t21

我的 2D 数组看起来像这样:{{John, Smith, 23}, {James, Jones, 21}} 我才开始使用 Java,所以我不太确定 2D 数组的一些语法。

编辑:根据要求的一些代码

String str;
int row = 0;
String array[][];
while ((str = br.readLine()) != null)   {
    array[row] = str.split("\t");
    System.out.println(array[row][0]);
    row++;
}
4

3 回答 3

4

您需要按如下方式初始化数组:

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

或者如果您不知道行数,您可以使用 ArrayList 代替:

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);
于 2012-09-11T15:57:19.580 回答
1

您必须使用str.split("\\\\t");split 方法接受正则表达式。
查看此帖子以获取更多详细信息

于 2012-09-11T16:01:24.553 回答
1

String array[][]必须在使用前进行初始化。

如果可以,请将您的代码移动到使用Lists 以使其工作:

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

如果您不能使用List,请初始化您的数组

final int SIZE = ...; //some value that would be the max size of the array of arrays
String array[][] = new String[SIZE][];
于 2012-09-11T16:02:22.137 回答