Category Archives: Homework

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 – 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(...));
    }
}

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");