Midterm Solution

  1. Box trace of a binary search for 30 in anArray=<10, 20, 30, 40, 50, 60, 70>
    value = 30
    first = 0
    last = 6
    mid = (0 + 6) / 2 = 3
    value < anArray[3]
    value = 30
    first = 0
    last = 2
    mid = (0 + 2) / 2 = 1
    value > anArray[1]
    value = 30
    first = 2
    last = 2
    mid = (2 + 2) / 2 = 2
    value = anArray[2]
    return 2
  2. /**
     * computeMin: compute and return the largest integer in a list of integers.
     * @param aList, a list object of a class that implements IntegerListInterface
     * @return the maximum integer in aList, or Integer.MAX_VALUE if alist is empty. 
     */
    public int computeMin (IntegerListInterface aList)
    {
        int size = aList.size();
    
        if (size == 0)
           return Integer.MAX_VALUE;
     
        // Invariant: aList has at least one element.
        int min = aList.get(1); // initialize the maximum so far to the first item in aList.
    
        for (int i = 2; i <= size; i++)
        {
    '       // Get the next item in aList
    	int nextItem = aList.get(i);
    
            // If next item is less than min (the minimum we've seen so far) then update min 
    	if (nextItem < min)
               min = nextItem;
        } // end for
    
        return min;
    } // end computeMin
    
  3. /**
     * deposit: Bank method which deposits a given amount to the account corresponding to the given account ID.
     * @param accountId String  the ID of the account to which we want to deposit
     * @param amount    Money   the amount to deposit
     * @return none
     * @throws AccountNotFoundException if there is no account with the given ID.
     */
    public void deposit (String accountId, Money amount) throws AccountNotFoundException
    {	
    	// Search for the account with the given id.
            Account acc = this.find(accountId);  // call helper method
    
            if (acc == null) { // id not found
    		throw new AccountNotFoundException(id + " not found");
            }
    	else { // id was found; deposit to the appropriate account
    		acc.deposit(amount);
    	}
    } // end deposit
    
    /**
     * find: helper nethod of deposit that searches for the account with the specified id.
     * @param id  String representing the account ID 
     * @return the account with the given id, or null if not found.
     */
    private Account find(String id)
    {
            int numOfAccounts = accounts.size();
    
    	for (int i = 1; i <= numOfAccounts; i++) {
    		// Get the next account (at index i) from the list of accounts.
    		Account nextAcc = (Account) accounts.get(i);
    
    		// If its id matches the id given as parameter, then return the account whose id matched 
    		if (id.equals(nextAcc.getId()))
    			return nextAcc;
    	} // end for
    
    	// Invariant: id was not found, so return null.
    	return null;
    } // end find