从txt读取矩阵并将其存储在java中的2D数组中

时间:2018-03-29 17:57:17

标签: java matrix

所以我尝试将txt文件中的矩阵放入变量中,但我使用的是一个名为value[][]的数组。

例如文件可以是:

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

value[2][1]的值为6.
请随意向我推荐另一种格式,例如,如果数字更有效,可以使用逗号分隔数字。

我将始终使用方形矩阵(2X2,3X3,4X4 ......),我需要从滤波器中获取行数(或列数),然后将其存储到另一个名为 nMatrix

我不确定如何读取文件,然后将正确的数字存储在数组的正确单元格中。

3 个答案:

答案 0 :(得分:1)

具有未定义矩阵长度的解决方案:

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();
}

答案 1 :(得分:0)

use a method like readFile(String theFileName)
{
     Scanner scan = new Scanner(theFileName);
     int[][] matrix = new int[someNumber][someNumber]
     try{
         for(int val = 0; val < matrix.length; val++)
          {
            for(int val2 = 0; val2< matrix[val].length; val++)
              {
                 matrix[val][val2] = scan.next();
              }
          }
        }
scan.close();
}

答案 2 :(得分:0)

所以诀窍是让你的文件正确读取,所以一定要确保你的路径正确。有几种方法可以访问文件系统上的文件,但我选择了完整路径选项。

此解决方案可为您以后提供灵活性。

public class ReadMatrix {

private static final String FILENAME = "/Users/username/Developer/Workspaces/java/SandboxPlayingAroundId/src/main/java/matrix.txt";

public static void main(String[] args) {
    BufferedReader bufferedReader = null;
    FileReader fileReader = null;
    Map<Integer, String[]> matrixMap = new HashMap<>();
    try {
        fileReader = new FileReader(FILENAME);
        bufferedReader = new BufferedReader(fileReader);
        String currentLine;
        int columnCounter = 0;

        while ((currentLine = bufferedReader.readLine()) != null) {
            String[] rowNumbers = currentLine.split(" ");
            matrixMap.put(columnCounter++, rowNumbers);
        }

        //print number of rows
        System.out.println(matrixMap.size());

        //print number of columns for nth row (2nd since our indexes are 0 based)
        int n = 1;
        System.out.println(matrixMap.get(n).length);

        //print element on nXm (1st since our indexes are 0 based
        int m = 0;
        System.out.println(matrixMap.get(n)[m]); //will print 4

    } catch (IOException ioEx) {
        ioEx.printStackTrace();
    } finally {
        try {
            if (bufferedReader != null)
                bufferedReader.close();
            if (fileReader != null)
                fileReader.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}}