I'm trying to write a method to take a multiline csv file and return the contents of that file as an arraylist. My problem is, when I print the array lines, they appear to only have the contents of the very last line of the file. I'm suspecting it might be something about FileReader or BufferedReader that I don't know. Anyhow, here's the code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public int[][] readCSV(String pFilename) throws NumberFormatException, IOException {
int[][] arr = new int[19][19];
BufferedReader br = new BufferedReader(new FileReader(pFilename));
String line = " ";
String [] temp;
while ((line = br.readLine())!= null){
temp = line.split(","); //split spaces
for(int i = 0; i<arr.length; i++) {
for (int j = 0; j<arr.length; j++) {
arr[i][j] = Integer.parseInt(temp[j]);
}
}
}
printArray(arr);
}
public static void printArray (int[][] arr) {
for (int i =0; i <arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j]);
}
System.out.println("");
}
}
}
input
1,1,0,0,1,1,1,1,1,0,0,1,1,0,0,0,1,1,1
1,0,0,1,1,1,1,0,1,1,1,0,1,1,1,0,1,0,1
1,0,0,1,0,0,1,1,1,1,1,1,1,1,1,0,1,1,0
1,1,0,1,0,1,1,0,1,0,1,0,0,1,1,1,0,1,1
1,1,0,1,1,1,0,1,0,1,0,0,1,1,1,0,1,0,0
1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1
1,1,1,0,0,0,1,1,1,0,1,1,1,1,1,0,1,0,1
0,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,1,1,1
1,1,1,1,1,0,0,1,1,1,1,0,1,0,0,1,1,0,1
1,1,1,0,1,1,1,0,1,0,1,1,1,1,0,1,1,1,1
0,0,1,1,1,1,1,0,0,1,0,1,1,0,1,1,0,1,0
1,0,0,0,1,1,1,1,1,1,1,1,0,1,1,1,1,0,0
1,1,1,1,1,1,1,1,1,1,0,1,1,1,0,1,1,1,1
1,0,1,0,1,1,1,1,1,1,0,1,1,1,1,1,0,1,1
1,1,1,0,1,1,0,1,1,0,1,1,1,0,1,1,0,1,0
1,0,0,1,1,1,0,1,1,1,0,1,1,1,0,0,1,1,0
1,1,1,0,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1
0,1,0,0,1,1,0,1,0,1,1,1,0,1,1,0,1,1,1
1,1,0,0,1,1,1,1,1,1,0,0,1,1,0,1,0,1,0
0,1,1,1,0,0,1,1,1,1,1,1,0,1,0,1,1,1,0
print output
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
That is because you are rewriting the whole array for every input line. So only the last one "survives".
You want to keep the
iindex tied to the current line number (just do ai++for every iteration of the outer loop, don't nest another for loop).