previous | start | next

File Purse.java

1 import java.io.BufferedReader;
2 import java.io.FileReader;
3 import java.io.IOException;
4
5 /**
6     A purse computes the total of a collection of coins.
7 */
8 public class Purse
9 {
10    /**
11        Constructs an empty purse.
12     */
13    public Purse()
14    {
15       total = 0;
16    }
17
18    /**
19        Read a file with coin descriptions and adds the coins
20        to the purse.
21       @param filename the name of the file
22     */
23    public void readFile(String filename)
24       throws IOException
25    {
26       BufferedReader in = null;
27       try
28       {  
29          in = new BufferedReader(new FileReader(filename));
30          read(in);
31       }
32       finally
33       {
34          if (in != null) in.close();
35       }
36    }
37
38    /**
39        Read a file with coin descriptions and adds the coins
40        to the purse.
41       @param in the buffered reader for reading the input
42     */
43    public void read(BufferedReader in) 
44       throws IOException
45    {  
46       boolean done = false;
47       while (!done)
48       {
49          Coin c = new Coin();
50          if (c.read(in))
51             add(c);
52          else
53             done = true;
54       }
55    }
56
57    /**
58        Add a coin to the purse.
59       @param aCoin the coin to add
60     */
61    public void add(Coin aCoin)
62    {
63       total = total + aCoin.getValue();
64    }
65
66    /**
67        Get the total value of the coins in the purse.
68       @return the sum of all coin values
69     */
70    public double getTotal()
71    {
72       return total;
73    }
74
75    private double total;
76 }
77


previous | start | next