java - Creating an ArrayList from data in a text file -
i trying write program uses 2 classes find total $ amount text file of retail transactions. first class must read file, , second class must perform calculations. problem having in first class, arraylist seems price of last item in file. here input (which in text file):
$69.99 3 shoes
$79.99 1 pants
$17.99 1 belt
and here first class:
class readinputfile { static arraylist<double> pricearray = new arraylist<>(); static arraylist<double> quantityarray = new arraylist<>(); static string pricesubstring = new string(); static string quantitysubstring = new string(); public void gatherdata () { string s = "c:\\filepath"; try { filereader inputfile = new filereader(s); bufferedreader bufferreader = new bufferedreader(inputfile); string line; string substring = " "; while ((line = bufferreader.readline()) != null) substring = line.substring(1, line.lastindexof(" ") + 1); pricesubstring = substring.substring(0,substring.indexof(" ")); quantitysubstring = substring.substring(substring.indexof(" ") + 1 , substring.lastindexof(" ") ); double price = double.parsedouble(pricesubstring); double quantity = double.parsedouble(quantitysubstring); pricearray.add(price); quantityarray.add(quantity); system.out.println(pricearray); } catch (ioexception e) { e.printstacktrace(); } }
the output , value of pricearray [17.99], desired output [69.99,79.99,17.99].
not sure problem is, in advance help!
basically have is:
while ((line = bufferreader.readline()) != null) { substring = line.substring(1, line.lastindexof(" ") + 1); } pricesubstring = substring.substring(0,substring.indexof(" ")); quantitysubstring = substring.substring(substring.indexof(" ") + 1 , substring.lastindexof(" ") ); double price = double.parsedouble(pricesubstring); double quantity = double.parsedouble(quantitysubstring); pricearray.add(price); quantityarray.add(quantity); system.out.println(pricearray);
so doing creating substring
of line read, reading next line, basically, substring
of last processed remaining code.
wrap code in {...}
want executed on each iteration of loop
for example...
while ((line = bufferreader.readline()) != null) { substring = line.substring(1, line.lastindexof(" ") + 1); pricesubstring = substring.substring(0,substring.indexof(" ")); quantitysubstring = substring.substring(substring.indexof(" ") + 1 , substring.lastindexof(" ") ); double price = double.parsedouble(pricesubstring); double quantity = double.parsedouble(quantitysubstring); pricearray.add(price); quantityarray.add(quantity); system.out.println(pricearray); }
this execute code within {...}
block each line of file
Comments
Post a Comment