1  import java.util.ArrayList;
  2  
  3  /**
  4     Describes an invoice for a set of purchased products.
  5  */
  6  public class Invoice
  7  {  
  8     private Address billingAddress;
  9     private ArrayList<LineItem> items;
 10  
 11     /**
 12        Constructs an invoice.
 13        @param anAddress the billing address
 14     */
 15     public Invoice(Address anAddress)
 16     {  
 17        items = new ArrayList<LineItem>();
 18        billingAddress = anAddress;
 19     }
 20    
 21     /**
 22        Adds a charge for a product to this invoice.
 23        @param aProduct the product that the customer ordered
 24        @param quantity the quantity of the product
 25     */
 26     public void add(Product aProduct, int quantity)
 27     {  
 28        LineItem anItem = new LineItem(aProduct, quantity);
 29        items.add(anItem);
 30     }
 31  
 32     /**
 33        Formats the invoice.
 34        @return the formatted invoice
 35     */
 36     public String format()
 37     {  
 38        String r =  "                     I N V O I C E\n\n"
 39              + billingAddress.format()
 40              + String.format("\n\n%-30s%8s%5s%8s\n",
 41                 "Description", "Price", "Qty", "Total");
 42  
 43        for (LineItem item : items)
 44        {  
 45           r = r + item.format() + "\n";
 46        }
 47  
 48        r = r + String.format("\nAMOUNT DUE: $%8.2f", getAmountDue());
 49  
 50        return r;
 51     }
 52  
 53     /**
 54        Computes the total amount due.
 55        @return the amount due
 56     */
 57     public double getAmountDue()
 58     {  
 59        double amountDue = 0;
 60        for (LineItem item : items)
 61        {  
 62           amountDue = amountDue + item.getTotalPrice();
 63        }
 64        return amountDue;
 65     }
 66  }