CoinPurse.java

Download CoinPurse.java

Show with line numbers

// Demo of enums.  The enum Coin shows U.S. coins.
// These are declared in the correct order, so the
// ordinal value of any coin can be compared with another.
//
// Here we create a List CoinPurse and add to it all the coins
// listed on the command line.  Notice the static parseCoin
// method to convert a String to a Coin.
//
// A more complete CoinPurse class would keep track of the number
// of each type of coin in the purse.
//
// Written 2/2009 by Wayne Pollock, Tampa Florida USA

import java.util.*;
import static java.lang.System.out;

enum Coin {

   PENNY( 1 ), NICKEL( 5 ), DIME( 10 ), QUARTER( 25 ),
   HALF_DOLLAR( 50 );

   private final int value;

   private Coin ( int value )  { this.value = value; }

   public int getValue() { return this.value; }

   public static Coin parseCoin ( String coin ) {
      if (coin.equalsIgnoreCase("PENNY") )        return PENNY;
      else if (coin.equalsIgnoreCase("NICKEL") )  return NICKEL;
      else if (coin.equalsIgnoreCase("DIME") )    return DIME;
      else if (coin.equalsIgnoreCase("QUARTER") ) return QUARTER;
      else if (coin.equalsIgnoreCase("HALF_DOLLAR") ) return HALF_DOLLAR;
      else return null;
   }
}

class CoinPurse
{
   public static void main ( String [] args ) {
      List<Coin> coinPurse = new ArrayList<Coin>();

      // Add some coins to the purse:
      for ( String coinName: args )
      {  Coin coin = Coin.parseCoin( coinName );
         if ( coin == null )
            out.println( "*** \"" + coinName
            + "\" is not legal tender!\n" );
         else
            coinPurse.add( coin );
      }

      int value = calcTotal( coinPurse );
      int dollars = value / 100;
      int cents   = value % 100;
      out.println( "Value of coins in purse is $"

         + dollars + "." + cents + "." );
   }

   public static int calcTotal ( List<Coin> purse ) {
      int total = 0;
      for ( Coin coin : purse )
         total += coin.getValue();
      return total;
   }
}