I was able to get the program to read a 2D array from a txt file, but with only setting the row and column length beforehand.
Is there any way to make it so It can read any .txt file without having to preset the column and row length?
here's my code :
public class GridReader {
private static final int ROW = 3;
private static final int COL = 3;
public static void main(String[] args) throws FileNotFoundException {
File file = new File("C:\\Users\\sitar\\Desktop\\GridReader\\src\\2dArray.txt");
FileInputStream fis = new FileInputStream(file);
int[][] array = new int[ROW][COL];
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
for (int i = 0; i < array.length; i++) {
String[] line = sc.nextLine().trim().split("," + " ");
for (int j = 0; j < line.length; j++) {
array[i][j] = Integer.parseInt(line[j]);
}
}
}
System.out.println("output:" + Arrays.deepToString(array));
}
}
and here are the input file's contents: img of txt files contents 3 rows and 3 columns
and the output:
output:[[1, 2, 3], [3, 4, 5], [5, 6, 7]]
I have been trying to figure it out a way to take the input of any txt file and transfer it into a 2D array, any input or help would be appreciated.