[英]How do you convert string arraylist to double using for loop to calculate?
I'm given the data.txt file and have to calculate the total amount using ArrayList
我得到了data.txt文件,必须使用
ArrayList
计算总数
my data.txt file contains: 我的data.txt文件包含:
32.14,235.1,341.4,134.41,335.3,132.1,34.1 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: 这是我的
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
}
}
Can I get some help?? 我可以帮忙吗?
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
}
}
... ...
您必须使用Double.valueOf()
:
Double.valueOf(string);
Double value = Double.parseDouble(yourString);
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.