【问题标题】:2D array[row][] = str.split("\t") not behaving as expected2D array[row][] = str.split("\t") 未按预期运行
【发布时间】:2012-09-04 14:35:50
【问题描述】:

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

例如:

John\tSmith\t23
James\tJones\t21

我的二维数组将如下所示:{{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++;
}

【问题讨论】:

  • 到目前为止你尝试过什么?你遇到了什么错误?我们可以看看一些代码吗?
  • 你的意思是array[0] = "John\tSmith\t23".split("\t");?你得到一个 NullPointerException 吗?如果是这样,您是否为数组分配了任何空间?
  • 你在使用它之前先初始化你的数组。到目前为止,您刚刚声明了它。
  • @Peter and Baz 如果我想放入数组中的数据是动态的怎么办?这是我之前的问题,它可能会添加一些上下文:stackoverflow.com/questions/12370657/…
  • @meiryo 然后不要使用数组。请改用List,例如ArrayList

标签: java multidimensional-array


【解决方案1】:

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

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);

【讨论】:

    【解决方案2】:

    您的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][];
    

    【讨论】:

      【解决方案3】:

      你必须使用str.split("\\\\t"); split 方法接受一个正则表达式。
      检查这个post for more details

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-11-12
        • 1970-01-01
        • 2020-06-28
        • 2012-02-18
        • 2018-01-18
        • 2012-06-14
        • 2019-03-03
        相关资源
        最近更新 更多