简体   繁体   中英

Read a matrix from a txt file

I have a txt file that has a list of matrices on it. For ex:

[6]

5 3        
6 2

7 8 -1     
4 3 1      
-2 0 3    

and I need to read through this txt file and determine the determinant of each matrix and then output the matrix and its determinant to an output txt file. I am stuck with getting each matrix to be read and run through my determinate class and then outputted to the output txt file. How do I get each matrix separately and a matrix so that I can run it through my code?

This is what I have so far, but it just outputs each line to the output file and does not get each matrix as a matrix so I can find its determinant.

    FileReader fileReader = new FileReader (inputFilePath);                                   
    FileWriter fileWriter = new FileWriter (outputFilePath);                                             
    BR = new BufferedReader(fileReader);                                                                           
    try {                                                                                          
        String line = BR.readLine();                                                                            
        while (line != null) {                                                                           
            fileWriter.write(line + '\n');                                                                                             
            fileWriter.write("determinant= " + '\n');                                                                                                           
            line = BR.readLine();                                                                                              
        } 
        BR.close();                                                                                          
    } catch (IOException e) {                                                                                              
        e.printStackTrace();                                                                                  
    }

Any help would be appreciated!

Assuming the matrices are made of integer values, you can read all lines and then for each line split by the whitespace and return as an array.

       List<String> lines = Files.readAllLines(Paths.get(inputFilePath));

       List<int[]> listOfMatrices = lines.stream()
                .filter(line -> !line.isEmpty())
                .map(line -> Arrays.stream(line.split(" "))
                        .mapToInt(Integer::parseInt)
                        .collect(Collectors.toList())
                .collect(Collectors.toList());

Output

[5, 3]
[6, 2]
[7, 8, -1]
[4, 3, 1]
[-2, 0, 3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM