Practice Questions: Week 11


Maps and Basic Exception Handling

1. Write a program that emulates GlobalCredit using a Map Specifically, create a Map that maps credit card numbers (as returned by CreditCard.getNumber) to CreditCards.

Try adding one or two CreditCards to the map. Try adding one or two RewardCards to the map; does it work?

Finally, print out all of the cards in the Map using four different traversals:

  1. Use a for-each loop over the set of keys.
  2. Use a for-each loop over the collection of values.
  3. Use an iterator over the set of keys.
  4. Use an iterator over the collection of values.

2. Study the type.lib.CharStack API (there are only two constructors and three methods). Modify the following program so that it catches the thrown exception and outputs the character that was being added to the stack when the exception occurred:

import type.lib.CharStack;

public class W11Q2
{
   public static void main(String[] args)
   {
      CharStack stack = new CharStack();
      
      char c = 'a';
      while (true)
      {
         stack.add(c);
         c = (char) (c + 1);
      }
   }
}

Note: this is a particularly poor use of exception handling; the point is to get some practice writing try-catch blocks. In general, you should never use exceptions for flow control as is done in this problem.


3. eCheck 10D if you have not attempted it already.


4. eCheck 11D if you have not attempted it already.


5. Exam programming test from last Fall.


6. Exam programming test from last Fall.


7. Long Map example from last Fall.