-2

我想将 matrix[i][j] 获取到我的 int[][] gettwodimensionalArray,我尝试了很多方法,但是当我进行测试时,我的 gettwodimensionaArray 仍然没有从 matrix[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;
}
4

1 回答 1

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];
于 2013-03-05T23:04:41.813 回答