虽然我可以让它在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++;
}
答案 0 :(得分: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);
答案 1 :(得分:1)
您必须使用str.split("\\\\t");
split方法接受正则表达式
请检查此post for more details
答案 2 :(得分:1)
您的String array[][]
必须在使用前初始化。
如果可以,请移动代码以使用List
来使其正常工作:
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][];