为了拥有一个数组的数组,您可以使用
ArrayList
如下所示:
List<String[]> arrayList = new ArrayList<>();
while ((myLine = bufRead.readLine()) != null) {
String[] vals = myLine.split(" ");
arrayList.add(vals);
}
这将遍历每一行,将其转换为数组,然后将其存储在ArrayList
中。
之后,您可以像这样迭代遍历ArrayList
:
for (String[] currLine : arrayList) {
for (String currString : currLine) {
System.out.print(currString + " ");
}
System.out.println();
}
这将打印:
run:
abc def zed fgf
qwe zxc ghj cvb
BUILD SUCCESSFUL(总时间:0秒)
编辑 创建了一个方法,可以查找您要查找的值的索引。
然而我建议像
"zxc"
这样搜索的结果应该是1,1而不是2,2,因为数组从0开始索引。
public static int[] getIndex(List<String[]> arrayList, String tofind) {
int[] index = new int[]{-1, -1};
for (int i = 0; i < arrayList.size(); i++) {
String[] currLine = arrayList.get(i);
for (int j = 0; j < currLine.length; j++) {
if (currLine[j].equals(tofind)) {
index = new int[]{i + 1, j + 1};
return index;
}
}
}
return index;
}
虽然这不是最高效的方法(它会遍历每个数组和该数组中的每个字符串),但它确实可以得到您想要的结果:
像这样调用它:
int[] zxcIndex = getIndex(arrayList, "zxc");
System.out.println(zxcIndex[0] + ", " + zxcIndex[1]);
将会打印出:
2, 2
我在处理这个问题时编写了这个print方法,你可以方便地将其用于调试:
public static void printList(List<String[]> arrayList) {
for (String[] currLine : arrayList) {
for (String currString : currLine) {
System.out.print(currString + " ");
}
System.out.println();
}
}
此外,如果你想在特定的索引位置更新数据,这样做会更简单:
public static void updateIndex(List<String[]> arrayList, int[] toUpdate, String value) {
String[] rowToUpdate = arrayList.get(toUpdate[0] - 1);
rowToUpdate[toUpdate[1] - 1] = value;
}
将所有内容放在一起,运行以下命令:
System.out.println("Current list:");
printList(arrayList);
int[] zxcIndex = getIndex(arrayList, "zxc");
System.out.println("\nIndex of xzc is: " + zxcIndex[0] + ", " + zxcIndex[1] + "\n");
updateIndex(arrayList, zxcIndex, "lmnop");
System.out.println("Modified list at index " + zxcIndex[0] + "," + zxcIndex[1] + " :");
printList(arrayList);
结果为:
运行:
当前列表:
abc def zed fgf
qwe zxc ghj cvb
xzc的索引是:2, 2
在索引2,2处修改后的列表为:
abc def zed fgf
qwe lmnop ghj cvb
构建成功(总时间:0秒)
myLine.split(":");
,这不意味着文件看起来更像是abc:def zed fgf
吗? - Jorn VerneeArray1 = []{abc, def, zed, ...}
而不是Array1 = []{abc def zed ...}
。这两者完全不同。在第一个中,您正在创建每行值的长度数组。在第二个中,您正在创建长度为1的数组,并将整行放入第一个索引中。 - robotlosArray1 = []{abc, def, zed, ...}
- user5469190