我已经给出了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
}
}
我可以得到一些帮助吗?
答案 0 :(得分:2)
您的具体答案:
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;
}