Chapter 7: Object-Oriented Design 113
Opening and Closing Accounts
File Account.java (see previous exercise) contains a definition for a simple bank account class with methods to withdraw,
deposit, get the balance and account number, and return a String representation. Note that the constructor for this class
creates a random account number. Save this class to your directory and study it to see how it works. Then write the following
additional code:
1. Suppose the bank wants to keep track of how many accounts exist.
a. Declare a private static integer variable numAccounts to hold this value. Like all instance and static variables, it will
be initialized (to 0, since it’s an int) automatically.
2. Add a method void close() to your Account class. This method should close the current account by appending
3. Add a static method Account consolidate(Account acct1, Account acct2) to your Account class that creates a new
account whose balance is the sum of the balances in acct1 and acct2 and closes acct1 and acct2. The new account should
be returned. Two important rules of consolidation:
4. Write a test program that prompts for and reads in three names and creates an account with an initial balance of $ 100 for
each. Print the three accounts, then close the first account and try to consolidate the second and third into a new account.
Now print the accounts again, including the consolidated one if it was created.
//************************************************************
// TestAccounts1
// A simple program to test the numAccts method of the
// Account class.
//************************************************************
import java.util.Scanner;
System.out.println(“How many accounts would you like to create?”); int num =
Chapter 7: Object-Oriented Design 115
Counting Transactions
File Account.java (see A Flexible Account Class exercise) contains a definition for a simple bank account class with
methods to withdraw, deposit, get the balance and account number, and return a String representation. Note that the
constructor for this class creates a random account number. Save this class to your directory and study it to see how it works.
Now modify it to keep track of the total number of deposits and withdrawals (separately) for each day, and the total amount
deposited and withdrawn. Write code to do this as follows:
1. Add four private static variables to the Account class, one to keep track of each value above (number and total amount of
3. Modify the withdraw and deposit methods to update the appropriate static variables at each withdrawal and deposit
4. File ProcessTransactions.java contains a program that creates and initializes two Account objects and enters a loop that
allows the user to enter transactions for either account until asking to quit. Modify this program as follows:
After the loop, print the total number of deposits and withdrawals and the total amount of each. You will need to use
the Account methods that you wrote above. Test your program.
Imagine that this loop contains the transactions for a single day. Embed it in a loop that allows the transactions to be
recorded and counted for many days. At the beginning of each day print the summary for each account, then have
the user enter the transactions for the day. When all of the transactions have been entered, print the total numbers
and amounts (as above), then reset these values to 0 and repeat for the next day. Note that you will need to add
methods to reset the variables holding the numbers and amounts of withdrawals and deposits to the Account class.
Think: should these be static or instance methods?
//************************************************************
import java.util.Scanner;
public class ProcessTransactions
{
public static void main(String[] args){
Account acct1, acct2; //two test accounts
String keepGoing = “y”; //more transactions?
acct1.printSummary();
System.out.println();
acct2.printSummary();
116 Chapter 7: Object-Oriented Design
while (keepGoing.equals(“y”) || keepGoing.equals(“y”))
{
//get account number, what to do, and amount
System.out.print(“\nEnter the number of the account you would like
to access: “);
acctNumber = scan.nextLong();
System.out.print(“Would you like to make a deposit (D) or withdrawal
(W) ? “);
acct1.withdraw(amount);
else if (action.equals(“d”) || action.equals(“D”))
acct1.deposit(amount);
else
acct1.withdraw(amount);
else if (action.equals(“d”) || action.equals(“D”))
acct1.deposit(amount);
else
System.out.println( “Sorry, invalid action. “);
else
System.out.println( “Sorry, invalid account number. “);
else
}
}
Transfering Funds
File Account.java (see A Flexible Account Class exercise) contains a definition for a simple bank account class with
methods to withdraw, deposit, get the balance and account number, and print a summary. Save it to your directory and study
it to see how it works. Then write the following additional code:
1. Add a method public void transfer(Account acct, double amount) to the Account class that allows the user to transfer
funds from one bank account to another. If acct1 and acct2 are Account objects, then the call
2. Write a class TransferTest with a main method that creates two bank account objects and enters a loop that does the
following:
3. Add a static method to the Account class that lets the user transfer money between two accounts without going through
either account. You can (and should) call the method transfer just like the other one – you are overloading this method.
Your new method should take two Account objects and an amount and transfer the amount from the first account to the
second account. The signature will look like this:
public static void transfer(Account acct1, Account acct2, double amount)
Random Walks
In this lab you will develop a class that models a random walk and write two client programs that use the class. A random
walk is basically a sequence of steps in some enclosed space where the direction of each step is random. The walk terminates
either when a maximum number of steps has been taken or a step goes outside of the boundary of the space. Random walks
are used to model physical phenomena such as the motion of molecules and economic phenomena such as stock prices.
We will assume that the random walk takes place on a square grid with the point (0,0) at the center. The boundary of the
square will be a single integer that represents the maximum x and y coordinate for the current position on the square (so for a
boundary value of 10, both the x and y coordinates can vary from -10 to 10, inclusive). Each step will be one unit up, one unit
down, one unit to the left, or one unit to the right. (No diagonal movement.)
The RandomWalk class will have the following instance data (all type int):
the x coordinate of the current position
the y coordinate of the current position
Create a new file RandomWalk.java. You’ll define the RandomWalk class incrementally testing each part as you go.
1. First declare the instance data (as described above) and add the following two constructors and toString method.
RandomWalk (int max, int edge) – Initializes the RandomWalk object. The maximum number of steps and
2. Compile what you have so far then open the file TestWalk.java. This file will be used to test your RandomWalk
methods. So far it prompts the user to enter a boundary, a maximum number of steps, and the x and y coordinates of
3. Next add the following method to the RandomWalk class: void takeStep(). This method simulates taking a single
4. Add a for loop to TestWalk.java to have each of your RandomWalk objects take 5 steps. Print out each object after
each step so you can see what is going on. Compile and run the program to make sure it is correct so far.
5. Now add to RandomWalk.java the following two methods. Each should be a single return statement that returns the
value of a boolean expression.
Chapter 7: Object-Oriented Design 119
boolean inBounds()returns true if the current position is on the square (include the boundary as part of the
square); returns false otherwise.
6. Add to the RandomWalk class a method named walk that has no parameters and returns nothing. Its job is to
7. Add to TestWalk.java a statement to instantiate a RandomWalk object with a boundary of 10 and 200 as the
maximum number of steps. (You may want to comment out most of the code currently in TestWalk — especially the
8. Now write a client program in a file named DrunkenWalk.java. The program should simulate a drunk staggering
randomly on some sort of platform (imagine a square dock in the middle of a lake). The goal of the program is to
have the program simulate the walk many times (because of randomness each walk is different) and count the
9. Now write a second client program in a file named Collisions.java. This program should simulate two particles
moving in space. Its goal is to determine the number of times the two particles collide (occupy exactly the same
position after the same number of steps — the steps could be thought of as simulating time). We’ll assume the
particles are in a very large space so use a large number for the boundary (such as 2,000,000). Use 100,000 for the
10. In your Collisions.java program the condition to determine if the points are at the same position is a bit cumbersome.
This is something that would be best put in a separate method. Add a static method to Collisions.java (after the main
11. In using random walks to simulate behavior it is often of interest to know how far away from the origin the object
gets as it moves.
120 Chapter 7: Object-Oriented Design
num2) and returns the largest of the two.
c. Add code to takeStep to update maxDistance. This can be done in a single statement using the max method
— the new value of maxDistance should be the maximum of 1) the old value of maxDistance, and 2) the
current distance to the origin. Note that if the current point is (-3, 15) the distance to the origin is 15; if the
current point is (-10, 7) the distance to the origin is 10. Remember that Math.abs returns the absolute value
of a number.
d. Finally add an accessor method to return that distance so a client program can access it:
public int getMaxDistance()
// ************************************************************
// TestWalk.java
import java.util.Scanner;
public class TestWalk
{
public static void main (String[] args)
{
int maxSteps; // maximum number of steps in a walk
int maxCoord; // the maximum x and y coordinate
int x, y; // starting x and y coordinates for a walk
Scanner scan = new Scanner(System.in);
}
}
Chapter 7: Object-Oriented Design 121
Telephone Keypad
Files Telephone.java and TelephonePanel.java contain the skeleton for a program to lay out a GUI that looks like telephone
keypad with a title that says “Your Telephone!!”. Save these files to your directory. Telephone.java is complete, but
TelephonePanel.java is not.
1. Using the comments as a guide, add code to TelephonePanel.java to create the GUI. Some things to consider:
a. TelephonePanel (the current object, which is a JPanel) should get a BorderLayout to make it easy to
separate the title from the keypad. The title will go in the north area and the keypad will go in the center
2. Compile and run Telephone.java. You should get a small keypad and title. Grow the window (just drag the corner) and
see how the GUI changes – everything grows proportionately.
3. Note that the title is not centered, but it would look nicer if it were. One way to do this is to create a new JPanel, add the
title label to it, then add the new JPanel to the north area of the TelephonePanel (instead of adding the label directly).
This works because the default layout for a JPanel is a centered FlowLayout, and the JPanel itself will expand to fill the
whole north area. Modify your program in this way so that the title is centered.
//************************************************************
frame.getContentPane().add(new TelephonePanel());
frame.pack();
frame.setVisible(true);
}
}
122 Chapter 7: Object-Oriented Design
//************************************************************
// TelephonePanel.java
//
public class TelephonePanel extends JPanel
{
public TelephonePanel()
{
//set BorderLayout for this panel
//create a JLabel with “Your Telephone” title