D
D
Denis Kuznetsov2019-02-28 11:55:55
Java
Denis Kuznetsov, 2019-02-28 11:55:55

How to read matrix from file?

How to read a matrix with different elements (positive and negative)
from a file, the file contains a number (the dimension of a square matrix) and the matrix itself, and I tried to read it bit by bit into a two-dimensional array, but the problem was that the negative elements ceased to be such (that is, it was read only number without sign)

private static int currentIndex = -1;
    
    //String to matrix numbers
    private static Integer next(String numbers[]) {
        ++currentIndex;
        while (currentIndex < numbers.length
                && numbers[currentIndex].equals(""))
            ++currentIndex;
        return currentIndex < numbers.length ?
                Integer.parseInt(numbers[currentIndex]) :
                null;
    }

    public static void main(String args[]) throws IOException {
        FileInputStream in = new FileInputStream("getMatrix.txt");
        byte[] str = new byte[in.available()];
        in.read(str);
        String text = new String(str);

        String[] numbers = text.split("\\D");
        int i, j;
        int n = next(numbers);
        int[][] matr = new int[n][n];

        for (i = 0; i < n; ++i) {
            for (j = 0; j < n; ++j) {
                matr[i][j] = next(numbers);
            }
        }
        for (i = 0; i < n; ++i, System.out.println()) {
            for (j = 0; j < n; ++j) {
                System.out.print(matr[i][j] + " ");
            }
        }
    }

PS : Matrix elements may not be integer

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Osipov, 2019-03-01
@DennisKingsman

Something like this
Dimension, I think, parse it yourself, if necessary

BufferedReader br = new BufferedReader(new FileReader("matrix.txt"));

    List<String> lines = new ArrayList<>();
    while (br.ready()) {
      lines.add(br.readLine());
    }
    int matrixWidth = lines.get(0).split(" ").length;
    int matrixHeight = lines.size();

    Double[][] matrix = new Double[matrixHeight][matrixWidth];

    for (int i = 0; i < matrixHeight; i++) {
      for (int j = 0; j < matrixWidth; j++) {
        String[] line = lines.get(i).split(" ");
        matrix[i][j] = Double.parseDouble(line[j]);
      }
    }

    for (int i = 0; i < matrixHeight; i++) {
      System.out.println(Arrays.toString(matrix[i]));
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question