【问题标题】:Populate 2DArray with data from file使用文件中的数据填充 2DArray
【发布时间】:2014-10-24 09:14:07
【问题描述】:

我的文件包含一些数据

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

我想从中读取,并将它们填充到二维数组中。

以下是我的尝试:

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

【问题讨论】:

  • 为什么要设置matrix[j][k] = key;
  • 因为我想填充数组? o.o

标签: java variable-assignment multidimensional-array


【解决方案1】:

这里修改如下

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() like

Arrays.deepToString(matrix)

【讨论】:

  • 非常感谢!被困了几个小时:S
猜你喜欢
  • 2015-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多