Reputation: 173
I'm trying to sum numerical values from a getter method (drawing values from an ArrayList) using an iterator.
Function in question:
public void overallTotal()
{
Iterator<Customer> customers = model.getCustomerIterator();
while (customers.hasNext())
{
Customer customer = customers.next();
int sum = 0;
sum = customer.getTotalForAllOrders() + sum;
System.out.println(sum);
}
}
for an interface model
.
This is simply printing getTotalForAllOrders() for each customer. I need to (cumulatively) sum them.
Could someone show me how to do this, please?
Customer:
import java.util.ArrayList;
public class Customer
{
private String firstName;
private String lastName;
private String address;
private String phone;
private String email;
private ArrayList<Order> orders;
public Customer(String firstName, String lastName, String address, String phone, String email)
{
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.phone = phone;
this.email = email;
orders = new ArrayList<Order>();
}
public int getTotalForAllOrders()
{
int total = 0;
for (Order order : orders)
{
total += order.getTotal();
}
return total;
}
}
Order:
public class Order
{
private ArrayList<LineItem> lineItems;
public Order()
{
lineItems = new ArrayList<LineItem>();
}
public int getTotal()
{
int total = 0;
for (LineItem item : lineItems)
{
total += item.getSubTotal();
}
return total;
}
}
Iterator:
public Iterator<Customer> getCustomerIterator()
{
return customers.iterator();
}
Upvotes: 1
Views: 1592
Reputation: 340
If I understand your issue correctly, you just need to initialize sum outside of your while loop, you're just redeclaring the variable after the scope breaks.
Upvotes: 4