read Int Matrix from InputStream - Java java.lang

Java examples for java.lang:Math Matrix

Description

read Int Matrix from InputStream

Demo Code


//package com.java2s;

import java.io.*;
import java.util.*;

public class Main {
    public static int[][] readIntMatrix(InputStream stream)
            throws IOException {
        List<List<Integer>> listRep = new ArrayList<List<Integer>>();

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                stream));/* w w  w . ja v a2 s .  c o m*/
        while (reader.ready()) {
            String line = reader.readLine();
            String[] vals = line.trim().split("\\s+");

            List<Integer> row = new ArrayList<Integer>();
            for (String val : vals) {
                row.add(Integer.parseInt(val));
            }
            listRep.add(row);
        }
        reader.close();

        int rows = listRep.size();
        int[][] arrayRep = new int[listRep.size()][];
        for (int i = 0; i < rows; i++) {
            List<Integer> row = listRep.get(i);
            int cols = row.size();
            arrayRep[i] = new int[cols];
            for (int j = 0; j < cols; j++) {
                arrayRep[i][j] = row.get(j);
            }
        }

        return arrayRep;
    }
}

Related Tutorials