使用文件中的数据填充2D数组

时间:2014-10-24 09:14:07

标签: java variable-assignment multidimensional-array

我的文件包含一些数据

  

[[22,19,23],[19,10,16],[12,15,8]]

我想读取它,并将它们填充到2D数组中。

以下是我的尝试:

private static void eFile() {
    String kF;

    System.out.println("K:");
    kF = mainInput.nextLine();

    if (kf.equalsIgnoreCase("kf.txt")) {
        BufferedReader br = null;

        try {
            String line = null;

            br = new BufferedReader(new FileReader("kf.txt"));
            int[][] matrix = null;
            String[] keys = null;
            int key = 0;

            if ((line = br.readLine()) != null) {
                keys = line.replace("[", "").replace("]", "")
                        .replace(",", "").split(" ");
                matrix = new int[(int) Math.sqrt(keys.length)][(int) Math
                        .sqrt(keys.length)];

                System.out.println("File elements: ");
                for (int i = 0; i < keys.length; i++) {
                    key = Integer.parseInt(keys[i]);
                    System.out.println(key); // Able to print normally.
                    for (int j = 0; j < matrix.length; j++) {
                        for (int k = 0; k < matrix.length; k++) {
                            matrix[j][k] = key; // Problematic line
                        }
                    }
                }
            }

            System.out.println("Matrix elements: ");
            for (int j = 0; j < matrix.length; j++) {
                for (int k = 0; k < matrix.length; k++) {
                    System.out.println(matrix[j][k]); // All same numbers
                }
            }
        } catch (Exception e) {

        }
    } else {
        System.out
                .println("Please rename your file to kf.txt");
    }
}

但输出结果不然

  

文件元素:   22   19   23   19   10   16   12   15   8   矩阵元素:   8   8   8   8   8   8   8   8   8

原定于:

  

文件元素:   22   19   23   19   10   16   12   15   8   矩阵元素:   22   19   23   19   10   16   12   15   8

1 个答案:

答案 0 :(得分:0)

此处修改如下

int keyIndex = 0;
for (int j = 0; j < matrix.length; j++) {
    for (int k = 0; k < matrix.length; k++) {
        matrix[j][k] = Integer.parseInt(keys[keyIndex]); // Problematic line
             keyIndex = keyIndex + 1;
    }
}

并打印matrix使用Arrays.deepToString(),如

Arrays.deepToString(matrix)