如何将字符串arraylist转换为使用for循环来计算?

时间:2014-11-14 12:54:54

标签: java list parsing arraylist double

我已经给出了data.txt文件,并且必须使用ArrayList来计算总金额

我的data.txt文件包含:

32.14,235.1,341.4,134.41,335.3,132.1,34.1

到目前为止我已经

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

}

这是我的setArrayListElement方法:

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

我可以得到一些帮助吗?

4 个答案:

答案 0 :(得分:2)

  1. 永远不要使用双打进行货币计算(以前的答案也是错误的)
  2. 永远不要参考具体课程。在这种情况下,接口是List arr = new ArrayList();
  3. 您的具体答案:

    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
     }
    }
    

    ...

答案 1 :(得分:0)

您必须使用Double.valueOf()

Double.valueOf(string);

答案 2 :(得分:0)

Double value = Double.parseDouble(yourString);

答案 3 :(得分:0)

我发布了计算总金额的方法,不要忘记控制异常。

    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;
}