java - Building two 2-D arrays from file data -
i'm tasked writing 2 matrices file (which have done), read data file perform various calculations. having difficulty rebuilding each matrix within method perform calculations. decided use arraylist of arraylist, in order 2-d matrix need. using bufferedreader, need loop through 1 matrix, adding elements 1 arraylist, second matrix. added titles above matrices act markers find matrix data want use. there better way it?
public void sum() throws ioexception { arraylist<arraylist<integer>> matrixarray = new arraylist<>(); while(br.read() != -1) { arraylist row = new arraylist(); //tried this, using 2 println spaces between matrices //but realized can't use readline way while(!br.readline().equals("\n\n")) { row.add(br.read()); } matrixarray.add(row); }
the file data of form:
matrix 1 b c d matrix 2 b c d
--update--from comment below
while(file.hasnext()) { if(file.hasnext("matrix one")){ //fill arraylist row data until \n while(file.hasnextint()) { row.add(file.nextint()); } matrixone.add(row); } else if(file.hasnext("matrix two")) { row.clear(); while(file.hasnextint()) { row.add(file.nextint()); } matrixtwo.add(row); } }
you should use java.util.scanner
class. easier use, , allows read line line.
once separate lines, can call string#split
method separate numbers using spaces.
this give array of string
s. can call integer.parseint
method retrieve int
string
, add arraylist
.
hope helps.