CoinPurse.java

Download CoinPurse.java

 1: // Demo of enums.  The enum Coin defines a type to represent all
 2: // U.S. coins.  These are declared in the correct order, so the
 3: // ordinal value of any coin can be compared with another.
 4: //
 5: // Here we create a List CoinPurse and add to it all the coins
 6: // listed on the command line.  The the value of the coins in
 7: // the purse are totaled and printed.  Note the use of the
 8: // implicit enum methods "values()" (returns an array of the
 9: // values of the enum type, in the order they were declared) and
10: // "valueOf(String)" (returns the enum constant with the specified
11: // name; throws an exception if no such constant).
12: // A more complete CoinPurse class would keep track of the number
13: // of each type of coin in the purse.
14: //
15: // Additional Java features demonstrated here include static import,
16: // use of collections with generics, and the "enhanced" for loop
17: // ("for-each" loop).
18: //
19: // Written 1/2010 by Wayne Pollock, Tampa Florida USA
20: 
21: import java.util.*;
22: import static java.lang.System.out;
23: 
24: enum Coin {
25: 
26:    PENNY( 1 ), NICKEL( 5 ), DIME( 10 ), QUARTER( 25 ),
27:    HALF_DOLLAR( 50 ), DOLLAR( 100 );
28: 
29:    private final int value;
30: 
31:    private Coin ( int value )  { this.value = value; }
32: 
33:    public int getValue() { return this.value; }
34: }
35: 
36: class CoinPurse
37: {
38:    public static void main ( String [] args ) {
39:       List<Coin> coinPurse = new ArrayList<Coin>();
40: 
41:       // Add some coins to the purse:
42:       for ( String coinName: args )
43:       {  try {
44:             Coin coin = Coin.valueOf( coinName.toUpperCase() );
45:             coinPurse.add( coin );
46:          } catch (IllegalArgumentException e) {
47:             if ( coinName.equalsIgnoreCase("help") ) {
48:                out.println( "Enter the names of some coins.  Legal names "
49:                  + "(case-insensitive) are:" );
50:                out.println( Arrays.toString( Coin.values() ) );
51:                System.exit( 0 );
52:             } else {
53:                out.println( "*** \"" + coinName
54:                + "\" is not legal tender!\n" );
55:             }
56:          }
57:       }
58: 
59:       int value = calcTotal( coinPurse );
60:       int dollars = value / 100;
61:       int cents   = value % 100;
62:       out.printf( "Value of coins in purse is $%01d.%02d.", dollars, cents );
63:    }
64: 
65:    public static int calcTotal ( List<Coin> purse ) {
66:       int total = 0;
67:       for ( Coin coin : purse )
68:          total += coin.getValue();
69:       return total;
70:    }
71: }