【发布时间】:2017-02-09 07:23:08
【问题描述】:
我有这个函数,它假设打开一个文件并读取第一个元素[第一行][第一列],将它存储在一个 3D 数组中[文件索引][行][列],然后打开下一个文件并执行相同的过程。此操作应一直运行,直到所有文件中的所有行和列都存储在 3D 数组中。 我的问题是,这个函数完成了这项工作,但它只读取每个文件的第一行(行)并停在那里!! 任何专家都可以帮助我弄清楚我的功能发生了什么吗?我已经使用 java 大约两个月了:/
public static double[][][] fetch_data(int start, int end, int column) throws IOException{
// start and end are for files start and end index.
int length = file_length(start); // since all files have the same length. The file_length() function just determine the length.
data = new double [number_of_files][length][number_of_columns];
int sum = 0;
for (int i = 0; i < length; i++){
for (int index = start; index < end; index++){
Scanner scan = new Scanner (new BufferedReader(new FileReader(file_call(index)))); // file_call() is a function that lookup the file dir.
scan.nextLine();
String scanedData = scan.nextLine();
String [] array = scanedData.split(",");
data[index][i][colum] = Double.parseDouble(array[index]);
sum += data[index][i][colum];
System.out.println(" element " + data[index][i][column]); // just to test the loop
}
}
return data;
}
数据文件如下所示: 文件(1):
A, B, C, D
1, 2, 3, 4
13, 2, 3, 4
1, 2, 3, 4
...
文件(2):
A, B, C, D
5, 6, 7, 8
55, 6, 7, 8
5, 6, 7, 8
...
文件(3):
A, B, C, D
9, 10, 11, 12
9, 10, 11, 12
91, 10, 11, 12
...
预期的输出(我们忽略了上面代码中的第一行“A,B C,D”):
1+5+9, 2+6+10, ...
13+55+9, 2+6+10, ...
1+5+91, 2+6+10, ...
...
我希望找到一个java专家,他可以教我如何让我for循环遍历每个文件的所有行,例如读取所有文件中的第一行并再次返回并读取所有文件中的第二行等等。
非常感谢你们的帮助。
最好的
【问题讨论】:
-
我建议你使用调试器来单步调试你的代码,看看它在做什么。
-
您还应该关闭计算机并准备一张纸和铅笔。用文字写出解决问题的步骤。
-
谢谢大家,我做了调试,结果发现它只读取第一行并停止。
-
@Code-Apprentice,我有,我的房间里实际上有一块大白板,我在上面做所有的事情。
-
我建议你阅读一下
if的作用。