如何获得int [] [] dimensionArray?

时间:2013-03-05 22:47:41

标签: java

我想得到矩阵[i] [j]到我的int [] [] gettwodimensionalArray,我尝试了很多方法,但是当我做测试时,我的gettwodimensionaArray仍然没有存储在矩阵[i] [j]中。请帮帮我,谢谢。

这是我的代码看起来像。

    public int[][] gettwodimensionalArray(String file_name) {
    File file = new File(file_name);
    ArrayList<int[]> rows = new ArrayList<int[]>();
    try {
        Scanner scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            String[] s = line.split("\\s+");
            int[] row = new int[s.length];
            for (int i = 0; i < s.length; i++) {
                row[i] = Integer.parseInt(s[i]);
            }
            rows.add(row);
            System.out.println(line);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    int numbOfRow = rows.size();
    // find number of columns by gettting the lenght of one of the rows row

    int keepTrackSizeFirstRow;
    for (int i = 0; i < numbOfRow; i++) {
        if (i == 0) {
            keepTrackSizeFirstRow = rows.get(0).length;

        }
        // compare current row i's array length, to keetracksizefirstrow
    }

    int[][] matrix = new int[numbOfRow][rows.get(0).length];
    // System.out.println(matrix);

    for (int i = 0; i < numbOfRow; i++) {
        // i = row

        for (int j = 0; j < rows.get(i).length; j++) {
            // j = col

            matrix[i][j] = rows.get(i)[j];
            System.out.print(matrix[i][j]);

        }
    }
    return matrix;
}

1 个答案:

答案 0 :(得分:0)

不确定你要做什么。如果您希望输入的每一行都适合数组,您可以使用可变大小声明数组,如下所示:

int[][] matrix = new int[numbOfRow][];
for (int i = 0; i < matrix.length; i++) {
    matrix[i] = new int[rows.get(i).length];
}

如果您希望所有行具有相同的长度,您应该找到输入的最大长度,如下所示:

int maxlength = 0;
for (int i = 0; i < rows.size(); i++) {
    maxlength = (rows.get(i).length > maxlength) ? rows.get(i).length : maxlength;
}
int[][] matrix = new int[numbOfRow][maxlength];