/Users/lyon/j4p/src/xml/cart/Cart.java

1    package xml.cart; 
2     
3    import xml.Product; 
4     
5    import java.util.Vector; 
6     
7    public class Cart { 
8        private Vector goodies = new Vector(); 
9     
10       public void addProduct(Product p) { 
11           if (p == null) return; 
12           goodies.addElement(p); 
13       } 
14    
15       public void removeProduct(Product p) { 
16           goodies.removeElement(p); 
17       } 
18    
19       public Product[] getProducts() { 
20           Product[] pa = new Product[goodies.size()]; 
21           goodies.copyInto(pa); 
22           return pa; 
23       } 
24    
25       public String toString() { 
26           Product p[] = getProducts(); 
27           String s = "cart:\n"; 
28           for (int i = 0; i < p.length; i++) 
29               s = s + p[i].toString() + '\n'; 
30           s = s + "total:" + getTotal(); 
31           return s; 
32       } 
33    
34       public float getTotal() { 
35           Product p[] = getProducts(); 
36           float t = 0; 
37           for (int i = 0; i < p.length; i++) 
38               t = t + p[i].getPrice(); 
39           return t; 
40       } 
41    
42       public static void main(String args[]) { 
43           Product p = new Product( 
44                   "Image Processing in Java", 25f, 12); 
45           Product p2 = new Product( 
46                   "Java for Programmers", 35f, 11); 
47           Cart c = initializeCart(p, p2); 
48           System.out.println(c); 
49           // Oh, I don't need two books 
50           // on image processing... lets get rid of one. 
51           c.removeProduct(p); 
52           System.out.println(c); 
53       } 
54    
55       private static Cart initializeCart(Product p, 
56                                          Product p2) { 
57           Cart c = new Cart(); 
58           c.addProduct(p); 
59           c.addProduct(p); 
60           c.addProduct(p2); 
61           return c; 
62       } 
63    
64    
65   }