如何在迭代器中对getter方法中的值求和?

时间:2015-02-18 16:16:41

标签: java oop iterator sum

我试图使用迭代器对getter方法中的数值求和(从ArrayList中绘制值)。

有问题的功能:

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);
    }
}

表示接口model

这只是为每个客户打印getTotalForAllOrders()。我需要(累积地)总结它们。

有人可以告诉我该怎么做吗?



客户:

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;
  }
}

订单:

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;
  }
}

迭代器:

public Iterator<Customer> getCustomerIterator()
{
    return customers.iterator();
}

1 个答案:

答案 0 :(得分:4)

如果我理解你的问题,你只需要在你的while循环之外初始化sum,你只需在范围破坏后重新声明变量。