//[0
import java.util.*;


/**
 * A partial encapsulation of a weight in "English measure"
 * (i.e., pounds and ounces)
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 0.1
 */
public class Weight 
//]0
    implements Operand
//[0
{
    private int      value;

    /**
     * Default Constructor
     */
    public Weight()
    {
       this(0, 0);       
    }

    /**
     * Explicit Value Constructor
     *
     * @param pounds     The number of pounds (must be positive)
     * @param ounces     The number of ounces (must be positive)
     */
    public Weight(int pounds, int ounces)
    {
        value = Math.abs(ounces) + Math.abs(pounds) * 16;
    }

//]0

//[Increaseable

    /**
     * Increase this Weight by a given amount (required by Increaseable)
     *
     * @param other   The amount to change this Weight by
     */
    public void increaseBy(Increaseable otherWeight)
    {
        Weight  other;

        // This typecast is dangerous. We will talk about how
        // to elimninate the need for it later.
        other = (Weight)otherWeight;

        value += other.value;
    }
//]Increaseable


//[Initializeable
    /**
     * Initialize the attributes of this Weight from a String representation
     * (required by Initializeable).
     *
     * @param s   The String representation (delimited by commas)
     */
    public void fromString(String s)
    {
        int                    ounces, pounds;        
        String                 token;       
        StringTokenizer        st;

       
       st = new StringTokenizer(s, ",");       

       try
       {
          token  = st.nextToken();
          pounds = Integer.parseInt(token);
          
          token  = st.nextToken();
          ounces = Integer.parseInt(token);

          value = Math.abs(ounces) + Math.abs(pounds) * 16;
       }
       catch (NoSuchElementException nsee)
       {
          // Leave the value as it is
       }
       catch (NumberFormatException nfe)
       {
          // Leave the values as it is
       }
    }
//]Initializeable
//[0    

    /**
     * Get a String representation of this Weight
     *
     * @return  The String
     */ 
    public String toString()
    {
        int        ounces, pounds;
	String     s, poundString;

	s = new String();
        pounds = value / 16;
        ounces = value % 16;        

	poundString = " lbs. ";
	if (pounds == 1) poundString = " lb.  ";

	s += pounds + poundString + ounces + " oz.";
	return s;
    }
}
//]0
