javamatrix

Read a matrix from a txt and store it in a 2D array in java


So I'm trying put a matrix from a txt file into a variable and I have though about using an Array called value[][].

for example the file could be:

0 2 8 1
4 1 6 2
2 1 4 7
2 4 7 9

And the value of value[2][1] would be 6.

How would I go about reading the file and filling the array with the numbers in the correct positions?


Solution

  • Solution with undefined matrix length:

    int[][] value = null;
    //you can use relative path or full path here
    File file = new File("file-name.txt");
    try {
        Scanner sizeScanner = new Scanner(file);
        String[] temp = sizeScanner.nextLine().split(" ");
        sizeScanner.close();
        int nMatrix = temp.length;
    
        Scanner scanner = new Scanner(file);
        value = new int[nMatrix][nMatrix];
        for (int i = 0; i < nMatrix; i++) {
            String[] numbers = scanner.nextLine().split(" ");
            for (int j = 0; j < nMatrix; j++) {
                value[i][j] = Integer.parseInt(numbers[j]);
            }
        }
        scanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }