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.
ArrayListinstead for both rows and columns.for (int i = 0; i < array.length; i++)eachsc.nextLine()will give you the next row. Second: is to read all your file first and find your ROW value.1, 2, 3, 4would you be able to convert it todouble[]? When you solve this step you are almost there. Next information you need is amount of rows which you can obtain by reading your file once to count its lines which also represents amount of rows. Then you just need to iterate your file second time, convert each line to 1D array, and place that array in 2D array.