java - How do you convert string arraylist to double using for loop to calculate? -
i'm given data.txt file , have calculate total amount using arraylist
my data.txt file contains:
32.14,235.1,341.4,134.41,335.3,132.1,34.1
so far have
public void processfile() throws ioexception { file file = new file("salesdata.txt"); scanner input = new scanner(file); arraylist<string> arr = new arraylist<string>(); string line = input.nextline(); stringtokenizer st = new stringtokenizer(line, ","); while (st.hasmoretokens()) { arr.add(st.nexttoken()); } setarraylistelement(arr); //calls setarraylistelement method }
and here setarraylistelement
method:
private void setarraylistelement(arraylist inarray) { (int = 0 ; < inarray.size() ; i++) { // need convert each string double , sum them } }
can help??
never utilize doubles monetary calculations (previous reply wrong) never refer concrete class. interface in case list arr = new arraylist();
to specific answer:
bigdecimal summed = bigdecimal.zero; (int = 0 ; < arr.size() ; i++) { final string value = arr.get(i); try{ bigdecimal bd = new bigdecimal(value); summed = summed.add(bd); } catch(numberformatexception nfe){ //todo: handle } }
...
java list parsing arraylist double
No comments:
Post a Comment