Ryerson University: Dept. of Computer Science

CPS209, Midterm Test 2B(yellow) Solutions, Winter 2006

Last Name __________________ First _______________ Number_________________
  1. (1 mark) Which of the following assignments compiles without error? (Assume HorseFly is a subclass of Fly).
    Answer: 1 3 4
        Fly fly = new Fly() ;
        HorseFly horseFly = new HorseFly() ;
        fly = horseFly ;          // 1
        horseFly = fly ;          // 2
        fly = (Fly)horseFly ;    // 3
        horseFly = (HorseFly)fly ;    // 4
  2. (8 marks) Write an application Sum which takes one or more command line arguments, for example:
    java Sum 4 3 7 1
    The purpose of the application is to add the numbers on the command line print the sum. The numbers can be integer or real, and there can be any number of them, but at least one. You can use Double.parseDouble which throws a NumberFormatException. You must catch such exceptions and print an error message and exit gracefully. Include a usage function which is called when the number of arguments is incorrect and which shows the usage and exits gracefully.
  3. (1 mark) What does a combo box and a group of radio buttons have in common?
    In both, the choices are mutually exclusive.
  4. (10 marks) Write a subclass of BankAccount (listed below) called LottoAccount which has the following features:
    1. Every LottoAccount has a special lottoNumber, which is an integer from 1 to 6. It also has a random number generator.
    2. There is a default constructor which sets balance to 0 and lottoNumber to a random value from 1 to 6 inclusive.
    3. There is a constructor with parameters for the initial balance and the lottoNumber.
    4. When there is a deposit for x dollars, then a random number is generated from 1 to 6, and if it equals the lottoNumber then there is a second deposit of x dollars, but the second deposit is a simple deposit, not the kind that can win money.
    5. Withdrawals of x dollars work normally except that if there is not enough money in the account, then they cause an IllegalArgumentException which is not caught here and the lottoNumber is set to 0 to prevent further winnings.
    public class BankAccount 
        private double balance ;
        public BankAccount() { balance = 0 ; }
        public BankAccount(double initialBalance) {	balance = initialBalance ; }
        public void deposit(double amount) { balance += amount ; }
        public void withdraw(double amount) { balance -= amount ; }
        public double getBalance() { return balance ; }