Quiz | Posted (Thursdays) |
Given in class (Thursdays) |
||
---|---|---|---|---|
3 | Feb | 10 | Feb |
You will fare better on the quiz if you try working the problems before looking at the solutions. If you don't understand the question or its answer, please get help.
Directions: Consider the following class definition (as presented in class) and then answer the questions below. Because the actual question on the quiz may be different, you are better off understanding your answers by doing them by-hand. Do not bother typing them into a computer.
public class Account { int balance; Account(int openingBalance) { balance = openingBalance; } public void deposit(int dollars) { balance = balance + dollars; } public boolean withdraw(int dollars) { if (balance < dollars) return false; else { balance = balance - dollars; return true; } } public boolean transfer (int dollars, Account destination) { if (withdraw(dollars)) { destination.deposit(dollars); return true; } else return false; } public String toString() { return ("$" + balance + ".00"); } }
Account alice, bob; // line 1 alice = new Account(100); // line 2 alice.deposit(25); // line 3 Terminal.println("Alice has " + alice); bob = new Account(100); // line 5 Terminal.println("Bob can withdraw $125.00? " + bob.withdraw(125)); Terminal.println("Bob can withdraw $25.00? " + bob.withdraw(25)); Terminal.println("Bob has " + bob); Account charlie = alice; // line 9 Terminal.println("Charlie can withdraw $25.00? " + charlie.withdraw(25)); Terminal.println("Charlie has " + charlie); Terminal.println("Alice has " + alice); alice.transfer(50, charlie); Terminal.println("After transfer..."); Terminal.println("Charlie has " + charlie); Terminal.println("Alice has " + alice);
Terminal.println("This account has " + (new Account(60)));
Account foo; // line 1 foo.withdraw(25); // line 2Suggest a line that could be added between lines 1 and 2 in order to avoid the error on line 2. (Alternatively, suggest a modification to line 1 that would avoid the problem.)