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??
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.