0

I'm given the data.txt file and have to calculate the 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 I 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 is my setArrayListElement method:

private void setArrayListElement(ArrayList inArray)
{                
    for (int i = 0 ; i < inArray.size() ; i++)
    {
         // need to convert each string into double and sum them up
    }
}

Can I get some help??

2
  • 3
    Use Double.parseDouble() to convert a String to a double. Commented Nov 14, 2014 at 12:56
  • Please add parameter to you Arraylist in the parameter private void setArrayListElement(ArrayList<String> inArray) Commented Nov 14, 2014 at 13:04

4 Answers 4

2
  1. Never use doubles for monetary calculations (Previous answer is also wrong)
  2. Never refer to a concrete class. The interface in this case is List arr = new ArrayList();

To your specific answer:

BigDecimal summed = BigDecimal.ZERO;

for (int i = 0 ; i < arr.size() ; i++) {
 final String value  = arr.get(i);
 try{
  BigDecimal bd = new BigDecimal(value);
  summed = summed.add(bd);
 } catch(NumberFormatException nfe){
       //TODO: Handle
 }
}

...

Sign up to request clarification or add additional context in comments.

2 Comments

Any reason for using explicit indexed access rather than for(String value : arr)?
Correct, not needed an index loop in this case.
0

You have to use Double.valueOf():

Double.valueOf(string);

Comments

0
Double value = Double.parseDouble(yourString);

Comments

0

I post you the method to calculate the total amount, dont forget to control exceptions.

    private Double setArrayListElement(ArrayList inArray) throws NumberFormatException
{   
    Double amount=0;    
    for (int i = 0 ; i < inArray.size() ; i++)
    {
       amount= amount+Double.valueOf(inArray.get(i));
    }
    return amount;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.