Tải bản đầy đủ (.pdf) (111 trang)

Java Concepts 5th Edition and 6th phần 8 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1016.96 KB, 111 trang )

Java Concepts, 5th Edition
99 {
100 assert state == TRANSACT;
101 return currentAccount.getBalance();
102 }
103
104 /**
105Moves back to the previous state.
106 */
107 public void back()
108 {
109 if (state == TRANSACT)
110 state = ACCOUNT;
111 else if (state == ACCOUNT)
112 state = PIN;
113 else if (state == PIN)
114 state = START;
115 }
116
117 /**
118Gets the current state of this ATM.
119 @return the current state
120 */
121 public int getState()
122 {
123 return state;
124 }
125
126 private int state;
127 private int customerNumber;
128 private Customer currentCustomer;


129 private BankAccount currentAccount;
130 private Bank theBank;
131
132 public static final int START = 1;
133 public static final int PIN = 2;
134 public static final int ACCOUNT = 3;
135 public static final int TRANSACT = 4;
136
137 public static final int CHECKING = 1;
138 public static final int SAVINGS = 2;
139 }
566
567
Chapter 12 Object-Oriented Design Page 51 of 77
Java Concepts, 5th Edition
ch12/atm/Bank.java
1 import java.io.FileReader;
2 import java.io.IOException;
3 import java.util.ArrayList;
4 import java.util.Scanner;
5
6 /**
7A bank contains customers with bank accounts.
8 */
9 public class Bank
10 {
11 /**
12Constructs a bank with no customers.
13 */
14 public Bank()

15 {
16 customers = new ArrayList<Customer>();
17 }
18
19 /**
20Reads the customer numbers and pins
21and initializes the bank accounts.
22 @param filename the name of the customer file
23 */
24 public void readCustomers(String filename)
25 throws IOException
26 {
27 Scanner in = new Scanner(new
FileReader(filename));
28 while (in.hasNext())
29 {
30 int number = in.nextInt();
31 int pin = in.nextInt();
32 Customer c = new Customer(number,
pin);
33 addCustomer(c);
34 }
35 in.close();
36 }
37
567
568
Chapter 12 Object-Oriented Design Page 52 of 77
Java Concepts, 5th Edition
38 /**

39Adds a customer to the bank.
40 @param c the customer to add
41 */
42 public void addCustomer(Customer c)
43 {
44 customers.add(c);
45 }
46
47 /**
48Finds a customer in the bank.
49 @param aNumber a customer number
50 @param aPin a personal identification number
51 @return the matching customer, or null if no customer
52matches
53 */
54 public Customer findCustomer(int aNumber,
int aPin)
55 {
56 for (Customer c : customers)
57 {
58 if (c.match(aNumber, aPin))
59 return c;
60 }
61 return null;
62 }
63
64 private ArrayList<Customer> customers;
65 }
ch12/atm/Customer.java
1 /**

2A bank customer with a checking and a savings account.
3 */
4 public class Customer
5 {
6 /**
7Constructs a customer with a given number and PIN.
8 @param aNumber the customer number
Chapter 12 Object-Oriented Design Page 53 of 77
Java Concepts, 5th Edition
9 @param aPinthe personal identification number
10 */
11 public Customer(int aNumber, int aPin)
12 {
13 customerNumber = aNumber;
14 pin = aPin;
15 checkingAccount = new BankAccount();
16 savingsAccount = new BankAccount();
17 }
18
19 /**
20Tests if this customer matches a customer number
21and PIN.
22 @param aNumber a customer number
23 @param aPin a personal identification number
24 @return true if the customer number and PIN match
25 */
26 public boolean match(int aNumber, int aPin)
27 {
28 return customerNumber == aNumber && pin
== aPin;

29 }
30
31 /**
32Gets the checking account of this customer.
33 @return the checking account
34 */
35 public BankAccount getCheckingAccount()
36 {
37 return checkingAccount;
38 }
39
40 /**
41Gets the savings account of this customer.
42 @return the checking account
43 */
44 public BankAccount getSavingsAccount()
45 {
46 return savingsAccount;
47 }
48
568
569
Chapter 12 Object-Oriented Design Page 54 of 77
Java Concepts, 5th Edition
49 private int customerNumber;
50 private int pin;
51 private BankAccount checkingAccount;
52 private BankAccount savingsAccount;
53 }
The following class implements a console user interface for the ATM.

ch12/atm/ATMSimulator.java
1 import java.io.IOException;
2 import java.util.Scanner;
3
4 /**
5A text-based simulation of an automatic teller machine.
6 */
7 public class ATMSimulator
8 {
9 public static void main(String[] args)
10 {
11 ATM theATM;
12 try
13 {
14 Bank theBank = new Bank();
15 theBank.readCustomers(“customers.txt”);
16 theATM = new ATM(theBank);
17 }
18 catch(IOException e)
19 {
20 System.out.println(“Error opening
accounts file.”);
21 return;
22 }
23
24 Scanner in = new Scanner(System.in);
25
26 while (true)
27 {
28 int state = theATM.getState();

29 if (state == ATM.START)
30 {
569
570
Chapter 12 Object-Oriented Design Page 55 of 77
Java Concepts, 5th Edition
31 System.out.print(“Enter customer
number: ”);
32 int number = in.nextInt();
33 theATM.setCustomerNumber(number);
34 }
35 else if (state == ATM.PIN)
36 {
37 System.out.print(“Enter PIN: ”);
38 int pin = in.nextInt();
39 theATM.selectCustomer(pin);
40 }
41 else if (state == ATM.ACCOUNT)
42 {
43 System.out.print(“A=Checking,
B=Savings, C=Quit: ”);
44 String command = in.next();
45 if (command.equalsIgnoreCase(“A”))
46 theATM.selectAccount(ATM.CHECKING);
47 else if
(command.equalsIgnoreCase(“B”))
48 theATM.selectAccount(ATM.SAVINGS);
49 else if
(command.equalsIgnoreCase(“C”))
50 theATM.reset();

51 else
52 System.out.println(“Illegal
input!”);
53 }
54 else if (state == ATM.TRANSACT)
55 {
56 System.out.println(“Balance=” +
theATM.getBalance());
57 System.out.print(“A=Deposit,
B=Withdrawal, C=Cancel: ”);
58 String command = in.next();
59 if (command.equalsIgnoreCase(“A”))
60 {
61 System.out.print(“Amount: ”);
62 double amount =
in.nextDouble();
63 theATM.deposit(amount);
64 theATM.back();
65 }
Chapter 12 Object-Oriented Design Page 56 of 77
Java Concepts, 5th Edition
66 else if
(command.equalsIgnoreCase(“B”))
67 {
68 System.out.print(“Amount: ”);
69 double amount =
in.nextDouble();
70 theATM.withdraw(amount);
71 theATM.back();
72 }

73 else if
(command.equalsIgnoreCase(“C”))
74 theATM.back();
75 else
76 System.out.println(“Illegal
input!”);
77 }
78 }
79 }
80 }
Output
Enter account number: 1
Enter PIN: 1234
A=Checking, B=Savings, C=Quit: A
Balance=0.0
A=Deposit, B=Withdrawal, C=Cancel: A
Amount: 1000
A=Checking, B=Savings, C=Quit: C
. . .
Here are the user interface classes for the GUI version of the user interface.
ch12/atm/ATMViewer.java
1 import java.io.IOException;
2 import javax.swing.JFrame;
3 import javax.swing.JOptionPane;
4
5 /**
6A graphical simulation of an automatic teller machine.
7 */
8 public class ATMViewer
570

571
Chapter 12 Object-Oriented Design Page 57 of 77
Java Concepts, 5th Edition
9 {
10 public static void main(String[] args)
11 {
12 ATM theATM;
13
14 try
15 {
16 Bank theBank = new Bank();
17 theBank.readCustomers(“customers.txt”);
18 theATM = new ATM(theBank);
19 }
20 catch(IOException e)
21 {
22 JOptionPane.showMessageDialog(null,
23 “Error opening accounts
file.”);
24 return;
25 }
26
27 JFrame frame = new ATMFrame(theATM);
28 frame.setTitle(“First National Bank of
Java”);
29 frame.setDefaultCloseOperation(JFrame.EXIT_
ON
30 frame.setVisible(true);
31 }
32 }

ch12/atm/ATMFrame.java
1 import java.awt.FlowLayout;
2 import java.awt.GridLayout;
3 import java.awt.event.ActionEvent;
4 import java.awt.event.ActionListener;
5 import javax.swing.JButton;
6 import javax.swing.JFrame;
7 import javax.swing.JPanel;
8 import javax.swing.JTextArea;
9
10 /**
11A frame displaying the components of an ATM.
12 */
13 public class ATMFrame extends JFrame
571
572
Chapter 12 Object-Oriented Design Page 58 of 77
Java Concepts, 5th Edition
14 {
15 /**
16Constructs the user interface of the ATM frame.
17 */
18 public ATMFrame(ATM anATM)
19 {
20 theATM = anATM;
21
22// Construct components
23 pad = new KeyPad();
24
25 display = new JTextArea(4, 20);

26
27 aButton = new JButton(“ A ”);
28 aButton.addActionListener(new
AButtonListener());
29
30 bButton = new JButton(“ B ”);
31 bButton.addActionListener(new
BButtonListener());
32
33 cButton = new JButton(“ C ”);
34 cButton.addActionListener(new
CButtonListener());
35
36// Add components
37
38 JPanel buttonPanel = new JPanel();
39 buttonPanel.add(aButton);
40 buttonPanel.add(bButton);
41 buttonPanel.add(cButton);
42
43 setLayout(new FlowLayout());
44 add(pad);
45 add(display);
46 add(buttonPanel);
47 showState();
48
49 setSize(FRAME_WIDTH, FRAME_HEIGHT);
50 }
51
52 /**

572
573
Chapter 12 Object-Oriented Design Page 59 of 77
Java Concepts, 5th Edition
53Updates display message.
54 */
55 public void showState()
56 {
57 int state = theATM.getState();
58 pad.clear();
59 if (state == ATM.START)
60 display.setText(“Enter customer
number\nA = OK”);
61 else if (state == ATM.PIN)
62 display.setText(“Enter PIN\nA = OK”);
63 else if (state == ATM.ACCOUNT)
64 display.setText(“Select Account\n”
65 + “A = Checking\nB =
Savings\nC = Exit”);
66 else if (state == ATM.TRANSACT)
67 display.setText(“Balance = ”
68 + theATM.getBalance()
69 + “\nEnter amount and select
transaction\n”
70 + “A = Withdraw\nB =
Deposit\nC = Cancel”);
71 }
72
73 private class AButtonListener implements
ActionListener

74 {
75 public void actionPerformed(ActionEvent
event)
76 {
77 int state = theATM.getState();
78 if (state == ATM.START)
79 theATM.setCustomerNumber((int)
pad.getValue());
80 else if (state == ATM.PIN)
81 theATM.selectCustomer((int)
pad.getValue());
82 else if (state == ATM.ACCOUNT)
83 theATM.selectAccount(ATM.CHECKING);
84 else if (state == ATM.TRANSACT)
85 {
86 theATM.withdraw(pad.getValue());
87 theATM.back();
Chapter 12 Object-Oriented Design Page 60 of 77
Java Concepts, 5th Edition
88 }
89 showState();
90 }
91 }
92
93 private class BButtonListener implements
ActionListener
94 {
95 public void actionPerformed(ActionEvent
event)
96 {

97 int state = theATM.getState();
98 if (state == ATM.ACCOUNT)
99 theATM.selectAccount(ATM.SAVINGS);
100 else if (state == ATM.TRANSACT)
101 {
102 theATM.deposit(pad.getValue());
103 theATM.back();
104 }
105 showState();
106 }
107 }
108
109 private class CButtonListener implements
ActionListener
110 {
111 public void actionPerformed(ActionEvent
event)
112 {
113 int state = theATM.getState();
114 if (state == ATM.ACCOUNT)
115 theATM.reset();
116 else if (state == ATM.TRANSACT)
117 theATM.back();
118 showState();
119 }
120 }
121
122 private JButton aButton;
123 private JButton bButton;
124 private JButton cButton;

125
126 private KeyPad pad;
573
574
Chapter 12 Object-Oriented Design Page 61 of 77
Java Concepts, 5th Edition
127 private JTextArea display;
128
129 private ATM theATM;
130
131 private static final int FRAME_WIDTH = 300;
132 private static final int FRAME_HEIGHT =
300;
133 }
This class uses layout managers to arrange the text field and the keypad buttons.
See Chapter 18 for more information about layout managers.
ch12/atm/KeyPad.java
1 import java.awt.BorderLayout;
2 import java.awt.GridLayout;
3 import java.awt.event.ActionEvent;
4 import java.awt.event.ActionListener;
5 import javax.swing.JButton;
6 import javax.swing.JPanel;
7 import javax.swing.JTextField;
8
9 /**
10A component that lets the user enter a number, using
11a keypad labeled with digits.
12 */
13 public class KeyPad extends JPanel

14 {
15 /**
16Constructs the keypad panel.
17 */
18 public KeyPad()
19 {
20 setLayout(new BorderLayout());
21
22 // Add display field
23
24 display = new JTextField();
25 add(display, “North”);
26
27 // Make button panel
574
575
Chapter 12 Object-Oriented Design Page 62 of 77
Java Concepts, 5th Edition
28
29 buttonPanel = new JPanel();
30 buttonPanel.setLayout(new
GridLayout(4, 3));
31
32 //Add digit buttons
33
34 addButton(“7”);
35 addButton(“8”);
36 addButton(“9”);
37 addButton(“4”);
38 addButton(“5”);

39 addButton(“6”);
40 addButton(“1”);
41 addButton(“2”);
42 addButton(“3”);
43 addButton(“0”);
44 addButton(“.”);
45
46 // Add clear entry button
47
48 clearButton = new JButton(“CE”);
49 buttonPanel.add(clearButton);
50
51 class ClearButtonListener implements
ActionListener
52 {
53 public void
actionPerformed(ActionEvent event)
54 {
55 display.setText(“”);
56 }
57 }
58 ActionListener listener = new
ClearButtonListener();
59
60 clearButton.addActionListener(new
61 ClearButtonListener());
62
63 add(buttonPanel, “Center”);
64 }
65

66 /**
575
576
Chapter 12 Object-Oriented Design Page 63 of 77
Java Concepts, 5th Edition
67Adds a button to the button panel.
68 @param label the button label
69 */
70 private void addButton(final String label)
71 {
72 class DigitButtonListener implements
ActionListener
73 {
74 public void
actionPerformed(ActionEvent event)
75 {
76
77 // Don't add two decimal points
78 if (label.equals(“.”)
79 &&
display.getText().indexOf(“.”) != -1)
80 return;
81
82 // Append label text to button
83 display.setText(display.getText()
+ label);
84 }
85 }
86
87 JButton button = new JButton (label);

88 buttonPanel.add(button);
89 ActionListener listener = new
DigitButtonListener();
90 button.addActionListener(listener);
91 }
92
93 /**
94Gets the value that the user entered.
95 @return the value in the text field of the keypad
96 */
97 public double getValue()
98 {
99 return
Double.parseDouble(display.getText());
100 }
101
102 /**
Chapter 12 Object-Oriented Design Page 64 of 77
Java Concepts, 5th Edition
103Clears the display.
104 */
105 public void clear()
106 {
107 display.setText(“”);
108 }
109
110 private JPanel buttonPanel;
111 private JButton clearButton;
112 private JTextField display;
113 }

In this chapter, you learned a systematic approach for building a relatively complex
program. However, object-oriented design is definitely not a spectator sport. To
really learn how to design and implement programs, you have to gain experience by
repeating this process with your own projects. It is quite possible that you don't
immediately home in on a good solution and that you need to go back and
reorganize your classes and responsibilities. That is normal and only to be expected.
The purpose of the object-oriented design process is to spot these problems in the
design phase, when they are still easy to rectify, instead of in the implementation
phase, when massive reorganization is more difficult and time consuming.
SELF CHECK
12. Why does the Bank class in this example not store an array list of
bank accounts?
13. Suppose the requirements change—you need to save the current
account balances to a file after every transaction and reload them
when the program starts. What is the impact of this change on the
design?
RANDOM FACT 12.2: Software Development–Art or
Science?
There has been a long discussion whether the discipline of computing is a
science or not. We call the field “computer science”, but that doesn't mean much.
576
577
Chapter 12 Object-Oriented Design Page 65 of 77
Java Concepts, 5th Edition
Except possibly for librarians and sociologists, few people believe that library
science and social science are scientific endeavors.
A scientific discipline aims to discover certain fundamental principles dictated
by the laws of nature. It operates on the scientific method: by posing hypotheses
and testing them with experiments that are repeatable by other workers in the
field. For example, a physicist may have a theory on the makeup of nuclear

particles and attempt to confirm or refute that theory by running experiments in a
particle collider. If an experiment cannot be confirmed, such as the “cold fusion”
research in the early 1990s, then the theory dies a quick death.
Some software developers indeed run experiments. They try out various methods
of computing certain results or of configuring computer systems, and measure
the differences in performance. However, their aim is not to discover laws of
nature.
Some computer scientists discover fundamental principles. One class of
fundamental results, for instance, states that it is impossible to write certain
kinds of computer programs, no matter how powerful the computing equipment
is. For example, it is impossible to write a program that takes as its input any two
Java program files and as its output prints whether or not these two programs
always compute the same results. Such a program would be very handy for
grading student homework, but nobody, no matter how clever, will ever be able
to write one that works for all input files. However, the majority of computer
scientists are not researching the limits of computation.
Some people view software development as an art or craft. A programmer who
writes elegant code that is easy to understand and runs with optimum efficiency
can indeed be considered a good craftsman. Calling it an art is perhaps
far-fetched, because an art object requires an audience to appreciate it, whereas
the program code is generally hidden from the program user.
Others call software development an engineering discipline. Just as mechanical
engineering is based on the fundamental mathematical principles of statics,
computing has certain mathematical foundations. There is more to mechanical
engineering than mathematics, such as knowledge of materials and of project
planning. The same is true for computing. A software engineer needs to know
about planning, budgeting, design, test automation, documentation, and source
577
578
Chapter 12 Object-Oriented Design Page 66 of 77

Java Concepts, 5th Edition
code control, in addition to computer science subjects, such as programming,
algorithm design, and database technologies.
In one somewhat worrisome aspect, software development does not have the
same standing as other engineering disciplines. There is little agreement as to
what constitutes professional conduct in the computer field. Unlike the scientist,
whose main responsibility is the search for truth, the software developer must
strive to satisfy the conflicting demands of quality, safety, and economy.
Engineering disciplines have professional organizations that hold their members
to standards of conduct. The computer field is so new that in many cases we
simply don't know the correct method for achieving certain tasks. That makes it
difficult to set professional standards.
What do you think? From your limited experience, do you consider software
development an art, a craft, a science, or an engineering activity?
CHAPTER SUMMARY
1. The life cycle of software encompasses all activities from initial analysis until
obsolescence.
2. A formal process for software development describes phases of the
development process and gives guidelines for how to carry out the phases.
3. The waterfall model of software development describes a sequential process of
analysis, design, implementation, testing, and deployment.
4. The spiral model of software development describes an iterative process in
which design and implementation are repeated.
5. Extreme Programming is a development methodology that strives for simplicity
by removing formal structure and focusing on best practices.
6. In object-oriented design, you discover classes, determine the responsibilities
of classes, and describe the relationships between classes.
7. A CRC card describes a class, its responsibilities, and its collaborating classes.
Chapter 12 Object-Oriented Design Page 67 of 77
Java Concepts, 5th Edition

8. Inheritance (the is-a relationship) is sometimes inappropriately used when the
has-a relationship would be more appropriate.
9. Aggregation (the has-a relationship) denotes that objects of one class contain
references to objects of another class.
10. Dependency is another name for the “uses” relationship.
11. You need to be able to distinguish the UML notations for inheritance, interface
implementation, aggregation, and dependency.
12. Use javadoc comments (with the method bodies left blank) to record the
behavior of classes.
FURTHER READING
1. Grady Booch, James Rumbaugh, and Ivar Jacobson, The Unified Modeling
Language User Guide, Addison-Wesley, 1999.
2. Kent Beck, Extreme Programming Explained, Addison-Wesley, 1999.
3. W. H. Sackmann, W. J. Erikson, and E. E. Grant, “Exploratory
Experimental Studies Comparing Online and Offline Programming
Performance”, Communications of the ACM, vol. 11, no. 1 (January 1968),
pp. 3–11.
4. F. Brooks, The Mythical Man-Month, Addison-Wesley, 1975.
REVIEW EXERCISES
★ Exercise R12.1. What is the software life cycle?
★★ Exercise R12.2. List the steps in the process of object-oriented design that
this chapter recommends for student use.
★ Exercise R12.3. Give a rule of thumb for how to find classes when
designing a program.
★ Exercise R12.4. Give a rule of thumb for how to find methods when
designing a program.
578
579
Chapter 12 Object-Oriented Design Page 68 of 77
Java Concepts, 5th Edition

★★ Exercise R12.5. After discovering a method, why is it important to
identify the object that is responsible for carrying out the action?
★ Exercise R12.6. What relationship is appropriate between the following
classes: aggregation, inheritance, or neither?
a. University–Student
b. Student–TeachingAssistant
c. Student–Freshman
d. Student–Professor
e. Car–Door
f. Truck–Vehicle
g. Traffic–TrafficSign
h. TrafficSign–Color
★★ Exercise R12.7. Every BMW is a vehicle. Should a class BMW inherit from
the class Vehicle? BMW is a vehicle manufacturer. Does that mean that
the class BMW should inherit from the class VehicleManufacturer?
★★ Exercise R12.8. Some books on object-oriented programming recommend
using inheritance so that the class Circle extends the class Point. Then
the Circle class inherits the setLocation method from the Point
superclass. Explain why the setLocation method need not be redefined
in the subclass. Why is it nevertheless not a good idea to have Circle
inherit from Point? Conversely, would inheriting Point from Circle
fulfill the is-a rule? Would it be a good idea?
★ Exercise R12.9. Write CRC cards for the Coin and CashRegister
classes described in Section 8.2.
★ Exercise R12.10. Write CRC cards for the Bank and BankAccount
classes in Section 7.2.
579
580
Chapter 12 Object-Oriented Design Page 69 of 77
Java Concepts, 5th Edition

★★ Exercise R12.11. Draw a UML diagram for the Coin and
CashRegister classes described in Section 8.2.
★★★ Exercise R12.12. A file contains a set of records describing countries.
Each record consists of the name of the country, its population, and its
area. Suppose your task is to write a program that reads in such a file and
prints
• The country with the largest area
• The country with the largest population
• The country with the largest population density (people per square
kilometer)
Think through the problems that you need to solve. What classes and
methods will you need? Produce a set of CRC cards, a UML diagram,
and a set of javadoc comments.
★★★ Exercise R12.13. Discover classes and methods for generating a student
report card that lists all classes, grades, and the grade point average for a
semester. Produce a set of CRC cards, a UML diagram, and a set of
javadoc comments.
★★★ Exercise R12.14. Consider a quiz grading system that grades student
responses to quizzes. A quiz consists of questions. There are different
types of questions, including essay questions and multiple-choice
questions. Students turn in submissions for quizzes, and the grading
system grades them. Draw a UML diagram for classes Quiz,
Question, EssayQuestion, MultipleChoiceQuestion,
Student, and Submission.
Additional review exercises are available in WileyPLUS.
PROGRAMMING EXERCISES
★★ Exercise P12.1. Enhance the invoice-printing program by providing for
two kinds of line items: One kind describes products that are purchased in
Chapter 12 Object-Oriented Design Page 70 of 77
Java Concepts, 5th Edition

certain numerical quantities (such as “3 toasters”), another describes a
fixed charge (such as “shipping: $5.00”). Hint: Use inheritance. Produce a
UML diagram of your modified implementation.
★★ Exercise P12.2. The invoice-printing program is somewhat unrealistic
because the formatting of the LineItem objects won't lead to good visual
results when the prices and quantities have varying numbers of digits.
Enhance the format method in two ways: Accept an int[] array of
column widths as a parameter. Use the NumberFormat class to format
the currency values.
★★ Exercise P12.3. The invoice-printing program has an unfortunate flaw—it
mixes “business logic”, the computation of total charges, and
“presentation”, the visual appearance of the invoice. To appreciate this
flaw, imagine the changes that would be necessary to draw the invoice in
HTML for presentation on the Web. Reimplement the program, using a
separate InvoiceFormatter class to format the invoice. That is, the
Invoice and LineItem methods are no longer responsible for
formatting. However, they will acquire other responsibilities, because the
InvoiceFormatter class needs to query them for the values that it
requires.
★★★ Exercise P12.4. Write a program that teaches arithmetic to your younger
brother. The program tests addition and subtraction. In level 1 it tests
only addition of numbers less than 10 whose sum is less than 10. In level
2 it tests addition of arbitrary one-digit numbers. In level 3 it tests
subtraction of one-digit numbers with a non-negative difference.
Generate random problems and get the player input. The player gets up
to two tries per problem. Advance from one level to the next when the
player has achieved a score of five points.
★★★ Exercise P12.5. Design a simple e-mail messaging system. A message
has a recipient, a sender, and a message text. A mailbox can store
messages. Supply a number of mailboxes for different users and a user

interface for users to log in, send messages to other users, read their own
messages, and log out. Follow the design process that was described in
this chapter.
580
581
Chapter 12 Object-Oriented Design Page 71 of 77
Java Concepts, 5th Edition
★★ Exercise P12.6. Write a program that simulates a vending machine.
Products can be purchased by inserting coins with a value at least equal to
the cost of the product. A user selects a product from a list of available
products, adds coins, and either gets the product or gets the coins returned
if insufficient money was supplied or if the product is sold out. The
machine does not give change if too much money was added. Products can
be restocked and money removed by an operator. Follow the design
process that was described in this chapter. Your solution should include a
class VendingMachine that is not coupled with the Scanner or
PrintStream classes.
★★★ Exercise P12.7. Write a program to design an appointment calendar. An
appointment includes the date, starting time, ending time, and a
description; for example,
Dentist 2007/10/1 17:30 18:30
CS1 class 2007/10/2 08:30 10:00
Supply a user interface to add appointments, remove canceled
appointments, and print out a list of appointments for a particular day.
Follow the design process that was described in this chapter. Your
solution should include a class AppointmentCalendar that is not
coupled with the Scanner or PrintStream classes.
★★★ Exercise P12.8. Airline seating. Write a program that assigns seats on an
airplane. Assume the airplane has 20 seats in first class (5 rows of 4 seats
each, separated by an aisle) and 90 seats in economy class (15 rows of 6

seats each, separated by an aisle). Your program should take three
commands: add passengers, show seating, and quit. When passengers are
added, ask for the class (first or economy), the number of passengers
traveling together (1 or 2 in first class; 1 to 3 in economy), and the
seating preference (aisle or window in first class; aisle, center, or
window in economy). Then try to find a match and assign the seats. If no
match exists, print a message. Your solution should include a class
Airplane that is not coupled with the Scanner or PrintSream
classes. Follow the design process that was described in this chapter.
581
582
Chapter 12 Object-Oriented Design Page 72 of 77
Java Concepts, 5th Edition
★★ Exercise P12.9. Modify the implementations of the class in the ATM
example so that the bank manages a collection of bank accounts and a
separate collection of customers. Allow joint accounts in which some
accounts can have more than one customer.
★★★ Exercise P12.10. Write a program that administers and grades quizzes.
A quiz consists of questions. There are four types of questions: text
questions, number questions, choice questions with a single answer, and
choice questions with multiple answers. When grading a text question,
ignore leading or trailing spaces and letter case. When grading a numeric
question, accept a response that is approximately the same as the answer.
A quiz is specified in a text file. Each question starts with a letter
indicating the question type (T, N, S, M), followed by a line containing
the question text. The next line of a non-choice question contains the
answer. Choice questions have a list of choices that is terminated by a
blank line. Each choice starts with + (correct) or − (incorrect). Here is a
sample file:
T

Which Java keyword is used to define a subclass?
extends
S
What is the original name of the Java language?
- *7
- C
+ Oak
- Gosling
M
Which of the following types are supertypes of
Rectangle?
- PrintStream
+ Shape
+ RectangularShape
+ Object
- String
N
What is the square root of 2?
1.41421356
Chapter 12 Object-Oriented Design Page 73 of 77
Java Concepts, 5th Edition
Your program should read in a quiz file, prompt the user for responses to
all questions, and grade the responses. Follow the design process that
was described in this chapter.
★★★G Exercise P12.11. Implement a program to teach your baby sister
to read the clock. In the game, present an analog clock, such as the one in
Figure 12. Generate random times and display the clock. Accept guesses
from the player. Reward the player for correct guesses. After two
incorrect guesses, display the correct answer and make a new random
time. Implement several levels of play. In level 1, only show full hours.

In level 2, show quarter hours. In level 3, show five-minute multiples,
and in level 4, show any number of minutes. After a player has achieved
five correct guesses at one level, advance to the next level.
Figure 12
An Analog Clock
★★★G Exercise P12.12. Write a program that can be used to design a
suburban scene, with houses, streets, and cars. Users can add houses and
cars of various colors to a street. Write more specific requirements that
include a detailed description of the user interface. Then, discover
classes and methods, provide UML diagrams, and implement your
program.
★★★G Exercise P12.13. Write a simple graphics editor that allows
users to add a mixture of shapes (ellipses, rectangles, and lines in
different colors) to a panel. Supply commands to load and save the
582
583
Chapter 12 Object-Oriented Design Page 74 of 77
Java Concepts, 5th Edition
picture. Discover classes, supply a UML diagram, and implement your
program.
Additional programming exercises are available in WileyPLUS.
PROGRAMMING PROJECTS
★★★ Project 12.1. Produce a requirements document for a program that
allows a company to send out personalized mailings, either by e-mail or
through the postal service. Template files contain the message text,
together with variable fields (such as Dear [Title] [Last Name] …). A
database (stored as a text file) contains the field values for each recipient.
Use HTML as the output file format. Then design and implement the
program.
★★★ Project 12.2. Write a tic-tac-toe game that allows a human player to play

against the computer. Your program will play many turns against a
human opponent, and it will learn. When it is the computer's turn, the
computer randomly selects an empty field, except that it won't ever
choose a losing combination. For that purpose, your program must keep
an array of losing combinations. Whenever the human wins, the
immediately preceding combination is stored as losing. For example,
suppose that X = computer and O = human. Suppose the current
combination is
Now it is the human's turn, who will of course choose
583
584
Chapter 12 Object-Oriented Design Page 75 of 77

×