In java how would I read a text file with an unknown number of lines and store each line in a separate array.
public readFile() { try { FileInputStream fin = new FileInputStream(file); //DataInputStream dis = new DataInputStream(fin); //needed for some data BufferedReader br = new BufferedReader(new InputStreamReader(fin)); //needed to read line by line. while(br.readLine != null) { //add to array here, increment what's needed etc. }
I know I have to use that to read the text line by line but the problem I am having is assigning each line to a separate array so at the end I have an array for each line in the file and I can treat the arrays like rows and the same index in each array like columns. I also want to do it as though I don't know how many lines there are in the text but I do know the number of rows will be the same as the number of columns.
while(br.readLine != null) { //add to array here, increment what's needed etc. }
so you could say String[] files as a global; int lines = 0; while(br.readLine != null) { lines++; //add to array here, increment what's needed etc. files = new String[lines]; files[lines-1] = br.readLine(); }
Won't that just store each line in as an element in the array files? I want to create an array of arrays with each line stored as a separate array, and I want to split the lines up like
so yo wan to make many 1 element arrays? Why...?
I figured it out, well I looked up a few different things and put them together. Not single element arrays I used split for each line. I used a 2D array which stored the array for each line. It was a magic squares problem and I needed to check that the columns and rows all added up to the same number so from there it was just a nested for loop another 2D array and an if statement.
sorry 1D array the second time to store all the row and column sums and then iterate through and check there values were all the same.
Join our real-time social learning platform and learn together with your friends!