Read a text file to create a 2D Array in Java

Tags: , ,



I have a text file with first line will be the size of the board and the remaining values will be the values of p row by row. All values are separated by whitespace. For example:

5
2 5 10 3 5
4 6 9 12 3
11 5 9 7 7
7 2 4 8 19
2 6 8 10 1

How can I read the file and store them in a 2D Array?

Answer

Ok, I’m assuming that the first number defines the width and height, so that it will be square board.

Scanner in = new Scanner(new File("filename.in"));
int N = in.nextInt();
int[][] arr = new int[N][N];

for(int r=0; r<arr.length; r++) {
    for(int c=0; c<arr[r].length; c++) {
        arr[r][c]=in.nextInt();
    }
}


Source: stackoverflow