1 |
import java.util.ArrayList; |
2 |
|
3 |
/** |
4 |
A purse holds a collection of coins. |
5 |
*/ |
6 |
public class Purse |
7 |
{ |
8 |
/** |
9 |
Constructs an empty purse. |
10 |
*/ |
11 |
public Purse() |
12 |
{ |
13 |
coins = new ArrayList(); |
14 |
} |
15 |
|
16 |
/** |
17 |
Add a coin to the purse. |
18 |
@param aCoin the coin to add |
19 |
*/ |
20 |
public void add(Coin aCoin) |
21 |
{ |
22 |
coins.add(aCoin); |
23 |
} |
24 |
|
25 |
/** |
26 |
Get the total value of the coins in the purse. |
27 |
@return the sum of all coin values |
28 |
*/ |
29 |
public double getTotal() |
30 |
{ |
31 |
double total = 0; |
32 |
for (int i = 0; i < coins.size(); i++) |
33 |
{ |
34 |
Coin aCoin = (Coin)coins.get(i); |
35 |
total = total + aCoin.getValue(); |
36 |
} |
37 |
return total; |
38 |
} |
39 |
|
40 |
/** |
41 |
Counts the number of coins in the purse |
42 |
@return the number of coins |
43 |
*/ |
44 |
public int count() |
45 |
{ |
46 |
return coins.size(); |
47 |
} |
48 |
|
49 |
/** |
50 |
Tests if the purse has a coin that matches |
51 |
a given coin. |
52 |
@param aCoin the coin to match |
53 |
@return true if there is a coin equal to aCoin |
54 |
*/ |
55 |
public boolean find(Coin aCoin) |
56 |
{ |
57 |
for (int i = 0; i < coins.size(); i++) |
58 |
{ |
59 |
Coin c = (Coin)coins.get(i); |
60 |
if (c.equals(aCoin)) return true; // found a match |
61 |
} |
62 |
return false; // no match in the entire array list |
63 |
} |
64 |
|
65 |
/** |
66 |
Counts the number of coins in the purse that match |
67 |
a given coin. |
68 |
@param aCoin the coin to match |
69 |
@return the number of coins equal to aCoin |
70 |
*/ |
71 |
public int count(Coin aCoin) |
72 |
{ |
73 |
int matches = 0; |
74 |
for (int i = 0; i < coins.size(); i++) |
75 |
{ |
76 |
Coin c = (Coin)coins.get(i); |
77 |
if (c.equals(aCoin)) matches++; // found a match |
78 |
} |
79 |
return matches; |
80 |
} |
81 |
|
82 |
/** |
83 |
Finds the coin with the largest value. |
84 |
(Precondition: The purse is not empty) |
85 |
@return a coin with maximum value in this purse |
86 |
*/ |
87 |
Coin getMaximum() |
88 |
{ |
89 |
Coin max = (Coin)coins.get(0); |
90 |
for (int i = 1; i < coins.size(); i++) |
91 |
{ |
92 |
Coin c = (Coin)coins.get(i); |
93 |
if (c.getValue() > max.getValue()) |
94 |
max = c; |
95 |
} |
96 |
return max; |
97 |
} |
98 |
|
99 |
private ArrayList coins; |
100 |
} |
101 |
|