![](/img/trans.png)
[英]How to Convert a String ArrayList to a Double ArrayList and calculate the sum of values?
[英]How do you convert string arraylist to double using for loop to calculate?
我得到了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
}
}
我可以幫忙嗎?
針對您的具體答案:
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
}
}
...
您必須使用Double.valueOf()
:
Double.valueOf(string);
Double value = Double.parseDouble(yourString);
我向您發布了用於計算總量的方法,請不要忘記控制異常。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.