How to create a matrix 3x3 from a text file

446 Views Asked by At

I have to create a 3x3 matrix from a txt file and then get the determinant. I tried to do it with these numbers:

22 10 15
12 5 8
22 3 8

But when I run the program the matrix is:

22 10 15 
12 5 88 
22 3 8
1

There are 1 best solutions below

1
mswedr On

Umm.. not sure what exactly do you expect

    int [] matrix = new int [9];

    File file = newFile("filepath")

    try (BufferedReader br = new BufferedReader(new FileReader(file))) 
    {
        String line;
        int i=0;

        while ((line = br.readLine()) != null) 
        {
            String [] numbers=line.split(" ");

            for(int j=0;j<numbers.length;j++)
            {
                if(numbers[j].matches(("-?\\d+")))
                {
                   matrix[i] = Integer.parseInt(numbers[j]);
                   i++;
                }
            }
        }

        System.out.println("determinant: "+ Integer.toString(matrix[0]*matrix[4]*matrix[8] + matrix[1]*matrix[5]*matrix[6] + matrix[2]*matrix[3]*matrix[7]));
    } catch (IOException e) 
    {
        e.printStackTrace();
    }

Here is an example how can you calculate determinant