Chapter 6: Coin and Purse ADTs

Make the following changes to the Purse ADT:

import java.util.ArrayList;

/**
   A purse holds a collection of coins.
*/
public class Purse
{
   /**
      Constructs an empty purse.
   */
   public Purse()
   {
      coins = new ArrayList();
   }

   /**
      Add a coin to the purse.
      @param aCoin the coin to add
   */
   public void add(Coin aCoin)
   {
      coins.add(aCoin);
   }

   /**
      Get the total value of the coins in the purse.
      @return the sum of all coin values
   */
   public double getTotal()
   {
      double total = 0;
      for (int i = 0; i < coins.size(); i++)
      {
         Coin aCoin = (Coin)coins.get(i);
         total = total + aCoin.getValue();       
      }
      return total;
   }

   private ArrayList coins;
}

/**
A coin with a monetary value.
 */
public class Coin
{
    /**
    Constructs a coin.
    @param aValue the monetary value of the coin.
    @param aName the name of the coin
     */
    public Coin(double aValue, String aName)
    {
        value = aValue;
        name = aName;
    }

    /**
    Gets the coin value.
    @return the value
     */
    public double getValue()
    {
        return value;
    }

    /**
    Gets the coin name.
    @return the name
     */
    public String getName()
    {
        return name;
    }

    public boolean equals(Object otherObject)
    {
        Coin other = (Coin)otherObject;
        return name.equals(other.name)
        && value == other.value;
    }

    private double value;
    private String name;
}

Modify the Purse class to be implemented with ArrayList<Coin> and to use a for-each loop.
Implement the following methods in the Purse class:

 /**
      Counts the number of coins in the purse
      @return the number of coins
   */
   public int count()
   {
     
   }

   /**
      Tests if the purse has a coin that matches
      a given coin.
      @param aCoin the coin to match
      @return true if there is a coin equal to aCoin
   */
   public boolean find(Coin aCoin)
   {

   }

   /**
      Counts the number of coins in the purse that match
      a given coin.
      @param aCoin the coin to match
      @return the number of coins equal to aCoin
   */
   public int count(Coin aCoin)
   {

   }

   /**
      Finds the coin with the largest value. 
      (Precondition: The purse is not empty)
      @return a coin with maximum value in this purse
   */
   pulic Coin getMaximum()
   {

   }

/**
      Adds coins in the purse - use for-each loop
      Comment on this implementation
      if any issues come up.
   */
   public void addCoin(ArrayList<Coin> aCoins)
   {
     
   }

/**
      Deletes coins in the purse - use for-each loop to find all "coins"
      Comment on this implementation if any issues come up.
      @return an object of Coin      
   */
   public Coin deleteCoin(Coin aCoin)
   {
     
   }

Finally, write a driver, PurseTest.java to demonstrate the behavior of the for-each loop performance. Comment on any issues that might arise.

Submit the files in a zip folder(compressed) or a link to GitHub.

Chapter 6: More details on ArrayLists

Screen Shot 2014-12-11 at 9.19.49 PM

Screen Shot 2014-12-11 at 9.26.39 PM

ArrayList Constructs an empty list with an initial capacity of ten.


Screen Shot 2014-12-11 at 9.30.09 PM

boolean add(E obj) Appends the specified element to the end of this list.

void add(int index, E obj) Inserts the specified element at the specified position in this list.


E get(int index) Returns the element at the specified position in this list.

int indexOf(Object obj) Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

boolean isEmpty() Returns true if this list contains no elements.

int size() Returns the number of elements in this list.

ListIterator<E> listIterator() Returns a list iterator over the elements in this list (in proper sequence).

E remove(int index) Removes the element at the specified position in this list.

boolean remove(Object o) Removes the first occurrence of the specified element from this list, if it is present.
Resources

ListIterator, indexOf, Iterator, List Interface
Screen Shot 2014-12-15 at 9.05.33 PM

[collapse]
//********************************************************************
//  DestinysChild.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates the use of a ArrayList object.
//********************************************************************

import java.util.ArrayList;

public class DestinysChild
{
   //-----------------------------------------------------------------
   //  Stores and modifies a list of band members.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      ArrayList band = new ArrayList();

      band.add ("Michelle");
      band.add ("Kelly");
      band.add ("Beyonce");
      band.add ("Farrah");

      System.out.println (band);

      int location = band.indexOf ("Farrah");
      band.remove (location);

      System.out.println (band);
      System.out.println ("At index 1: " + band.get(1));

      System.out.println (band);
      System.out.println ("Size of the band: " + band.size());
   }
}

[Michelle, Kelly, Beyonce, Farrah]
[Michelle, Kelly, Beyonce]
At index 1: Kelly
[Michelle, Kelly, Beyonce]
Size of the band: 3

Two ways to iterate through the elements of a collection in java:

  1. By Iterator interface.
  2. By for-each loop.
//********************************************************************
//  Recipe.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates the use of a ListIterator to iterate through the
//  elements of an ArrayList.
//********************************************************************

import java.util.ArrayList;
import java.util.ListIterator;

public class Recipe
{
   //-----------------------------------------------------------------
   //  Stores and then prints a list of ingredients for a recipe.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      ArrayList<String> ingredients = new ArrayList<String>);

      ingredients.add ("flour");
      ingredients.add ("sugar");
      ingredients.add ("cocoa");
      ingredients.add ("oil");
      ingredients.add ("butter");
      ingredients.add ("eggs");
      ingredients.add ("baking soda");

      System.out.println ("To make a chocolate cake, use the following " +
         ingredients.size() + " ingredients:");

      // traversing ArrayList by Iterator
      ListIterator<String> iterator = ingredients.listIterator(); 
      while (iterator.hasNext())
         System.out.println(iterator.next());

      // traversing ArrayList using the "for-each" loop
       for(String obj:ingredients)  
          System.out.println(obj);  

   }
}

To make a chocolate cake, use the following 7 ingredients:
flour
sugar
cocoa
oil
butter
eggs
baking soda

Assignments:
1. Create a class DataSet of BankAccounts. The constructor creates an ArrayList of BankAccount(s). Write the test class to add, delete and print (use the for-each loop) bank accounts. Your driver should have at least 3 BankAccount objects. Make any changes necessary to have the DataSet ADT implemented with an ArrayList. Also, change the comments to fit the modifications to the it.

DataSet with ArrayList
/**
Computes the average of a set of data values.
*/
public class DataSet
{
/**
Constructs an empty data set with no BankAccount objects.
*/
public DataSet()
{
sum = 0;
count = 0; // Warning: Is "count" necessary?
maximum = 0; // Warning: this should not be a numeric type!!
// create an object of the ArrayList dataSet
}

/**
Adds a BankAccount object to the data set
@param x a BankAccount object
*/
public void add(BankAccount bank)
{
// add object to ArrayList
sum = sum + bank.getBalance();
if (count == 0 || maximum.getBalance() < x.getBalance()) maximum = x;
count++;
}

/**
Gets the average of the added BankAccount balances.
@return the average or 0 if no data has been added
*/
public double getAverage()
{
if (count == 0) return 0;
else return sum / count; // Warning
}

/**
Gets the largest of the added data. // changes must be made here
@return the maximum or 0 if no data has been added
*/
public BankAccount getMaximum()
{
return maximum;
}

/**
Prints the balance for each element of the added data in the ArrayList.// Warning
@return the average or 0 if no data has been added
*/
public void printDataSet()
{
// implement the code to print the elements of the ArrayList datSet. Add more specific comments
// use the for-each loop
}

private double sum;
private BankAccount maximum;
private int count;
private ArrayList<BankAccount> dataSet;
}

[collapse]
  1. Create a class Purse (see below) that contains an ArrayList of Coin(s). Write the test class to add, delete, and print coins. Make any changes necessary to have the Purse class implemented with an ArrayList. Also, change the comments to fit the modifications to the ADT.
/**
A coin with a monetary value.
*/
public class Coin
{
/**
Constructs a coin.
@param aValue the monetary value of the coin.
@param aName the name of the coin
*/
public Coin(double aValue, String aName)
{
value = aValue;
name = aName;
}

/**
Gets the coin value.
@return the value
*/
public double getValue()
{
return value;
}

/**
Gets the coin name.
@return the name
*/
public String getName()
{
return name;
}

public boolean equals(Object otherObject)
{
Coin other = (Coin)otherObject;
return name.equals(other.name)
&& value == other.value;
}

private double value;
private String name;
}

Modify the Purse class to be implemented with ArrayList<Coin> and to use a for-each loop.
Implement the following methods in the Purse class:

 /**
Counts the number of coins in the purse
@return the number of coins
*/
public int count()
{

}

/**
Tests if the purse has a coin that matches
a given coin.
@param aCoin the coin to match
@return true if there is a coin equal to aCoin
*/
public boolean find(Coin aCoin)
{

}

/**
Counts the number of coins in the purse that match
a given coin.
@param aCoin the coin to match
@return the number of coins equal to aCoin
*/
public int count(Coin aCoin)
{

}

/**
Finds the coin with the largest value.
(Precondition: The purse is not empty)
@return a coin with maximum value in this purse
*/
pulic Coin getMaximum()
{

}

NOTE: Use the “for-each” loop in the implementation.

Chapter 6: The Iterator


import java.util.ArrayList;

/**
   This bank contains a collection of bank accounts.
*/
public class Bank
{   
   /**
      Constructs a bank with no bank accounts.
   */
   public Bank()
   {
      accounts = new ArrayList<BankAccount>();
   }

   /**
      Adds an account to this bank.
      @param a the account to add
   */
   public void addAccount(BankAccount a)
   {
      accounts.add(a);
   }
   
   /**
      Gets the sum of the balances of all accounts in this bank.
      @return the sum of the balances
   */
   public double getTotalBalance()
   {
      double total = 0;
      for (BankAccount a : accounts)
      {
         total = total + a.getBalance();
      }
      return total;
   }

   /**
      Counts the number of bank accounts whose balance is atLeast a given value.
      @param atLeast the balance required to count an account
      @return the number of accounts having least the given balance
   */
   public int count(double atLeast)
   {
      int matches = 0;
      for (BankAccount a : accounts)
      {
         if (a.getBalance() >= atLeast) matches++; // Found a match
      }
      return matches;
   }

   /**
      Finds a bank account with a given number.
      @param accountNumber the number to find
      @return the account with the given number, or null if there
      is no such account
   */
   public BankAccount find(int accountNumber)
   {
      for (BankAccount a : accounts)
      {
         if (a.getAccountNumber() == accountNumber) // Found a match
            return a;
      } 
      return null; // No match in the entire array list
   }

   /**
      Gets the bank account with the largest balance.
      @return the account with the largest balance, or null if the
      bank has no accounts
   */
   public BankAccount getMaximum()
   {
      if (accounts.size() == 0) return null;
      BankAccount largestYet = accounts.get(0);
      for (int i = 1; i < accounts.size(); i++) 
      {
         BankAccount a = accounts.get(i);
         if (a.getBalance() < largestYet.getBalance())
            largestYet = a;
      }
      return largestYet;
   }

   private ArrayList<BankAccount> accounts;
}

/** 
 * mrs.e
 * 12/14/2018
 * 
 * ArrayLists
 * for-each loop
 * Iterator
 * 
 * */

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListIterator 
{
   public static void main( String[] args )
   {
      // add elements to an ArrayList
      String[] pets = { "Puppy", "Kitten", "Gerbil", "Bunny", "Ferret" };
      ArrayList<String> aList = new ArrayList<String>();      

      for ( String pet : pets )
         aList.add( pet ); // for each loop - don't change the ArrayList   

      // add elements in removePets array to removeList
      String[] removePets = { "Gerbil", "Bunny" };
      ArrayList<String> removeList = new ArrayList<String>();

      for ( String pet : removePets )
         removeList.add( pet ); 

      // print items of the list
      System.out.println( "ArrayList: " );

      for ( int count = 0; count < aList.size(); count++ )
         System.out.printf( "%s ", aList.get( count ) );

      // remove from list the pets contained in removeList
      removePets( aList, removeList );

      // print items of the list 
      System.out.println( "\n\nArrayList after calling removePets: " );

      for ( String pet : aList )
         System.out.printf( "%s ", pet );
   } // end main

   // remove pets in collection2 found in collection1
   private static void removePets( ArrayList<String> collection1, 
      ArrayList<String> collection2 )
   {
      // get iterator
      Iterator<String> iterator = collection1.iterator(); 

      // loop while collection has items
      while ( iterator.hasNext() )         
      {
         if ( collection2.contains( iterator.next() ) )
            {
            iterator.remove(); // remove current pet
            }
      } // end while
   } // end method removePets
} // end class ArrayListIterator

Time and Space Efficiency

There are lots of reasons for choosing one sorting algorithm over another. We might choose an algorithm because it is simple, fast, uses less memory, or works well on the kind of data we have. An algorithm that is easier to understand is also easier to write and debug. However, often the simplest sorts are not efficient. Efficiency is usually the first thing we look for.

We can compare algorithms in terms of time and space efficiency.

Space efficiency refers to the amount of space that an algorithm uses. An algorithm that uses less space and runs faster is more efficient.

  • We measure efficiency by the size of the input. For a sorting algorithm the input is the array of elements to be sorted, so the size of the input is the number of elements. We will use n for the number of elements being sorted.
  • We can measure the time efficiency of an algorithm by counting how many statements get executed when the algorithm runs.

We are most interested in how the running time grows as the size of the input grows, so we can ignore statements that get executed the same number of times each time the algorithm is run.

  • Instead we look at those statements that get executed a different number of times depending on the size of the input.
  • In sorting algorithms, the common operation is a comparison, so we usually count comparisons when we consider sorting algorithms.
  • As the number of elements to be sorted grows, the number of comparisons required grows as well.

We want to find the relationship between the two growth rates.

The selection sort has an outer loop that runs n-1 times, where n is the size of the input array.

The inner loop runs a variable number of times, ranging from 1 to n-1, depending on the index of the outer loop.

So, we can say that the time efficiency of the selection sort algorithm is on the order of n^2.

  • We use big-oh notation saying that selection sort is O(n^2). This means that the running time of the selection sort algorithm will be no worse than on the order of n^2 units of time, where n is the size of the input.
  • We are not interested in how long a unit of time is because we use big-oh notation only to compare algorithms to each other; we are not trying to find out how long the algorithm takes to run.
  • Note that because O(n^2) is an efficiency no worse than n^2, we could also say that selection sort is O(n^3) or O(n^4 ) or O(2n). However, we want to get as close as possible to an algorithm’s real time efficiency.
  • We can analyze insertion sort in almost the same way.
  • Its two nested loops run n times each, so the statements (comparisons) inside get executed approximately n^2 times.
  • The insertion sort algorithm is therefore also O(n^2).
  • An algorithm,  that  was  O(n) would be more efficient than one that is O(n^2 ).
  • Likewise, O(n^3 ) and O(2n) algorithms are less efficient than O(n2 ).

Table below shows various efficiency values for algorithms ranked from most efficient to least efficient. Note that for small values of n there is not much difference, but when n gets large, the efficiency of an algorithm makes a big difference.

The insertion sort has O(n^2) in the worse case. However, in an verage when the data is random, it is a more efficient sort.

These two sorts can also be implemented to work on objects.

 

Chapter 6 – ArrayLists of BankAccount objects


import java.util.ArrayList; 

/** This bank contains a collection of bank accounts. */ 

public class Bank { 

    /** instance field(s) **/
    private ArrayList<BankAccount> accounts; 

    /** Constructs a bank with no bank accounts. */ 

    public Bank() 
    { 
        accounts = new ArrayList<BankAccount>(); 
    } 

    /** Adds an account to this bank. 
    @param a the account to add */ 

    public void addAccount(BankAccount a) 
    { 

        accounts.add(a); 
    } 

    /** Gets the sum of the balances of all accounts in this bank. @return the sum of the balances */ 

    public double getTotalBalance() 
    { 
        double total = 0; 
        for (BankAccount a : accounts) 
        { 
            total = total + a.getBalance(); 
        } 
        return total;
    } 

    /** Counts the number of bank accounts whose balance is at least a given value. 
     * @param atLeast the balance required to count an account 
     * @return the number of accounts having least the given balance */ 

    public int count(double atLeast) 
    { 
        int matches = 0; 
        for (BankAccount a : accounts) 
        { 
            if (a.getBalance() >= atLeast) 
                matches++; // Found a match 
        } 
        return matches; 
    } 

    /** Finds a bank account with a given number. 
     * @param accountNumber the number to find 
     * @return the account with the given number, or null if there is no such account */ 
    public BankAccount find(int accountNumber) 
    { 
        for (BankAccount a : accounts) 
        { 
            if (a.getAccountNumber() == accountNumber) // Found a match 
                return a; 
        } 
        return null; // No match in the entire array list 
    } 

    /** Gets the bank account with the largest balance. 
     * @return the account with the largest balance, or null if the bank has no accounts */ 
    public BankAccount getMaximum() 
    { 
        if (accounts.size() == 0) return null; 
        BankAccount largestYet = accounts.get(0); 
        for (int i = 1; i < accounts.size(); i++) 
        { 
            BankAccount a = accounts.get(i); 
            if (a.getBalance() > largestYet.getBalance()) largestYet = a; 
        } 
        return largestYet; 
    } 

}



//********************************************************************
//  Account.java now called BankAccount.java       Author: Lewis/Loftus/Cocking
//
//  Represents a bank account with basic services such as deposit
//  and withdraw.
//********************************************************************

import java.text.NumberFormat;

public class BankAccount /** formerly called Account **/
{
   private NumberFormat fmt = NumberFormat.getCurrencyInstance();

   private final double RATE = 0.035;  // interest rate of 3.5%

   private int acctNumber;
   private double balance;
   private String name;

   //-----------------------------------------------------------------
   //  Sets up the account by defining its owner, account number,
   //  and initial balance.
   //-----------------------------------------------------------------
   public BankAccount (String owner, int account, double initial)
   {
      name = owner;
      acctNumber = account;
      balance = initial;
   }

   //-----------------------------------------------------------------
   //  Validates the transaction, then deposits the specified amount
   //  into the account. Returns the new balance.
   //-----------------------------------------------------------------
   public double deposit (double amount)
   {
      if (amount < 0)  // deposit value is negative
      {
         System.out.println ();
         System.out.println ("Error: Deposit amount is invalid.");
         System.out.println (acctNumber + "  " + fmt.format(amount));
      }
      else
         balance = balance + amount;
      return balance;
   }

   //-----------------------------------------------------------------
   //  Validates the transaction, then withdraws the specified amount
   //  from the account. Returns the new balance.
   //-----------------------------------------------------------------
   public double withdraw (double amount, double fee)
   {
      amount += fee;

      if (amount < 0)  // withdraw value is negative
      {
         System.out.println ();
         System.out.println ("Error: Withdraw amount is invalid.");
         System.out.println ("Account: " + acctNumber);
         System.out.println ("Requested: " + fmt.format(amount));
      }
      else
         if (amount > balance)  // withdraw value exceeds balance
         {
            System.out.println ();
            System.out.println ("Error: Insufficient funds.");
            System.out.println ("Account: " + acctNumber);
            System.out.println ("Requested: " + fmt.format(amount));
            System.out.println ("Available: " + fmt.format(balance));
         }
         else
            balance = balance - amount;

      return balance;
   }

   //-----------------------------------------------------------------
   //  Adds interest to the account and returns the new balance.
   //-----------------------------------------------------------------
   public double addInterest ()
   {
      balance += (balance * RATE);
      return balance;
   }

   //-----------------------------------------------------------------
   //  Returns the current balance of the account.
   //-----------------------------------------------------------------
   public double getBalance ()
   {
      return balance;
   }

   //-----------------------------------------------------------------
   //  Returns the account number.
   //-----------------------------------------------------------------
   public int getAccountNumber ()
   {
      return acctNumber;
   }

   //-----------------------------------------------------------------
   //  Returns a one-line description of the account as a string.
   //-----------------------------------------------------------------
   public String toString ()
   {
      return (acctNumber + "\t" + name + "\t" + fmt.format(balance));
   }
}



The whole Bank ADT is visible:

import java.util.ArrayList;

/**
   This bank contains a collection of bank accounts.
*/
public class Bank
{   
   /**
      Constructs a bank with no bank accounts.
   */
   public Bank()
   {
      accounts = new ArrayList<BankAnccount>();
   }

   /**
      Adds an account to this bank.
      @param a the account to add
   */
   public void addAccount(BankAccount a)
   {
      accounts.add(a);
   }
   
   /**
      Gets the sum of the balances of all accounts in this bank.
      @return the sum of the balances
   */
   public double getTotalBalance()
   {
      double total = 0;
      for (BankAccount a : accounts)
      {
         total = total + a.getBalance();
      }
      return total;
   }

   /**
      Counts the number of bank accounts whose balance is at
      least a given value.
      @param atLeast the balance required to count an account
      @return the number of accounts having least the given balance
   */
   public int count(double atLeast)
   {
      int matches = 0;
      for (BankAccount a : accounts)
      {
         if (a.getBalance() >= atLeast) matches++; // Found a match
      }
      return matches;
   }

   /**
      Finds a bank account with a given number.
      @param accountNumber the number to find
      @return the account with the given number, or null if there
      is no such account
   */
   public BankAccount find(int accountNumber)
   {
      for (BankAccount a : accounts)
      {
         if (a.getAccountNumber() == accountNumber) // Found a match
            return a;
      } 
      return null; // No match in the entire array list
   }

   /**
      Gets the bank account with the largest balance.
      @return the account with the largest balance, or null if the
      bank has no accounts
   */
   public BankAccount getMaximum()
   {
      if (accounts.size() == 0) return null;
      BankAccount largestYet = accounts.get(0);
      for (int i = 1; i < accounts.size(); i++) 
      {
         BankAccount a = accounts.get(i);
         if (a.getBalance() < largestYet.getBalance())
            largestYet = a;
      }
      return largestYet;
   }
   /** NOTICE THE INSTANCE FIELD AT THE END OF THE FILE **/
   private ArrayList<BankAccount> accounts;
}

The whole BankAccount ADT (formerly Account) is visible:

//********************************************************************
//  Account.java now called BankAccount.java       Author: Lewis/Loftus/Cocking
//
//  Represents a bank account with basic services such as deposit
//  and withdraw.
//********************************************************************

import java.text.NumberFormat;

public class BankAccount
{
   private NumberFormat fmt = NumberFormat.getCurrencyInstance();

   private final double RATE = 0.035;  // interest rate of 3.5%

   private int acctNumber;
   private double balance;
   private String name;

   //-----------------------------------------------------------------
   //  Sets up the account by defining its owner, account number,
   //  and initial balance.
   //-----------------------------------------------------------------
   public BankAccount (String owner, int account, double initial)
   {
      name = owner;
      acctNumber = account;
      balance = initial;
   }

   //-----------------------------------------------------------------
   //  Validates the transaction, then deposits the specified amount
   //  into the account. Returns the new balance.
   //-----------------------------------------------------------------
   public double deposit (double amount)
   {
      if (amount < 0)  // deposit value is negative
      {
         System.out.println ();
         System.out.println ("Error: Deposit amount is invalid.");
         System.out.println (acctNumber + "  " + fmt.format(amount));
      }
      else
         balance = balance + amount;
      return balance;
   }

   //-----------------------------------------------------------------
   //  Validates the transaction, then withdraws the specified amount
   //  from the account. Returns the new balance.
   //-----------------------------------------------------------------
   public double withdraw (double amount, double fee)
   {
      amount += fee;

      if (amount < 0)  // withdraw value is negative
      {
         System.out.println ();
         System.out.println ("Error: Withdraw amount is invalid.");
         System.out.println ("Account: " + acctNumber);
         System.out.println ("Requested: " + fmt.format(amount));
      }
      else
         if (amount > balance)  // withdraw value exceeds balance
         {
            System.out.println ();
            System.out.println ("Error: Insufficient funds.");
            System.out.println ("Account: " + acctNumber);
            System.out.println ("Requested: " + fmt.format(amount));
            System.out.println ("Available: " + fmt.format(balance));
         }
         else
            balance = balance - amount;

      return balance;
   }

   //-----------------------------------------------------------------
   //  Adds interest to the account and returns the new balance.
   //-----------------------------------------------------------------
   public double addInterest ()
   {
      balance += (balance * RATE);
      return balance;
   }

   //-----------------------------------------------------------------
   //  Returns the current balance of the account.
   //-----------------------------------------------------------------
   public double getBalance ()
   {
      return balance;
   }

   //-----------------------------------------------------------------
   //  Returns the account number.
   //-----------------------------------------------------------------
   public int getAccountNumber ()
   {
      return acctNumber;
   }

   //-----------------------------------------------------------------
   //  Returns a one-line description of the account as a string.
   //-----------------------------------------------------------------
   public String toString ()
   {
      return (acctNumber + "\t" + name + "\t" + fmt.format(balance));
   }
}

You may use a ListIterator which has support for a remove/add method during the iteration itself.

stackoverflow

ListIterator<Book> iter = books.listIterator();
while(iter.hasNext()){
    if(iter.next().getIsbn().equals(isbn)){
        iter.add(new Book(...));
    }
}

Global Sequence Alignment

Write a program to compute the optimal sequence alignment of two DNA strings. This program will introduce you to the field of computational biology in which computers are used to do research on biological systems. Further, you will be introduced to a powerful algorithmic design paradigm known as dynamic programming.

Biology review.  A genetic sequence is a string formed from a four-letter alphabet {Adenine (A), Thymine (T), Guanine (G), Cytosine (C)} of biological macromolecules referred to together as the DNA bases. A gene is a genetic sequence that contains the information needed to construct a protein. All of your genes taken together are referred to as the human genome, a blueprint for the parts needed to construct the proteins that form your cells. Each new cell produced by your body receives a copy of the genome. This copying process, as well as natural wear and tear, introduces a small number of changes into the sequences of many genes. Among the most common changes are the substitution of one base for another and the deletion of a substring of bases; such changes are generally referred to as point mutations. As a result of these point mutations, the same gene sequenced from closely related organisms will have slight differences.

The problem.  Through your research you have found the following sequence of a gene in a previously unstudied organism.

A A C A G T T A C C

What is the function of the protein that this gene encodes? You could begin a series of uninformed experiments in the lab to determine what role this gene plays. However, there is a good chance that it is a variant of a known gene in a previously studied organism. Since biologists and computer scientists have laboriously determined (and published) the genetic sequence of many organisms (including humans), you would like to leverage this information to your advantage. We’ll compare the above genetic sequence with one which has already been sequenced and whose function is well understood.

T A A G G T C A

If the two genetic sequences are similar enough, we might expect them to have similar functions. We would like a way to quantify “similar enough.”

Edit-distance.  In this assignment we will measure the similarity of two genetic sequences by their edit distance, a concept first introduced in the context of coding theory, but which is now widely used in spell checking, speech recognition, plagiarism detection, file revisioning, and computational linguistics. We align the two sequences, but we are permitted to insert gaps in either sequence (e.g., to make them have the same length). We pay a penalty for each gap that we insert and also for each pair of characters that mismatch in the final alignment. Intuitively, these penalties model the relative likeliness of point mutations arising from deletion/insertion and substitution. We produce a numerical score according to the following table, which is widely used in biological applications:

Here are two possible alignments of the strings x = "AACAGTTACC" and y = "TAAGGTCA":

The first alignment has a score of 8, while the second one has a score of 7. The edit-distance is the score of the best possible alignment between the two genetic sequences over all possible alignments. In this example, the second alignment is in fact optimal, so the edit-distance between the two strings is 7. Computing the edit-distance is a nontrivial computational problem because we must find the best alignment among exponentially many possibilities. For example, if both strings are 100 characters long, then there are more than 10^75 possible alignments.

Not finished

Chapter 3: The “switch” Statement

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

public class SwitchDemo {
    public static void main(String[] args) {

        int month = 8;
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
    }
}

In this case, August is printed to standard output.

The body of a switch statement is known as a switch block. A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label.

You could also display the name of the month with if-then-else statements:

int month = 8;
if (month == 1) {
    System.out.println("January");
} else if (month == 2) {
    System.out.println("February");
}
...  // and so on

Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing. An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.

Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered. The program SwitchDemoFallThrough shows statements in a switch block that fall through. The program displays the month corresponding to the integer month and the months that follow in the year:

public class SwitchDemoFallThrough {

    public static void main(String[] args) {
        java.util.ArrayList<String> futureMonths =
            new java.util.ArrayList<String>();

        int month = 8;

        switch (month) {
            case 1:  futureMonths.add("January");
            case 2:  futureMonths.add("February");
            case 3:  futureMonths.add("March");
            case 4:  futureMonths.add("April");
            case 5:  futureMonths.add("May");
            case 6:  futureMonths.add("June");
            case 7:  futureMonths.add("July");
            case 8:  futureMonths.add("August");
            case 9:  futureMonths.add("September");
            case 10: futureMonths.add("October");
            case 11: futureMonths.add("November");
            case 12: futureMonths.add("December");
                     break;
            default: break;
        }

        if (futureMonths.isEmpty()) {
            System.out.println("Invalid month number");
        } else {
            for (String monthName : futureMonths) {
               System.out.println(monthName);
            }
        }
    }
}

This is the output from the code:

August
September
October
November
December

Technically, the final break is not required because flow falls out of the switch statement. Using a break is recommended so that modifying the code is easier and less error prone. The default section handles all values that are not explicitly handled by one of the case sections.

The following code example, SwitchDemo2, shows how a statement can have multiple case labels. The code example calculates the number of days in a particular month:

class SwitchDemo2 {
    public static void main(String[] args) {

        int month = 2;
        int year = 2000;
        int numDays = 0;

        switch (month) {
            case 1: case 3: case 5:
            case 7: case 8: case 10:
            case 12:
                numDays = 31;
                break;
            case 4: case 6:
            case 9: case 11:
                numDays = 30;
                break;
            case 2:
                if (((year % 4 == 0) && 
                     !(year % 100 == 0))
                     || (year % 400 == 0))
                    numDays = 29;
                else
                    numDays = 28;
                break;
            default:
                System.out.println("Invalid month.");
                break;
        }
        System.out.println("Number of Days = "
                           + numDays);
    }
}

This is the output from the code:

Number of Days = 29

Using Strings in switch Statements

In Java SE 7 and later, you can use a String object in the switch statement’s expression. The following code example, StringSwitchDemo, displays the number of the month based on the value of the String named month:

public class StringSwitchDemo {

    public static int getMonthNumber(String month) {

        int monthNumber = 0;

        if (month == null) {
            return monthNumber;
        }

        switch (month.toLowerCase()) {
            case "january":
                monthNumber = 1;
                break;
            case "february":
                monthNumber = 2;
                break;
            case "march":
                monthNumber = 3;
                break;
            case "april":
                monthNumber = 4;
                break;
            case "may":
                monthNumber = 5;
                break;
            case "june":
                monthNumber = 6;
                break;
            case "july":
                monthNumber = 7;
                break;
            case "august":
                monthNumber = 8;
                break;
            case "september":
                monthNumber = 9;
                break;
            case "october":
                monthNumber = 10;
                break;
            case "november":
                monthNumber = 11;
                break;
            case "december":
                monthNumber = 12;
                break;
            default: 
                monthNumber = 0;
                break;
        }

        return monthNumber;
    }

    public static void main(String[] args) {

        String month = "August";

        int returnedMonthNumber =
            StringSwitchDemo.getMonthNumber(month);

        if (returnedMonthNumber == 0) {
            System.out.println("Invalid month");
        } else {
            System.out.println(returnedMonthNumber);
        }
    }
}

The output from this code is 8.

The String in the switch expression is compared with the expressions associated with each case label as if the String.equals method were being used. In order for the StringSwitchDemo example to accept any month regardless of case, month is converted to lowercase (with the toLowerCase method), and all the strings associated with the case labels are in lowercase.

Note: This example checks if the expression in the switch statement is null. Ensure that the expression in any switch statement is not null to prevent a NullPointerException from being thrown.

Chapter 3: Language Basics – Conditionals

Chapter 3: Program Statements Notes

Control Flow:

  1. A conditional statement is sometimes called a selection statement.
  2. Each decision is based on a boolean expression.
  3. Three types of loop statements: while, do and for statements.

The if statement:

ifStatementFlowChart

Shorthand “if” statement: a ternary operator, inline if a or ternary

y = ( x <= 0 ) ? x : -x

which is a convenient way of writing

if ( x <= 0 )
y = x;
else
y = -x;
Equality and Relational Operators
Nested if statements
if (a > b)
if (a > c)
x = a; // a is ...
else
x = c; // c is ...
else
if (b > c)
x = b; // b is ...
else
x = c; // c is .. 

Classwork: you can use this code snippet to write a program minMax_YI.java to prompt the user for three numbers and displays them in order from smallest to largest.Write the test/driver program if you use OOD.
NOTE: Assume the numbers are different. Include this assumption in your documentation.

Boolean expressions:

Logical operators:

logicalOps

Truth Table:

truthTable

Logical AND and OR operators:

andOrTruthTable

Example of truth table for a specific condition:

truthTableExample

Visit edmodo.com to access the doc version.

While Statement:

whileLoopFC

while ( condition )
{
   // statements block
}

A common mistake: an infinite loop. The loop will keep going forever.

whileStatmt

The do loop:

doFC

do
{
   // statements block
}
while ( condition );

The for loop:

forStatement

forFlowChart

for ( initialization; condition; update )
    {
      // block statements
    }

It is a sign of unbelievably bad taste to put unrelated conditions into the loop. ( lol )

Classwork:
Using the code snippet from the lesson write a program MinMax_YI.java to prompt the user for three numbers and displays them in order from smallest to largest. OOP is not required. However, write the test/driver program if you use OOD.


Assignment: Programming Project 3.2
Design and implement an application that reads an integer value representing a year input by the user. The purpose of the program is to determine if the year is a leap year (and therefore has 29 days in February) in the Gregorian calendar. A year is a leap year if it is divisible by 4, unless it is also divisible by 100 but not 400. For example, the year 2003 is not a leap year, but 2004 is. The year 1900 is not a leap year because it is divisible by 100, but the year 2000 is a leap year because even though it is divisible by 100, it is also divisible by 400. Produce an error message for any input value less than 1582 (the year the Gregorian calendar was adopted).

Reading and Writing Assignments:

Read pages 124 through 140, submit the short answers 3.1 through 3.5.

Short Answers:

3.1 What happens in the MinOfThree_YI.java program if two or more of
the values are equal? If exactly two of the values are equal, does
it matter whether the equal values are lower or higher than the
third?

3.2 What is wrong with the following code fragment? Rewrite it so
that it produces correct output.

if (total == MAX)
    if (total < sum)
       System.out.println ("total == MAX and is < sum.");
    else
       System.out.println ("total is not equal to MAX");

3.3 What is wrong with the following code fragment? Will this code
compile if it is part of a valid program? Explain.

if (length == MIN_LENGTH)
   System.out.println ("The length is minimal.");

3.4 What output is produced by the following code fragment?

int num = 87, max = 25;
if (num >= max*2)
System.out.println ("apple");
System.out.println ("orange");
System.out.println ("pear");

3.5 What output is produced by the following code fragment?

int limit = 100, num1 = 15, num2 = 40;
if (limit <= limit)
{
if (num1 == num2)
System.out.println ("lemon");
System.out.println ("lime");
}
System.out.println ("grape");