Exercise Set 5

Put your solutions under the set5 directory in your repository.

Don't forget to commit your changes locally and then push them up to GitLab.


In a file named Ex11.java, write a program that uses a map to simulate a phone book. It should

  • Create the map and populate it with a few names and phone numbers
  • Prompt the user to enter a name
  • Display the corresponding phone number, or a suitable error message if the name is not found

Optional extra tasks (not required for exercise to be considered complete):

  • Modify the program so that it uses a loop to repeatedly prompt the user for a name.
  • Modify the program so that it terminates if the user enters quit as a name.
  • Modify the program so that it reads names and numbers from a file rather than hardcoding them.


Copy the file BankAccount.java that you created for Exercise 9 into the set5 directory. Modify the class, changing the accessibility of the balance field from private to protected.

In a new file named SavingsAccount.java, create a class named SavingsAccount. This class should inherit from BankAccount, as shown in the UML diagram below.

UML representation of SavingsAccount class

The interest rate field for this class should have a default value of 0.05, in the case where an initial value isn't provided to the constructor. Make sure that attempts to initialise or change interest rate to a value ≤ 0.0 are prevented, by throwing an IllegalArgumentException.

The applyInterest method should apply interest to the account by multiplying interest rate by balance, rounding down to the nearest integer and incrementing the balance by this rounded amount.

One feature of this type of account is that, whilst it is possible to create the account with any initial balance ≥ 0, withdrawals are only permitted if they won't drop the balance below 100. Implement this feature by making appropriate changes to SavingsAccount (and, if necessary, BankAccount). There are a couple of different ways of achieving this. The most obvious approach would be to override the withdraw method directly.

In a new file named Ex12.java, create a class named Ex12 containing a program that creates a SavingsAccount object and demonstrates that it functions as described above.