我正在尝试将多个矩阵存储到一个数组中(每个矩阵具有相同的维度),我认为我的逻辑是正确的,但代码运行不正确。我在文本文件中的输入如下所示(例如):
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0000000000
00 00
0000000000
000 00 000
00 000 00
000 00 000
所以在这个例子中,每个''都算作一个我转换为-1的字符,每个新行都是一个新的矩阵。我已经找到了行数和列数,我告诉我将在文本文件中看到的对数。所以我想制作一个像这样的数组
pairs[number of pairs][rows][columns].
所以在这个例子中,它将是对[3] [3] [10]所以3个样本每个都有3×10矩阵。我的代码是:
int lines = 0;
BufferedReader brr = new BufferedReader(new FileReader(inFile));
//now read and store in 2D matrix
int[][][] samples = new int[pairs][rows][cols];
while((lines = brr.readLine()) != null) {
if (line > 2) { // to skip first 3 lines of text file
for (int i = 0; i < pairs; i++) {
for (int j = 0; j < rows; j++) {
for (int k = 0; k < lines.length(); k++) {
//Cycle through each character in line
if (lines.charAt(k) == 'O' || lines.charAt(k) == '0') {
samples[i][j][k] = 1; //store in the matrix as a 1
}
else if (lines.charAt(k) == ' ') {
samples[i][j][k] = -1;
//store spaces as -1
}
}
}
}
}
line++;
}
br.close();
抱歉,我的意思是编写我的输出,但是现在它正在分配变量,但它会继续重复。我的意思是,一旦完成第三次输入,for循环再次重复。换句话说,一旦i = 2(在这个例子中),并且j = 2,k = 2,它然后重复并且由于某种原因一切从头开始再次通过。
答案 0 :(得分:-1)
我弄清楚发生了什么,我没有考虑每对之间的新线。所以工作代码是:
BufferedReader brr = new BufferedReader(new FileReader(inFile));
//now read and store in 2D matrix
int[][][] samples = new int[inVals.get(1)][rows][cols];
int index = 0;
while((lines = brr.readLine()) != null) {
if (curr > 2) {
if (lines.equals("")) {
index++; //increment the pair we're on
}
for (int j = 0; j < rows; j++) {
for (int k = 0; k < lines.length(); k++) {
//Cycle through each character in line
if (lines.charAt(k) == 'O' || lines.charAt(k) == '0') {
samples[index][j][k] = 1;
}
else if (lines.charAt(k) == ' ') {
samples[index][j][k] = -1;
}
}
}
}
curr++; //for the current line we're reading
}
brr.close(); //close buffered reader