Data Structures, Algorithms, & Applications in Java
Chapter 1, Exercise 15

We have at least two options on how to proceed. The new methods can be placed directly into the class applications.CurrencyAsLong or we can place the new methods in a class applications.EnhancedCurrencyAsLong which is derived from applications.CurrencyAsLong. We shall take the former approach. The latter approach becomes quite cumbersome, because we have not provided the class applications.CurrencyAsLong with an accessor method which returns the value of amount. The code for the new methods is given below.


// new instance methods
public void input()
{
   // define the input stream to be the standard input stream
   MyInputStream keyboard = new MyInputStream();

   // input the amount as a double
   System.out.println("Enter the currency amount as a real number");
   double theValue = keyboard.readDouble();

   // set the value
   setValue(theValue);
}

/** return this - x */
public CurrencyAsLong subtract(CurrencyAsLong x)
   {return new CurrencyAsLong(amount - x.amount);}

/** return x percent of this */
public CurrencyAsLong percent(float x)
   {return new CurrencyAsLong((long) (amount * x / 100));}

/** return this * x */
public CurrencyAsLong multiply(float x)
   {return new CurrencyAsLong((long) (amount * x));}

/** return this / x */
public CurrencyAsLong divide(float x)
   {return new CurrencyAsLong((long) (amount / x));}



A minimal test code for the new methods is given below.


   /** test program for new methods */
   public static void main(String [] args)
   {
      CurrencyAsLong g = new CurrencyAsLong(),
                       h = new CurrencyAsLong(PLUS, 3L, (byte) 50),
                       i = new CurrencyAsLong(2.50),
                       j = new CurrencyAsLong();

      // test input
      j.input();
      System.out.println("The input value is " + j);
      
      // test remaining new methods
      System.out.println(h + " - " + i + " = " + h.subtract(i));
      System.out.println("10 percent of " + i + " is " + i.percent(10.0F));
      System.out.println("2 * " + i + " = " + i.multiply(2.0F));
      System.out.println(i + " / 5 = " + i.divide(5.0F));
   }
}