【发布时间】: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