To have an array of arrays you could use an ArrayList like so:
List<String[]> arrayList = new ArrayList<>();
while ((myLine = bufRead.readLine()) != null) {
String[] vals = myLine.split(" ");
arrayList.add(vals);
}
This will go through each line, make it into an array and then store it in the ArrayList.
After, you can iterate through your ArrayList like this:
for (String[] currLine : arrayList) {
for (String currString : currLine) {
System.out.print(currString + " ");
}
System.out.println();
}
This will print:
run:
abc def zed fgf
qwe zxc ghj cvb
BUILD SUCCESSFUL (total time: 0 seconds)
EDIT Created a method that will find the index of the value you're looking for. However I suggest that searching for something like "zxc" result in 1,1 and not 2,2 because arrays are indexed at 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;
}
While not the most efficient way (it iterates through every Array and every String of that Array) it does get you the result that you're looking for:
Calling it like so:
int[] zxcIndex = getIndex(arrayList, "zxc");
System.out.println(zxcIndex[0] + ", " + zxcIndex[1]);
Will print:
2, 2
I wrote this print method up while working on this, you can use it to your convenience for debugging:
public static void printList(List<String[]> arrayList) {
for (String[] currLine : arrayList) {
for (String currString : currLine) {
System.out.print(currString + " ");
}
System.out.println();
}
}
Also, figured you might want to update at a given index, this is a lot easier:
public static void updateIndex(List<String[]> arrayList, int[] toUpdate, String value) {
String[] rowToUpdate = arrayList.get(toUpdate[0] - 1);
rowToUpdate[toUpdate[1] - 1] = value;
}
So putting this all together, running the following:
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);
results in:
run:
Current list:
abc def zed fgf
qwe zxc ghj cvb
Index of xzc is: 2, 2
Modified list at index 2,2 :
abc def zed fgf
qwe lmnop ghj cvb
BUILD SUCCESSFUL (total time: 0 seconds)
myLine.split(":");doesn't that mean the file looks more likeabc:def zed fgf.Array1 = []{abc, def, zed, ...}and notArray1 = []{abc def zed ...}. These are completely different. In the first, you are creating an Array of length of values per line. In the second, you are creating an Array of length 1 with the entire line in the first index.