SlideShare a Scribd company logo
ch12/.DS_Store
__MACOSX/ch12/._.DS_Store
ch12/section_1/.DS_Store
__MACOSX/ch12/section_1/._.DS_Store
ch12/section_1/CashRegister.javach12/section_1/CashRegister.j
ava/**
A cash register totals up sales and computes change due.
*/
publicclassCashRegister
{
privatedouble purchase;
privatedouble payment;
/**
Constructs a cash register with no money in it.
*/
publicCashRegister()
{
purchase =0;
payment =0;
}
/**
Records the sale of an item.
@param amount the price of the item
*/
publicvoid addItem(double amount)
{
double newTotal = purchase + amount;
purchase = newTotal;
}
/**
Enters the payment received from the customer; should be c
alled once
for each coin type.
@param coinCount the number of coins
@param coinType the type of the coins in the payment
*/
publicvoid enterPayment(int coinCount,Coin coinType)
{
payment = payment + coinCount * coinType.getValue();
}
/**
Computes the change due and resets the machine for the nex
t customer.
@return the change due to the customer
*/
publicdouble giveChange()
{
double change = payment - purchase;
purchase =0;
payment =0;
return change;
}
}
__MACOSX/ch12/section_1/._CashRegister.java
ch12/section_1/CashRegister.java.html 1 /** 2 A cash
register totals up sales and computes change due. 3 */ 4
public class CashRegister 5 { 6 private double purchase; 7
private double payment; 8 9 /** 10 Constructs a cash
register with no money in it. 11 */ 12 public
CashRegister() 13 { 14 purchase = 0; 15 payment =
0; 16 } 17 18 /** 19 Records the sale of an item. 20
@param amount the price of the item 21 */ 22 public void
addItem(double amount) 23 { 24 double newTotal =
purchase + amount; 25 purchase = newTotal; 26 } 27
28 /** 29 Enters the payment received from the
customer; should be called once 30 for each coin type. 31
@param coinCount the number of coins 32 @param
coinType the type of the coins in the payment 33 */ 34
public void enterPayment(int coinCount, Coin coinType) 35 {
36 payment = payment + coinCount *
coinType.getValue(); 37 } 38 39 /** 40 Computes
the change due and resets the machine for the next customer. 41
@return the change due to the customer 42 */ 43 public
double giveChange() 44 { 45 double change = payment -
purchase; 46 purchase = 0; 47 payment = 0; 48
return change; 49 } 50 }
__MACOSX/ch12/section_1/._CashRegister.java.html
ch12/section_1/CashRegisterTester.javach12/section_1/CashReg
isterTester.java/**
This program tests the CashRegister class.
*/
publicclassCashRegisterTester
{
publicstaticvoid main(String[] args)
{
CashRegister register1 =newCashRegister();
register1.addItem(1.95);
register1.addItem(0.95);
register1.addItem(2.50);
Coin dollar =newCoin(1.0,"Dollar");
Coin quarter =newCoin(0.25,"Quarter");
register1.enterPayment(6, dollar);
register1.enterPayment(3, quarter);
System.out.printf("Change: %.2fn", register1.giveChange());
}
}
__MACOSX/ch12/section_1/._CashRegisterTester.java
ch12/section_1/CashRegisterTester.java.html 1 /** 2 This
program tests the CashRegister class. 3 */ 4 public class
CashRegisterTester 5 { 6 public static void main(String[]
args) 7 { 8 CashRegister register1 = new
CashRegister(); 9 register1.addItem(1.95); 10
register1.addItem(0.95); 11 register1.addItem(2.50); 12
13 Coin dollar = new Coin(1.0, "Dollar"); 14 Coin
quarter = new Coin(0.25, "Quarter"); 15 16
register1.enterPayment(6, dollar); 17
register1.enterPayment(3, quarter); 18 19
System.out.printf("Change: %.2fn", register1.giveChange());
20 } 21 }
__MACOSX/ch12/section_1/._CashRegisterTester.java.html
ch12/section_1/Coin.javach12/section_1/Coin.java/**
A coin with a monetary value.
*/
publicclassCoin
{
privatedouble value;
privateString name;
/**
Constructs a coin.
@param aValue the monetary value of the coin.
@param aName the name of the coin
*/
publicCoin(double aValue,String aName)
{
value = aValue;
name = aName;
}
/**
Gets the coin value.
@return the value
*/
publicdouble getValue()
{
return value;
}
/**
Gets the coin name.
@return the name
*/
publicString getName()
{
return name;
}
}
__MACOSX/ch12/section_1/._Coin.java
ch12/section_1/Coin.java.html 1 /** 2 A coin with a
monetary value. 3 */ 4 public class Coin 5 { 6 private
double value; 7 private String name; 8 9 /** 10
Constructs a coin. 11 @param aValue the monetary value
of the coin. 12 @param aName the name of the coin 13
*/ 14 public Coin(double aValue, String aName) 15 { 16
value = aValue; 17 name = aName; 18 } 19 20 /**
21 Gets the coin value. 22 @return the value 23 */
24 public double getValue() 25 { 26 return value; 27
} 28 29 /** 30 Gets the coin name. 31 @return the
name 32 */ 33 public String getName() 34 { 35
return name; 36 } 37 }
__MACOSX/ch12/section_1/._Coin.java.html
__MACOSX/ch12/._section_1
ch12/section_2/.DS_Store
__MACOSX/ch12/section_2/._.DS_Store
ch12/section_2/ChoiceQuestion.javach12/section_2/ChoiceQues
tion.javaimport java.util.ArrayList;
/**
A question with multiple choices.
*/
publicclassChoiceQuestionextendsQuestion
{
privateArrayList<String> choices;
/**
Constructs a choice question with no choices.
*/
publicChoiceQuestion()
{
choices =newArrayList<String>();
}
/**
Adds an answer choice to this question.
@param choice the choice to add
@param correct true if this is the correct choice, false otherwise
*/
publicvoid addChoice(String choice,boolean correct)
{
choices.add(choice);
if(correct)
{
// Convert choices.size() to string
String choiceString =""+ choices.size();
setAnswer(choiceString);
}
}
publicvoid display()
{
// Display the question text
super.display();
// Display the answer choices
for(int i =0; i < choices.size(); i++)
{
int choiceNumber = i +1;
System.out.println(choiceNumber +": "+ choices.get(i));
}
}
}
__MACOSX/ch12/section_2/._ChoiceQuestion.java
ch12/section_2/ChoiceQuestion.java.html 1 import
java.util.ArrayList; 2 3 /** 4 A question with multiple
choices. 5 */ 6 public class ChoiceQuestion extends Question
7 { 8 private ArrayList<String> choices; 9 10 /** 11
Constructs a choice question with no choices. 12 */ 13
public ChoiceQuestion() 14 { 15 choices = new
ArrayList<String>(); 16 } 17 18 /** 19 Adds an
answer choice to this question. 20 @param choice the
choice to add 21 @param correct true if this is the correct
choice, false otherwise 22 */ 23 public void
addChoice(String choice, boolean correct) 24 { 25
choices.add(choice); 26 if (correct) 27 { 28 //
Convert choices.size() to string 29 String choiceString =
"" + choices.size(); 30 setAnswer(choiceString); 31
} 32 } 33 34 public void display() 35 { 36 //
Display the question text 37 super.display(); 38 //
Display the answer choices 39 for (int i = 0; i <
choices.size(); i++) 40 { 41 int choiceNumber = i +
1; 42 System.out.println(choiceNumber + ": " +
choices.get(i)); 43 } 44 } 45 } 46
__MACOSX/ch12/section_2/._ChoiceQuestion.java.html
ch12/section_2/Question.javach12/section_2/Question.java/**
A question with a text and an answer.
*/
publicclassQuestion
{
privateString text;
privateString answer;
/**
Constructs a question with empty question and answer.
*/
publicQuestion()
{
text ="";
answer ="";
}
/**
Sets the question text.
@param questionText the text of this question
*/
publicvoid setText(String questionText)
{
text = questionText;
}
/**
Sets the answer for this question.
@param correctResponse the answer
*/
publicvoid setAnswer(String correctResponse)
{
answer = correctResponse;
}
/**
Checks a given response for correctness.
@param response the response to check
@return true if the response was correct, false otherwise
*/
publicboolean checkAnswer(String response)
{
return response.equals(answer);
}
/**
Displays this question.
*/
publicvoid display()
{
System.out.println(text);
}
}
__MACOSX/ch12/section_2/._Question.java
ch12/section_2/Question.java.html 1 /** 2 A question with
a text and an answer. 3 */ 4 public class Question 5 { 6
private String text; 7 private String answer; 8 9 /** 10
Constructs a question with empty question and answer. 11 */
12 public Question() 13 { 14 text = ""; 15
answer = ""; 16 } 17 18 /** 19 Sets the question
text. 20 @param questionText the text of this question 21
*/ 22 public void setText(String questionText) 23 { 24
text = questionText; 25 } 26 27 /** 28 Sets the
answer for this question. 29 @param correctResponse the
answer 30 */ 31 public void setAnswer(String
correctResponse) 32 { 33 answer = correctResponse; 34
} 35 36 /** 37 Checks a given response for correctness.
38 @param response the response to check 39 @return
true if the response was correct, false otherwise 40 */ 41
public boolean checkAnswer(String response) 42 { 43
return response.equals(answer); 44 } 45 46 /** 47
Displays this question. 48 */ 49 public void display() 50
{ 51 System.out.println(text); 52 } 53 }
__MACOSX/ch12/section_2/._Question.java.html
ch12/section_2/Quiz.javach12/section_2/Quiz.javaimport java.u
til.ArrayList;
import java.util.Scanner;
/**
A quiz contains a list of questions.
*/
publicclassQuiz
{
privateArrayList<Question> questions;
/**
Constructs a quiz with no questions.
*/
publicQuiz()
{
questions =newArrayList<Question>();
}
/**
Adds a question to this quiz.
@param q the question
*/
publicvoid addQuestion(Question q)
{
questions.add(q);
}
/**
Presents the questions to the user and checks the response.
*/
publicvoid presentQuestions()
{
Scanner in =newScanner(System.in);
for(Question q : questions)
{
q.display();
System.out.print("Your answer: ");
String response = in.nextLine();
System.out.println(q.checkAnswer(response));
}
}
}
__MACOSX/ch12/section_2/._Quiz.java
ch12/section_2/Quiz.java.html 1 import java.util.ArrayList; 2
import java.util.Scanner; 3 4 /** 5 A quiz contains a list
of questions. 6 */ 7 public class Quiz 8 { 9 private
ArrayList<Question> questions; 10 11 /** 12
Constructs a quiz with no questions. 13 */ 14 public
Quiz() 15 { 16 questions = new ArrayList<Question>();
17 } 18 19 /** 20 Adds a question to this quiz. 21
@param q the question 22 */ 23 public void
addQuestion(Question q) 24 { 25 questions.add(q); 26
} 27 28 /** 29 Presents the questions to the user and
checks the response. 30 */ 31 public void
presentQuestions() 32 { 33 Scanner in = new
Scanner(System.in); 34 35 for (Question q : questions) 36
{ 37 q.display(); 38 System.out.print("Your
answer: "); 39 String response = in.nextLine(); 40
System.out.println(q.checkAnswer(response)); 41 } 42 }
43 } 44
__MACOSX/ch12/section_2/._Quiz.java.html
ch12/section_2/QuizDemo.javach12/section_2/QuizDemo.javap
ublicclassQuizDemo
{
publicstaticvoid main(String[] args)
{
Question first =newQuestion();
first.setText("Who was the inventor of Java?");
first.setAnswer("James Gosling");
ChoiceQuestion second =newChoiceQuestion();
second.setText("In which country was the inventor of Java
born?");
second.addChoice("Australia",false);
second.addChoice("Canada",true);
second.addChoice("Denmark",false);
second.addChoice("United States",false);
Quiz q =newQuiz();
q.addQuestion(first);
q.addQuestion(second);
q.presentQuestions();
}
}
__MACOSX/ch12/section_2/._QuizDemo.java
ch12/section_2/QuizDemo.java.html 1 public class QuizDemo
2 { 3 public static void main(String[] args) 4 { 5
Question first = new Question(); 6 first.setText("Who was
the inventor of Java?"); 7 first.setAnswer("James
Gosling"); 8 9 ChoiceQuestion second = new
ChoiceQuestion(); 10 second.setText("In which country
was the inventor of Java born?"); 11
second.addChoice("Australia", false); 12
second.addChoice("Canada", true); 13
second.addChoice("Denmark", false); 14
second.addChoice("United States", false); 15 16 Quiz q =
new Quiz(); 17 q.addQuestion(first); 18
q.addQuestion(second); 19 q.presentQuestions(); 20 } 21
}
__MACOSX/ch12/section_2/._QuizDemo.java.html
__MACOSX/ch12/._section_2
ch12/section_3/.DS_Store
__MACOSX/ch12/section_3/._.DS_Store
ch12/section_3/Address.javach12/section_3/Address.java/**
Describes a mailing address.
*/
publicclassAddress
{
privateString name;
privateString street;
privateString city;
privateString state;
privateString zip;
/**
Constructs a mailing address.
@param aName the recipient name
@param aStreet the street
@param aCity the city
@param aState the two-letter state code
@param aZip the ZIP postal code
*/
publicAddress(String aName,String aStreet,
String aCity,String aState,String aZip)
{
name = aName;
street = aStreet;
city = aCity;
state = aState;
zip = aZip;
}
/**
Formats the address.
@return the address as a string with three lines
*/
publicString format()
{
return name +"n"+ street +"n"
+ city +", "+ state +" "+ zip;
}
}
__MACOSX/ch12/section_3/._Address.java
ch12/section_3/Address.java.html 1 /** 2 Describes a
mailing address. 3 */ 4 public class Address 5 { 6
private String name; 7 private String street; 8 private
String city; 9 private String state; 10 private String zip;
11 12 /** 13 Constructs a mailing address. 14
@param aName the recipient name 15 @param aStreet the
street 16 @param aCity the city 17 @param aState the
two-letter state code 18 @param aZip the ZIP postal code
19 */ 20 public Address(String aName, String aStreet, 21
String aCity, String aState, String aZip) 22 { 23 name
= aName; 24 street = aStreet; 25 city = aCity; 26
state = aState; 27 zip = aZip; 28 } 29 30 /** 31
Formats the address. 32 @return the address as a string
with three lines 33 */ 34 public String format() 35 {
36 return name + "n" + street + "n" 37 + city + ",
" + state + " " + zip; 38 } 39 } 40
__MACOSX/ch12/section_3/._Address.java.html
ch12/section_3/Invoice.javach12/section_3/Invoice.javaimport j
ava.util.ArrayList;
/**
Describes an invoice for a set of purchased products.
*/
publicclassInvoice
{
privateAddress billingAddress;
privateArrayList<LineItem> items;
/**
Constructs an invoice.
@param anAddress the billing address
*/
publicInvoice(Address anAddress)
{
items =newArrayList<LineItem>();
billingAddress = anAddress;
}
/**
Adds a charge for a product to this invoice.
@param aProduct the product that the customer ordered
@param quantity the quantity of the product
*/
publicvoid add(Product aProduct,int quantity)
{
LineItem anItem =newLineItem(aProduct, quantity);
items.add(anItem);
}
/**
Formats the invoice.
@return the formatted invoice
*/
publicString format()
{
String r =" I N V O I C Enn"
+ billingAddress.format()
+String.format("nn%-30s%8s%5s%8sn",
"Description","Price","Qty","Total");
for(LineItem item : items)
{
r = r + item.format()+"n";
}
r = r +String.format("nAMOUNT DUE: $%8.2f", getAmou
ntDue());
return r;
}
/**
Computes the total amount due.
@return the amount due
*/
privatedouble getAmountDue()
{
double amountDue =0;
for(LineItem item : items)
{
amountDue = amountDue + item.getTotalPrice();
}
return amountDue;
}
}
__MACOSX/ch12/section_3/._Invoice.java
ch12/section_3/Invoice.java.html 1 import java.util.ArrayList;
2 3 /** 4 Describes an invoice for a set of purchased
products. 5 */ 6 public class Invoice 7 { 8 private
Address billingAddress; 9 private ArrayList<LineItem>
items; 10 11 /** 12 Constructs an invoice. 13
@param anAddress the billing address 14 */ 15 public
Invoice(Address anAddress) 16 { 17 items = new
ArrayList<LineItem>(); 18 billingAddress = anAddress; 19
} 20 21 /** 22 Adds a charge for a product to this
invoice. 23 @param aProduct the product that the customer
ordered 24 @param quantity the quantity of the product 25
*/ 26 public void add(Product aProduct, int quantity) 27 {
28 LineItem anItem = new LineItem(aProduct, quantity);
29 items.add(anItem); 30 } 31 32 /** 33
Formats the invoice. 34 @return the formatted invoice 35
*/ 36 public String format() 37 { 38 String r = "
I N V O I C Enn" 39 + billingAddress.format() 40
+ String.format("nn%-30s%8s%5s%8sn", 41
"Description", "Price", "Qty", "Total"); 42 43 for
(LineItem item : items) 44 { 45 r = r +
item.format() + "n"; 46 } 47 48 r = r +
String.format("nAMOUNT DUE: $%8.2f", getAmountDue());
49 50 return r; 51 } 52 53 /** 54 Computes the
total amount due. 55 @return the amount due 56 */ 57
private double getAmountDue() 58 { 59 double
amountDue = 0; 60 for (LineItem item : items) 61 {
62 amountDue = amountDue + item.getTotalPrice(); 63
} 64 return amountDue; 65 } 66 }
__MACOSX/ch12/section_3/._Invoice.java.html
ch12/section_3/InvoicePrinter.javach12/section_3/InvoicePrinte
r.java/**
This program demonstrates the invoice classes by printing
a sample invoice.
*/
publicclassInvoicePrinter
{
publicstaticvoid main(String[] args)
{
Address samsAddress
=newAddress("Sam's Small Appliances",
"100 Main Street","Anytown","CA","98765");
Invoice samsInvoice =newInvoice(samsAddress);
samsInvoice.add(newProduct("Toaster",29.95),3);
samsInvoice.add(newProduct("Hair dryer",24.95),1);
samsInvoice.add(newProduct("Car vacuum",19.99),2);
System.out.println(samsInvoice.format());
}
}
__MACOSX/ch12/section_3/._InvoicePrinter.java
ch12/section_3/InvoicePrinter.java.html 1 /** 2 This
program demonstrates the invoice classes by printing 3 a
sample invoice. 4 */ 5 public class InvoicePrinter 6 { 7
public static void main(String[] args) 8 { 9 Address
samsAddress 10 = new Address("Sam's Small
Appliances", 11 "100 Main Street", "Anytown",
"CA", "98765"); 12 13 Invoice samsInvoice = new
Invoice(samsAddress); 14 samsInvoice.add(new
Product("Toaster", 29.95), 3); 15 samsInvoice.add(new
Product("Hair dryer", 24.95), 1); 16 samsInvoice.add(new
Product("Car vacuum", 19.99), 2); 17 18
System.out.println(samsInvoice.format()); 19 } 20 }
21 22 23
__MACOSX/ch12/section_3/._InvoicePrinter.java.html
ch12/section_3/LineItem.javach12/section_3/LineItem.java/**
Describes a quantity of an article to purchase.
*/
publicclassLineItem
{
privateint quantity;
privateProduct theProduct;
/**
Constructs an item from the product and quantity.
@param aProduct the product
@param aQuantity the item quantity
*/
publicLineItem(Product aProduct,int aQuantity)
{
theProduct = aProduct;
quantity = aQuantity;
}
/**
Computes the total cost of this line item.
@return the total price
*/
publicdouble getTotalPrice()
{
return theProduct.getPrice()* quantity;
}
/**
Formats this item.
@return a formatted string of this item
*/
publicString format()
{
returnString.format("%-30s%8.2f%5d%8.2f",
theProduct.getDescription(), theProduct.getPrice(),
quantity, getTotalPrice());
}
}
__MACOSX/ch12/section_3/._LineItem.java
ch12/section_3/LineItem.java.html 1 /** 2 Describes a
quantity of an article to purchase. 3 */ 4 public class
LineItem 5 { 6 private int quantity; 7 private Product
theProduct; 8 9 /** 10 Constructs an item from the
product and quantity. 11 @param aProduct the product 12
@param aQuantity the item quantity 13 */ 14 public
LineItem(Product aProduct, int aQuantity) 15 { 16
theProduct = aProduct; 17 quantity = aQuantity; 18 } 19
20 /** 21 Computes the total cost of this line item. 22
@return the total price 23 */ 24 public double
getTotalPrice() 25 { 26 return theProduct.getPrice() *
quantity; 27 } 28 29 /** 30 Formats this item. 31
@return a formatted string of this item 32 */ 33 public
String format() 34 { 35 return String.format("%-
30s%8.2f%5d%8.2f", 36 theProduct.getDescription(),
theProduct.getPrice(), 37 quantity, getTotalPrice()); 38
} 39 }
__MACOSX/ch12/section_3/._LineItem.java.html
ch12/section_3/Product.javach12/section_3/Product.java/**
Describes a product with a description and a price.
*/
publicclassProduct
{
privateString description;
privatedouble price;
/**
Constructs a product from a description and a price.
@param aDescription the product description
@param aPrice the product price
*/
publicProduct(String aDescription,double aPrice)
{
description = aDescription;
price = aPrice;
}
/**
Gets the product description.
@return the description
*/
publicString getDescription()
{
return description;
}
/**
Gets the product price.
@return the unit price
*/
publicdouble getPrice()
{
return price;
}
}
__MACOSX/ch12/section_3/._Product.java
ch12/section_3/Product.java.html 1 /** 2 Describes a
product with a description and a price. 3 */ 4 public class
Product 5 { 6 private String description; 7 private
double price; 8 9 /** 10 Constructs a product from a
description and a price. 11 @param aDescription the
product description 12 @param aPrice the product price 13
*/ 14 public Product(String aDescription, double aPrice) 15
{ 16 description = aDescription; 17 price = aPrice;
18 } 19 20 /** 21 Gets the product description. 22
@return the description 23 */ 24 public String
getDescription() 25 { 26 return description; 27 } 28
29 /** 30 Gets the product price. 31 @return the
unit price 32 */ 33 public double getPrice() 34 { 35
return price; 36 } 37 } 38
__MACOSX/ch12/section_3/._Product.java.html
__MACOSX/ch12/._section_3
ch12/section_4/.DS_Store
__MACOSX/ch12/section_4/._.DS_Store
ch12/section_4/BankAccountTester.javach12/section_4/BankAc
countTester.javaimport com.horstmann.BankAccount;
/**
This program tests the BankAccount class.
*/
publicclassBankAccountTester
{
/**
Tests the methods of the BankAccount class.
@param args not used
*/
publicstaticvoid main(String[] args)
{
BankAccount harrysAccount =newBankAccount(1000);
harrysAccount.deposit(500);// Balance is now $1500
harrysAccount.withdraw(2000);// Balance is now $1490
harrysAccount.addInterest(1);// Balance is now $1490 + 14.
90
System.out.printf("%.2fn", harrysAccount.getBalance());
System.out.println("Expected: 1504.90");
}
}
__MACOSX/ch12/section_4/._BankAccountTester.java
ch12/section_4/BankAccountTester.java.html 1 import
com.horstmann.BankAccount; 2 3 /** 4 This program
tests the BankAccount class. 5 */ 6 public class
BankAccountTester 7 { 8 /** 9 Tests the methods of
the BankAccount class. 10 @param args not used 11 */
12 public static void main(String[] args) 13 { 14
BankAccount harrysAccount = new BankAccount(1000); 15
harrysAccount.deposit(500); // Balance is now $1500 16
harrysAccount.withdraw(2000); // Balance is now $1490 17
harrysAccount.addInterest(1); // Balance is now $1490 + 14.90
18 System.out.printf("%.2fn",
harrysAccount.getBalance()); 19
System.out.println("Expected: 1504.90"); 20 } 21 }
__MACOSX/ch12/section_4/._BankAccountTester.java.html
ch12/section_4/com/.DS_Store
__MACOSX/ch12/section_4/com/._.DS_Store
ch12/section_4/com/horstmann/.DS_Store
__MACOSX/ch12/section_4/com/horstmann/._.DS_Store
ch12/section_4/com/horstmann/BankAccount.javach12/section_
4/com/horstmann/BankAccount.javapackage com.horstmann;
/**
A bank account has a balance that can be changed by
deposits and withdrawals.
*/
publicclassBankAccount
{
privatedouble balance;
/**
Constructs a bank account with a zero balance.
*/
publicBankAccount()
{
balance =0;
}
/**
Constructs a bank account with a given balance.
@param initialBalance the initial balance
*/
publicBankAccount(double initialBalance)
{
balance = initialBalance;
}
/**
Deposits money into this account.
@param amount the amount to deposit
*/
publicvoid deposit(double amount)
{
balance = balance + amount;
}
/**
Makes a withdrawal from this account, or charges a penalty
if
sufficient funds are not available.
@param amount the amount of the withdrawal
*/
publicvoid withdraw(double amount)
{
finaldouble PENALTY =10;
if(amount > balance)
{
balance = balance - PENALTY;
}
else
{
balance = balance - amount;
}
}
/**
Adds interest to this account.
@param rate the interest rate in percent
*/
publicvoid addInterest(double rate)
{
double amount = balance * rate /100;
balance = balance + amount;
}
/**
Gets the current balance of this account.
@return the current balance
*/
publicdouble getBalance()
{
return balance;
}
}
__MACOSX/ch12/section_4/com/horstmann/._BankAccount.jav
a
__MACOSX/ch12/section_4/com/._horstmann
__MACOSX/ch12/section_4/._com
__MACOSX/ch12/._section_4
ch12/worked_example_1/.DS_Store
__MACOSX/ch12/worked_example_1/._.DS_Store
ch12/worked_example_1/ATM.javach12/worked_example_1/AT
M.java/**
An ATM that accesses a bank.
*/
publicclass ATM
{
publicstaticfinalint CHECKING =1;
publicstaticfinalint SAVINGS =2;
privateint state;
privateint customerNumber;
privateCustomer currentCustomer;
privateBankAccount currentAccount;
privateBank theBank;
publicstaticfinalint START =1;
publicstaticfinalint PIN =2;
publicstaticfinalint ACCOUNT =3;
publicstaticfinalint TRANSACT =4;
/**
Constructs an ATM for a given bank.
@param aBank the bank to which this ATM connects
*/
public ATM(Bank aBank)
{
theBank = aBank;
reset();
}
/**
Resets the ATM to the initial state.
*/
publicvoid reset()
{
customerNumber =-1;
currentAccount =null;
state = START;
}
/**
Sets the current customer number
and sets state to PIN.
(Precondition: state is START)
@param number the customer number.
*/
publicvoid setCustomerNumber(int number)
{
customerNumber = number;
state = PIN;
}
/**
Finds customer in bank.
If found sets state to ACCOUNT, else to START.
(Precondition: state is PIN)
@param pin the PIN of the current customer
*/
publicvoid selectCustomer(int pin)
{
currentCustomer
= theBank.findCustomer(customerNumber, pin);
if(currentCustomer ==null)
{
state = START;
}
else
{
state = ACCOUNT;
}
}
/**
Sets current account to checking or savings. Sets
state to TRANSACT.
(Precondition: state is ACCOUNT or TRANSACT)
@param account one of CHECKING or SAVINGS
*/
publicvoid selectAccount(int account)
{
if(account == CHECKING)
{
currentAccount = currentCustomer.getCheckingAccount()
;
}
else
{
currentAccount = currentCustomer.getSavingsAccount();
}
state = TRANSACT;
}
/**
Withdraws amount from current account.
(Precondition: state is TRANSACT)
@param value the amount to withdraw
*/
publicvoid withdraw(double value)
{
currentAccount.withdraw(value);
}
/**
Deposits amount to current account.
(Precondition: state is TRANSACT)
@param value the amount to deposit
*/
publicvoid deposit(double value)
{
currentAccount.deposit(value);
}
/**
Gets the balance of the current account.
(Precondition: state is TRANSACT)
@return the balance
*/
publicdouble getBalance()
{
return currentAccount.getBalance();
}
/**
Moves back to the previous state.
*/
publicvoid back()
{
if(state == TRANSACT)
{
state = ACCOUNT;
}
elseif(state == ACCOUNT)
{
state = PIN;
}
elseif(state == PIN)
{
state = START;
}
}
/**
Gets the current state of this ATM.
@return the current state
*/
publicint getState()
{
return state;
}
}
__MACOSX/ch12/worked_example_1/._ATM.java
ch12/worked_example_1/ATM.java.html 1 /** 2 An ATM
that accesses a bank. 3 */ 4 public class ATM 5 { 6
public static final int CHECKING = 1; 7 public static final
int SAVINGS = 2; 8 9 private int state; 10 private int
customerNumber; 11 private Customer currentCustomer; 12
private BankAccount currentAccount; 13 private Bank
theBank; 14 15 public static final int START = 1; 16
public static final int PIN = 2; 17 public static final int
ACCOUNT = 3; 18 public static final int TRANSACT = 4; 19
20 /** 21 Constructs an ATM for a given bank. 22
@param aBank the bank to which this ATM connects 23 */
24 public ATM(Bank aBank) 25 { 26 theBank =
aBank; 27 reset(); 28 } 29 30 /** 31 Resets the
ATM to the initial state. 32 */ 33 public void reset() 34
{ 35 customerNumber = -1; 36 currentAccount = null;
37 state = START; 38 } 39 40 /** 41
Sets the current customer number 42 and sets state to PIN.
43 (Precondition: state is START) 44 @param number
the customer number. 45 */ 46 public void
setCustomerNumber(int number) 47 { 48
customerNumber = number; 49 state = PIN; 50 } 51 52
/** 53 Finds customer in bank. 54 If found sets state
to ACCOUNT, else to START. 55 (Precondition: state is
PIN) 56 @param pin the PIN of the current customer 57
*/ 58 public void selectCustomer(int pin) 59 { 60
currentCustomer 61 =
theBank.findCustomer(customerNumber, pin); 62 if
(currentCustomer == null) 63 { 64 state = START;
65 } 66 else 67 { 68 state = ACCOUNT;
69 } 70 } 71 72 /** 73 Sets current account
to checking or savings. Sets 74 state to TRANSACT. 75
(Precondition: state is ACCOUNT or TRANSACT) 76
@param account one of CHECKING or SAVINGS 77 */ 78
public void selectAccount(int account) 79 { 80 if
(account == CHECKING) 81 { 82 currentAccount =
currentCustomer.getCheckingAccount(); 83 } 84 else
85 { 86 currentAccount =
currentCustomer.getSavingsAccount(); 87 } 88 state =
TRANSACT; 89 } 90 91 /** 92 Withdraws amount
from current account. 93 (Precondition: state is
TRANSACT) 94 @param value the amount to withdraw 95
*/ 96 public void withdraw(double value) 97 { 98
currentAccount.withdraw(value); 99 }100 101 /** 102
Deposits amount to current account. 103 (Precondition:
state is TRANSACT)104 @param value the amount to
deposit105 */106 public void deposit(double value)107
{ 108 currentAccount.deposit(value);109 }110 111
/** 112 Gets the balance of the current account. 113
(Precondition: state is TRANSACT)114 @return the
balance115 */116 public double getBalance()117 { 118
return currentAccount.getBalance();119 }120 121 /**122
Moves back to the previous state.123 */124 public void
back()125 {126 if (state == TRANSACT)127 {128
state = ACCOUNT;129 }130 else if (state ==
ACCOUNT)131 {132 state = PIN;133 }134
else if (state == PIN)135 {136 state = START;137
}138 }139 140 /**141 Gets the current state of this
ATM.142 @return the current state143 */144 public
int getState()145 {146 return state;147 }148 }
__MACOSX/ch12/worked_example_1/._ATM.java.html
ch12/worked_example_1/ATMFrame.javach12/worked_example
_1/ATMFrame.javaimport java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
/**
A frame displaying the components of an ATM.
*/
publicclassATMFrameextendsJFrame
{
privatestaticfinalint FRAME_WIDTH =300;
privatestaticfinalint FRAME_HEIGHT =300;
privateJButton aButton;
privateJButton bButton;
privateJButton cButton;
privateKeyPad pad;
privateJTextArea display;
private ATM theATM;
/**
Constructs the user interface of the ATM frame.
*/
publicATMFrame(ATM anATM)
{
theATM = anATM;
// Construct components
pad =newKeyPad();
display =newJTextArea(4,20);
aButton =newJButton(" A ");
aButton.addActionListener(newAButtonListener());
bButton =newJButton(" B ");
bButton.addActionListener(newBButtonListener());
cButton =newJButton(" C ");
cButton.addActionListener(newCButtonListener());
// Add components
JPanel buttonPanel =newJPanel();
buttonPanel.add(aButton);
buttonPanel.add(bButton);
buttonPanel.add(cButton);
setLayout(newFlowLayout());
add(pad);
add(display);
add(buttonPanel);
showState();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
/**
Updates display message.
*/
publicvoid showState()
{
int state = theATM.getState();
pad.clear();
if(state == ATM.START)
{
display.setText("Enter customer numbernA = OK");
}
elseif(state == ATM.PIN)
{
display.setText("Enter PINnA = OK");
}
elseif(state == ATM.ACCOUNT)
{
display.setText("Select Accountn"
+"A = CheckingnB = SavingsnC = Exit");
}
elseif(state == ATM.TRANSACT)
{
display.setText("Balance = "
+ theATM.getBalance()
+"nEnter amount and select transactionn"
+"A = WithdrawnB = DepositnC = Cancel");
}
}
classAButtonListenerimplementsActionListener
{
publicvoid actionPerformed(ActionEvent event)
{
int state = theATM.getState();
if(state == ATM.START)
{
theATM.setCustomerNumber((int) pad.getValue());
}
elseif(state == ATM.PIN)
{
theATM.selectCustomer((int) pad.getValue());
}
elseif(state == ATM.ACCOUNT)
{
theATM.selectAccount(ATM.CHECKING);
}
elseif(state == ATM.TRANSACT)
{
theATM.withdraw(pad.getValue());
theATM.back();
}
showState();
}
}
classBButtonListenerimplementsActionListener
{
publicvoid actionPerformed(ActionEvent event)
{
int state = theATM.getState();
if(state == ATM.ACCOUNT)
{
theATM.selectAccount(ATM.SAVINGS);
}
elseif(state == ATM.TRANSACT)
{
theATM.deposit(pad.getValue());
theATM.back();
}
showState();
}
}
classCButtonListenerimplementsActionListener
{
publicvoid actionPerformed(ActionEvent event)
{
int state = theATM.getState();
if(state == ATM.ACCOUNT)
{
theATM.reset();
}
elseif(state == ATM.TRANSACT)
{
theATM.back();
}
showState();
}
}
}
__MACOSX/ch12/worked_example_1/._ATMFrame.java
ch12/worked_example_1/ATMFrame.java.html 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 14 { 15 private static final int
FRAME_WIDTH = 300; 16 private static final int
FRAME_HEIGHT = 300; 17 18 private JButton aButton; 19
private JButton bButton; 20 private JButton cButton; 21
22 private KeyPad pad; 23 private JTextArea display; 24
25 private ATM theATM; 26 27 /** 28 Constructs
the user interface of the ATM frame. 29 */ 30 public
ATMFrame(ATM anATM) 31 { 32 theATM = anATM;
33 34 // Construct components 35 pad = new
KeyPad(); 36 37 display = new JTextArea(4, 20); 38
39 aButton = new JButton(" A "); 40
aButton.addActionListener(new AButtonListener()); 41 42
bButton = new JButton(" B "); 43
bButton.addActionListener(new BButtonListener()); 44 45
cButton = new JButton(" C "); 46
cButton.addActionListener(new CButtonListener()); 47 48
// Add components 49 50 JPanel buttonPanel = new
JPanel(); 51 buttonPanel.add(aButton); 52
buttonPanel.add(bButton); 53 buttonPanel.add(cButton); 54
55 setLayout(new FlowLayout()); 56 add(pad); 57
add(display); 58 add(buttonPanel); 59 showState(); 60
61 setSize(FRAME_WIDTH, FRAME_HEIGHT); 62 }
63 64 /** 65 Updates display message. 66 */ 67
public void showState() 68 { 69 int state =
theATM.getState(); 70 pad.clear(); 71 if (state ==
ATM.START) 72 { 73 display.setText("Enter
customer numbernA = OK"); 74 } 75 else if (state ==
ATM.PIN) 76 { 77 display.setText("Enter PINnA =
OK"); 78 } 79 else if (state == ATM.ACCOUNT) 80
{ 81 display.setText("Select Accountn" 82 +
"A = CheckingnB = SavingsnC = Exit"); 83 } 84 else
if (state == ATM.TRANSACT) 85 { 86
display.setText("Balance = " 87 +
theATM.getBalance() 88 + "nEnter amount and
select transactionn" 89 + "A = WithdrawnB =
DepositnC = Cancel"); 90 } 91 } 92 93 class
AButtonListener implements ActionListener 94 { 95
public void actionPerformed(ActionEvent event) 96 { 97
int state = theATM.getState(); 98 if (state ==
ATM.START) 99 {100
theATM.setCustomerNumber((int) pad.getValue());101
}102 else if (state == ATM.PIN)103 {104
theATM.selectCustomer((int) pad.getValue());105 }106
else if (state == ATM.ACCOUNT)107 {108
theATM.selectAccount(ATM.CHECKING);109 }110
else if (state == ATM.TRANSACT)111 {112
theATM.withdraw(pad.getValue());113
theATM.back();114 }115 showState();116
}117 }118 119 class BButtonListener implements
ActionListener120 { 121 public void
actionPerformed(ActionEvent event)122 { 123 int
state = theATM.getState();124 if (state ==
ATM.ACCOUNT)125 {126
theATM.selectAccount(ATM.SAVINGS);127 }128
else if (state == ATM.TRANSACT)129 {130
theATM.deposit(pad.getValue());131
theATM.back();132 }133 showState();134
}135 }136 137 class CButtonListener implements
ActionListener138 { 139 public void
actionPerformed(ActionEvent event)140 { 141 int
state = theATM.getState();142 if (state ==
ATM.ACCOUNT)143 {144 theATM.reset();145
}146 else if (state == ATM.TRANSACT)147 {148
theATM.back();149 }150 showState();151
}152 }153 }
__MACOSX/ch12/worked_example_1/._ATMFrame.java.html
ch12/worked_example_1/ATMSimulator.javach12/worked_exam
ple_1/ATMSimulator.javaimport java.io.IOException;
import java.util.Scanner;
/**
A text-based simulation of an automatic teller machine.
*/
publicclassATMSimulator
{
publicstaticvoid main(String[] args)
{
ATM theATM;
try
{
Bank theBank =newBank();
theBank.readCustomers("customers.txt");
theATM =new ATM(theBank);
}
catch(IOException e)
{
System.out.println("Error opening accounts file.");
return;
}
Scanner in =newScanner(System.in);
while(true)
{
int state = theATM.getState();
if(state == ATM.START)
{
System.out.print("Enter customer number: ");
int number = in.nextInt();
theATM.setCustomerNumber(number);
}
elseif(state == ATM.PIN)
{
System.out.print("Enter PIN: ");
int pin = in.nextInt();
theATM.selectCustomer(pin);
}
elseif(state == ATM.ACCOUNT)
{
System.out.print("A=Checking, B=Savings, C=Quit: ");
String command = in.next();
if(command.equalsIgnoreCase("A"))
{
theATM.selectAccount(ATM.CHECKING);
}
elseif(command.equalsIgnoreCase("B"))
{
theATM.selectAccount(ATM.SAVINGS);
}
elseif(command.equalsIgnoreCase("C"))
{
theATM.reset();
}
else
{
System.out.println("Illegal input!");
}
}
elseif(state == ATM.TRANSACT)
{
System.out.println("Balance="+ theATM.getBalance());
System.out.print("A=Deposit, B=Withdrawal, C=Cancel: ");
String command = in.next();
if(command.equalsIgnoreCase("A"))
{
System.out.print("Amount: ");
double amount = in.nextDouble();
theATM.deposit(amount);
theATM.back();
}
elseif(command.equalsIgnoreCase("B"))
{
System.out.print("Amount: ");
double amount = in.nextDouble();
theATM.withdraw(amount);
theATM.back();
}
elseif(command.equalsIgnoreCase("C"))
{
theATM.back();
}
else
{
System.out.println("Illegal input!");
}
}
}
}
}
__MACOSX/ch12/worked_example_1/._ATMSimulator.java
ch12/worked_example_1/ATMSimulator.java.html 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 { 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 { 47
theATM.selectAccount(ATM.CHECKING); 48 } 49
else if (command.equalsIgnoreCase("B")) 50 { 51
theATM.selectAccount(ATM.SAVINGS); 52 } 53
else if (command.equalsIgnoreCase("C")) 54 { 55
theATM.reset(); 56 } 57 else 58 { 59
System.out.println("Illegal input!"); 60
} 61 } 62 else if (state == ATM.TRANSACT) 63
{ 64 System.out.println("Balance=" +
theATM.getBalance()); 65
System.out.print("A=Deposit, B=Withdrawal, C=Cancel: "); 66
String command = in.next(); 67 if
(command.equalsIgnoreCase("A")) 68 { 69
System.out.print("Amount: "); 70 double amount =
in.nextDouble(); 71 theATM.deposit(amount); 72
theATM.back(); 73 } 74 else if
(command.equalsIgnoreCase("B")) 75 { 76
System.out.print("Amount: "); 77 double amount =
in.nextDouble(); 78 theATM.withdraw(amount); 79
theATM.back(); 80 } 81 else if
(command.equalsIgnoreCase("C")) 82 { 83
theATM.back(); 84 } 85 else 86 { 87
System.out.println("Illegal input!"); 88
} 89 } 90 } 91 } 92 } 93
__MACOSX/ch12/worked_example_1/._ATMSimulator.java.ht
ml
ch12/worked_example_1/ATMViewer.javach12/worked_exampl
e_1/ATMViewer.javaimport java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
A graphical simulation of an automatic teller machine.
*/
publicclassATMViewer
{
publicstaticvoid main(String[] args)
{
ATM theATM;
try
{
Bank theBank =newBank();
theBank.readCustomers("customers.txt");
theATM =new ATM(theBank);
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null,"Error opening accounts
file.");
return;
}
JFrame frame =newATMFrame(theATM);
frame.setTitle("First National Bank of Java");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;
frame.setVisible(true);
}
}
__MACOSX/ch12/worked_example_1/._ATMViewer.java
ch12/worked_example_1/ATMViewer.java.html 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 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, "Error
opening accounts file."); 23 return; 24 } 25 26
JFrame frame = new ATMFrame(theATM); 27
frame.setTitle("First National Bank of Java"); 28
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 29
frame.setVisible(true); 30 } 31 } 32
__MACOSX/ch12/worked_example_1/._ATMViewer.java.html
ch12/worked_example_1/Bank.javach12/worked_example_1/Ba
nk.javaimport java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
/**
A bank contains customers.
*/
publicclassBank
{
privateArrayList<Customer> customers;
/**
Constructs a bank with no customers.
*/
publicBank()
{
customers =newArrayList<Customer>();
}
/**
Reads the customer numbers and pins.
@param filename the name of the customer file
*/
publicvoid readCustomers(String filename)
throwsIOException
{
Scanner in =newScanner(newFile(filename));
while(in.hasNext())
{
int number = in.nextInt();
int pin = in.nextInt();
Customer c =newCustomer(number, pin);
addCustomer(c);
}
in.close();
}
/**
Adds a customer to the bank.
@param c the customer to add
*/
publicvoid addCustomer(Customer c)
{
customers.add(c);
}
/**
Finds a customer in the bank.
@param aNumber a customer number
@param aPin a personal identification number
@return the matching customer, or null if no customer
matches
*/
publicCustomer findCustomer(int aNumber,int aPin)
{
for(Customer c : customers)
{
if(c.match(aNumber, aPin))
{
return c;
}
}
returnnull;
}
}
__MACOSX/ch12/worked_example_1/._Bank.java
ch12/worked_example_1/Bank.java.html 1 import java.io.File;
2 import java.io.IOException; 3 import java.util.ArrayList; 4
import java.util.Scanner; 5 6 /** 7 A bank contains
customers. 8 */ 9 public class Bank 10 { 11 private
ArrayList<Customer> customers; 12 13 /** 14
Constructs a bank with no customers. 15 */ 16 public
Bank() 17 { 18 customers = new
ArrayList<Customer>(); 19 } 20 21 /** 22 Reads
the customer numbers and pins. 23 @param filename the
name of the customer file 24 */ 25 public void
readCustomers(String filename) 26 throws IOException
27 { 28 Scanner in = new Scanner(new File(filename));
29 while (in.hasNext()) 30 { 31 int number =
in.nextInt(); 32 int pin = in.nextInt(); 33 Customer
c = new Customer(number, pin); 34 addCustomer(c); 35
} 36 in.close(); 37 } 38 39 /** 40 Adds a
customer to the bank. 41 @param c the customer to add 42
*/ 43 public void addCustomer(Customer c) 44 { 45
customers.add(c); 46 } 47 48 /** 49 Finds a
customer in the bank. 50 @param aNumber a customer
number 51 @param aPin a personal identification number
52 @return the matching customer, or null if no customer
53 matches 54 */ 55 public Customer
findCustomer(int aNumber, int aPin) 56 { 57 for
(Customer c : customers) 58 { 59 if
(c.match(aNumber, aPin)) 60 { 61 return c; 62
} 63 } 64 return null; 65 } 66 } 67 68
__MACOSX/ch12/worked_example_1/._Bank.java.html
ch12/worked_example_1/BankAccount.javach12/worked_examp
le_1/BankAccount.java/**
A bank account has a balance that can be changed by
deposits and withdrawals.
*/
publicclassBankAccount
{
privatedouble balance;
/**
Constructs a bank account with a zero balance.
*/
publicBankAccount()
{
balance =0;
}
/**
Constructs a bank account with a given balance.
@param initialBalance the initial balance
*/
publicBankAccount(double initialBalance)
{
balance = initialBalance;
}
/**
Deposits money into the account.
@param amount the amount of money to withdraw
*/
publicvoid deposit(double amount)
{
balance = balance + amount;
}
/**
Withdraws money from the account.
@param amount the amount of money to deposit
*/
publicvoid withdraw(double amount)
{
balance = balance - amount;
}
/**
Gets the account balance.
@return the account balance
*/
publicdouble getBalance()
{
return balance;
}
}
__MACOSX/ch12/worked_example_1/._BankAccount.java
ch12/worked_example_1/BankAccount.java.html 1 /** 2 A
bank account has a balance that can be changed by 3
deposits and withdrawals. 4 */ 5 public class BankAccount 6
{ 7 private double balance; 8 9 /** 10
Constructs a bank account with a zero balance. 11 */ 12
public BankAccount() 13 { 14 balance = 0; 15 } 16
17 /** 18 Constructs a bank account with a given
balance. 19 @param initialBalance the initial balance 20
*/ 21 public BankAccount(double initialBalance) 22 { 23
balance = initialBalance; 24 } 25 26 /** 27
Deposits money into the account. 28 @param amount the
amount of money to withdraw 29 */ 30 public void
deposit(double amount) 31 { 32 balance = balance +
amount; 33 } 34 35 /** 36 Withdraws money from
the account. 37 @param amount the amount of money to
deposit 38 */ 39 public void withdraw(double amount) 40
{ 41 balance = balance - amount; 42 } 43 44 /**
45 Gets the account balance. 46 @return the account
balance 47 */ 48 public double getBalance() 49 { 50
return balance; 51 } 52 } 53
__MACOSX/ch12/worked_example_1/._BankAccount.java.html
ch12/worked_example_1/Customer.javach12/worked_example_1
/Customer.java/**
A bank customer with a checking and a savings account.
*/
publicclassCustomer
{
privateint customerNumber;
privateint pin;
privateBankAccount checkingAccount;
privateBankAccount savingsAccount;
/**
Constructs a customer with a given number and PIN.
@param aNumber the customer number
@param aPin the personal identification number
*/
publicCustomer(int aNumber,int aPin)
{
customerNumber = aNumber;
pin = aPin;
checkingAccount =newBankAccount();
savingsAccount =newBankAccount();
}
/**
Tests if this customer matches a customer number
and PIN.
@param aNumber a customer number
@param aPin a personal identification number
@return true if the customer number and PIN match
*/
publicboolean match(int aNumber,int aPin)
{
return customerNumber == aNumber && pin == aPin;
}
/**
Gets the checking account of this customer.
@return the checking account
*/
publicBankAccount getCheckingAccount()
{
return checkingAccount;
}
/**
Gets the savings account of this customer.
@return the checking account
*/
publicBankAccount getSavingsAccount()
{
return savingsAccount;
}
}
__MACOSX/ch12/worked_example_1/._Customer.java
ch12/worked_example_1/Customer.java.html 1 /** 2 A
bank customer with a checking and a savings account. 3 */ 4
public class Customer 5 { 6 private int customerNumber;
7 private int pin; 8 private BankAccount
checkingAccount; 9 private BankAccount savingsAccount;
10 11 /** 12 Constructs a customer with a given
number and PIN. 13 @param aNumber the customer
number 14 @param aPin the personal identification number
15 */ 16 public Customer(int aNumber, int aPin) 17 {
18 customerNumber = aNumber; 19 pin = aPin; 20
checkingAccount = new BankAccount(); 21
savingsAccount = new BankAccount(); 22 } 23 24 /**
25 Tests if this customer matches a customer number 26
and PIN. 27 @param aNumber a customer number 28
@param aPin a personal identification number 29 @return
true if the customer number and PIN match 30 */ 31 public
boolean match(int aNumber, int aPin) 32 { 33 return
customerNumber == aNumber && pin == aPin; 34 } 35
36 /** 37 Gets the checking account of this customer.
38 @return the checking account 39 */ 40 public
BankAccount getCheckingAccount() 41 { 42 return
checkingAccount; 43 } 44 45 /** 46 Gets the
savings account of this customer. 47 @return the checking
account 48 */ 49 public BankAccount getSavingsAccount()
50 { 51 return savingsAccount; 52 } 53 }
__MACOSX/ch12/worked_example_1/._Customer.java.html
ch12/worked_example_1/customers.txt
1 1234
2 2468
3 3692
4 4826
5 5050
6 6284
7 7418
8 8642
9 9876
__MACOSX/ch12/worked_example_1/._customers.txt
ch12/worked_example_1/KeyPad.javach12/worked_example_1/
KeyPad.javaimport java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
A component that lets the user enter a number, using
a button pad labeled with digits.
*/
publicclassKeyPadextendsJPanel
{
privateJPanel buttonPanel;
privateJButton clearButton;
privateJTextField display;
/**
Constructs the keypad panel.
*/
publicKeyPad()
{
setLayout(newBorderLayout());
// Add display field
display =newJTextField();
add(display,"North");
// Make button panel
buttonPanel =newJPanel();
buttonPanel.setLayout(newGridLayout(4,3));
// Add digit buttons
addButton("7");
addButton("8");
addButton("9");
addButton("4");
addButton("5");
addButton("6");
addButton("1");
addButton("2");
addButton("3");
addButton("0");
addButton(".");
// Add clear entry button
clearButton =newJButton("CE");
buttonPanel.add(clearButton);
classClearButtonListenerimplementsActionListener
{
publicvoid actionPerformed(ActionEvent event)
{
display.setText("");
}
}
ActionListener listener =newClearButtonListener();
clearButton.addActionListener(new
ClearButtonListener());
add(buttonPanel,"Center");
}
/**
Adds a button to the button panel
@param label the button label
*/
privatevoid addButton(finalString label)
{
classDigitButtonListenerimplementsActionListener
{
publicvoid actionPerformed(ActionEvent event)
{
// Don't add two decimal points
if(label.equals(".")
&& display.getText().indexOf(".")!=-1)
{
return;
}
// Append label text to button
display.setText(display.getText()+ label);
}
}
JButton button =newJButton(label);
buttonPanel.add(button);
ActionListener listener =newDigitButtonListener();
button.addActionListener(listener);
}
/**
Gets the value that the user entered.
@return the value in the text field of the keypad
*/
publicdouble getValue()
{
returnDouble.parseDouble(display.getText());
}
/**
Clears the display.
*/
publicvoid clear()
{
display.setText("");
}
}
__MACOSX/ch12/worked_example_1/._KeyPad.java
ch12/worked_example_1/KeyPad.java.html 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 button pad labeled with
digits. 12 */ 13 public class KeyPad extends JPanel 14 { 15
private JPanel buttonPanel; 16 private JButton clearButton;
17 private JTextField display; 18 19 /** 20
Constructs the keypad panel. 21 */ 22 public KeyPad() 23
{ 24 setLayout(new BorderLayout()); 25 26 //
Add display field 27 28 display = new JTextField(); 29
add(display, "North"); 30 31 // Make button panel 32 33
buttonPanel = new JPanel(); 34 buttonPanel.setLayout(new
GridLayout(4, 3)); 35 36 // Add digit buttons 37
38 addButton("7"); 39 addButton("8"); 40
addButton("9"); 41 addButton("4"); 42
addButton("5"); 43 addButton("6"); 44
addButton("1"); 45 addButton("2"); 46
addButton("3"); 47 addButton("0"); 48
addButton("."); 49 50 // Add clear entry button 51
52 clearButton = new JButton("CE"); 53
buttonPanel.add(clearButton); 54 55 class
ClearButtonListener implements ActionListener 56 { 57
public void actionPerformed(ActionEvent event) 58 {
59 display.setText(""); 60 } 61 } 62 63
ActionListener listener = new ClearButtonListener(); 64
65 clearButton.addActionListener(new 66
ClearButtonListener()); 67 68 add(buttonPanel,
"Center"); 69 } 70 71 /** 72 Adds a button to the
button panel 73 @param label the button label 74 */ 75
private void addButton(final String label) 76 { 77 class
DigitButtonListener implements ActionListener 78 { 79
public void actionPerformed(ActionEvent event) 80 {
81 // Don't add two decimal points 82 if
(label.equals(".") 83 &&
display.getText().indexOf(".") != -1) 84 { 85
return; 86 } 87 88 // Append label text to
button 89 display.setText(display.getText() + label); 90
} 91 } 92 93 JButton button = new JButton(label); 94
buttonPanel.add(button); 95 ActionListener listener = new
DigitButtonListener(); 96
button.addActionListener(listener); 97 } 98 99 /** 100
Gets the value that the user entered. 101 @return the value
in the text field of the keypad102 */103 public double
getValue()104 { 105 return
Double.parseDouble(display.getText());106 }107 108
/** 109 Clears the display. 110 */111 public void
clear()112 { 113 display.setText("");114 }115 }116
__MACOSX/ch12/worked_example_1/._KeyPad.java.html
__MACOSX/ch12/._worked_example_1
__MACOSX/._ch12
Chapter12 Worked out example.pdf
simulating an automatic teller Machine we1
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
step 1 Gather requirements.
The purpose of this project is to simulate an automatic teller
machine (ATM). The ATM is
used by the customers of a bank. Each customer has two
accounts: a checking account and
a savings account. Each customer also has a customer number
and a personal identification
number (PIN); both are required to gain access to the accounts.
(In a real ATM, the customer
number would be recorded on the magnetic strip of the ATM
card. In this simulation, the
customer will need to type it in.) With the ATM, customers can
select an account (checking or
savings). The balance of the selected account is displayed. Then
the customer can deposit and
withdraw money. This process is repeated until the customer
chooses to exit.
The details of the user interaction depend on the user interface
that we choose for the simu-
lation. We will develop two separate interfaces: a graphical
interface that closely mimics an
actual ATM (see Figure 12), and a text-based interface that
allows you to test the ATM and
bank classes without being dis tracted by GUI programming.
In the GUI interface, the ATM has a keypad to enter numbers, a
display to show messages,
and a set of buttons, labeled A, B, and C, whose function
depends on the state of the machine.
Specifically, the user interaction is as follows. When the ATM
starts up, it expects a user to
enter a cus tomer number. The display shows the following
message:
Enter-customer-number
A-=-OK
The user enters the customer number on the keypad and presses
the A button. The display
message changes to
Enter-PIN
A-=-OK
Next, the user enters the PIN and presses the A button again. If
the customer number and ID
match those of one of the customers in the bank, then the
customer can proceed. If not, the
user is again prompted to enter the customer number.
w O r k e d e x a M p L e 1 2 . 1 simulating an automatic
Teller machine
In this Worked Example, we apply the object-oriented
design methodology to the simulation of an automatic
teller machine that works with both a console-based and
graphical user interface.
Figure 12
graphical User interface for
the automatic teller Machine
we2 Chapter 12 Object-Oriented design
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
If the customer has been authorized to use the system, then the
display message changes to
Select-Account
A-=-Checking
B-=-Savings
C-=-Exit
If the user presses the C button, the ATM reverts to its original
state and asks the next user to
enter a cus tomer number.
If the user presses the A or B buttons, the ATM remembers the
selected account, and the
display mes sage changes to
Balance-=-balance of selected account-
Enter-amount-and-select-transaction
A-=-Withdraw
B-=-Deposit
C-=-Cancel
If the user presses the A or B buttons, the value entered in the
keypad is withdrawn from or
deposited into the selected account. (This is just a simulation,
so no money is dispensed and no
deposit is accepted.) Afterward, the ATM reverts to the
preceding state, allowing the user to
select another account or to exit.
If the user presses the C button, the ATM reverts to the
preceding state without executing
any transac tion.
In the text-based interaction, we read input from System.in
instead of the buttons. Here is a
typical dia log:
Enter-customer-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
In our solution, only the user interface classes are affected by
the choice of user interface. The
remainder of the classes can be used for both solutions—they
are decoupled from the user
interface.
Because this is a simulation, the ATM does not actually
communicate with a bank. It simply
loads a set of customer numbers and PINs from a file. All
accounts are initialized with a zero
balance.
step 2 Use CRC cards to find classes, responsibilities, and
collaborators.
We will again follow the recipe of Section 12.2 and show how
to discover classes, responsibili-
ties, and rela tionships and how to obtain a detailed design for
the ATM program.
Recall that the first rule for finding classes is “Look for nouns
in the problem description”.
Here is a list of the nouns:
ATM
User
Keypad
Display
Display-message
Button
State
Bank-account
Checking-account
Savings-account
Customer
Customer-number
PIN
Bank
simulating an automatic teller Machine we3
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
Of course, not all of these nouns will become names of classes,
and we may yet discover the
need for classes that aren’t in this list, but it is a good start.
Users and customers represent the same concept in this
program. Let’s use a class Customer.
A customer has two bank accounts, and we will require that a
Customer object should be able
to locate these accounts. (Another possible design would make
the Bank class responsible for
locating the accounts of a given cus tomer—see Exercise
P12.10.)
A customer also has a customer number and a PIN. We can, of
course, require that a cus-
tomer object give us the customer number and the PIN. But
perhaps that isn’t so secure.
Instead, simply require that a customer object, when given a
customer number and a PIN, will
tell us whether it matches its own infor mation or not.
get accounts
match number and PIN
Customer
A bank contains a collection of customers. When a user walks
up to the ATM and enters a
customer num ber and PIN, it is the job of the bank to find the
matching customer. How can
the bank do this? It needs to check for each customer whether
its customer number and PIN
match. Thus, it needs to call the match number and PIN method
of the Customer class that we
just discovered. Because the find customer method calls a
Customer method, it collaborates with
the Customer class. We record that fact in the right-hand col
umn of the CRC card.
When the simulation starts up, the bank must also be able to
read customer information
from a file.
find customer Customer
read customers
Bank
The BankAccount class is our familiar class with methods to get
the balance and to deposit and
withdraw money.
In this program, there is nothing that distinguishes checking
accounts from savings
accounts. The ATM does not add interest or deduct fees.
Therefore, we decide not to imple-
ment separate subclasses for check ing and savings accounts.
Finally, we are left with the ATM class itself. An important
notion of the ATM is the state.
The current machine state determines the text of the prompts
and the function of the buttons.
For example, when you first log in, you use the A and B buttons
to select an account. Next,
you use the same buttons to choose between deposit and
withdrawal. The ATM must remem-
ber the current state so that it can correctly interpret the
buttons.
we4 Chapter 12 Object-Oriented design
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
Figure 13
state diagram for
the atM Class START
PIN
Customer
not found
Customer found
Account selected
Customer number entered
Exit selected
Transaction
completed or
canceled
ACCOUNT
TRANSACT
There are four states:
1. START: Enter customer ID
2. PIN: Enter PIN
3. ACCOUNT: Select account
4. TRANSACT: Select transaction
To understand how to move from one state to the next, it is
useful to draw a state diagram
(Figure 13). The UML notation has standardized shapes for state
diagrams. Draw states as
rectangles with rounded corners. Draw state changes as arrows,
with labels that indicate the
reason for the change.
The user must type a valid customer number and PIN. Then the
ATM can ask the bank to
find the cus tomer. This calls for a select customer method. It
collaborates with the bank, ask-
ing the bank for the cus tomer that matches the customer
number and PIN. Next, there must
be a select account method that asks the current customer for
the checking or savings account.
Finally, the ATM must carry out the selected transaction on the
current account.
manage state Customer
Bank
BankAccount
select customer
select account
execute transaction
ATM
simulating an automatic teller Machine we5
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
Of course, discovering these classes and methods was not as
neat and orderly as it appears
from this dis cussion. When I designed these classes for this
book, it took me several trials and
many torn cards to come up with a satisfactory design. It is also
important to remember that
there is seldom one best design.
This design has several advantages. The classes describe clear
concepts. The methods are
sufficient to implement all necessary tasks. (I mentally walked
through every ATM usage sce-
nario to verify that.) There are not too many collaboration
dependencies between the classes.
Thus, I was satisfied with this design and proceeded to the next
step.
step 3 Use UML diagrams to record class relationships.
To draw the dependencies, use the “collaborator” columns from
the CRC cards. Looking at
those col umns, you find that the dependencies are as follows:
• ATM knows about Bank, Customer, and BankAccount.
• Bank knows about Customer.
• Customer knows about BankAccount.
ATM
BankAccount
Customer
Bank
It is easy to see some of the aggregation relationships. A bank
has customers, and each cus-
tomer has two bank accounts.
Does the ATM class aggregate Bank? To answer this question,
ask yourself whether an ATM
object needs to store a reference to a bank object. Does it need
to locate the same bank object
across multiple method calls? Indeed it does. Therefore,
aggregation is the appropriate rela-
tionship.
Does an ATM aggregate customers? Clearly, the ATM is not
responsible for storing all of
the bank’s customers. That’s the bank’s job. But in our design,
the ATM remembers the current
customer. If a cus tomer has logged in, subsequent commands
refer to the same customer. The
ATM needs to either store a reference to the customer, or ask
the bank to look up the object
whenever it needs the current customer. It is a design decision:
either store the object, or look
it up when needed. We will decide to store the cur rent customer
object. That is, we will use
aggregation. Note that the choice of aggregation is not an auto
matic consequence of the prob-
lem description—it is a design decision.
Similarly, we will decide to store the current bank account
(checking or savings) that the
user selects. Therefore, we have an aggregation relationship
between ATM and BankAccount.
Figure 14 shows the relationships between these classes, using
the graphical user interface.
(The console user interface uses a single class ATMSimulator
instead of the ATMFrame, ATMViewer,
and Keypad classes.)
we6 Chapter 12 Object-Oriented design
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
Figure 14 relationships between the atM Classes
ATMFrame
ATMViewer
Keypad
ATM
BankAccount
Customer
Bank
1
1
1 2
*
The class diagram is a good tool to visualize dependencies.
Look at the GUI classes. They
are com pletely independent from the rest of the ATM system.
You can replace the GUI with a
console interface, and you can take out the Keypad class and
use it in another application. Also,
the Bank, BankAccount, and Cus-tomer classes, although
dependent on each other, don’t know any-
thing about the ATM class. That makes sense—you can have
banks without ATMs. As you can
see, when you analyze relationships, you look for both the
absence and presence of relation-
ships.
step 4 Use javadoc to document method behavior.
Now you are ready for the final step of the design phase:
documenting the classes and methods
that you discovered. Here is a part of the documentation for the
ATM class:
/**
---An ATM that accesses a bank.-
*/
public-class-ATM-
{-
---.-.-.
---/**
------Constructs an ATM for a given bank.-
------@param-aBank-the bank to which this ATM connects-
---*/----
---public-ATM(Bank-aBank)-{-}
---/**-
------Sets the current customer number-
------and sets state to PIN.-
------(Precondition: state is START)
------@param-number-the customer number-
---*/
---public-void-setCustomerNumber(int-number)-{-}
simulating an automatic teller Machine we7
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
---/**-
------Finds customer in bank.-
------If found sets state to ACCOUNT, else to START.-
------(Precondition: state is PIN)-
------@param-pin-the PIN of the current customer-
---*/
---public-void-selectCustomer(int-pin)-{-}
---/**-
------Sets current account to checking or savings. Sets-
------state to TRANSACT.-
------(Precondition: state is ACCOUNT or TRANSACT)-
------@param-account-one of CHECKING or SAVINGS-
---*/
---public-void-selectAccount(int-account)-{-}
---/**-
------Withdraws amount from current account.-
------(Precondition: state is TRANSACT)-
------@param-value-the amount to withdraw
---*/
---public-void-withdraw(double-value)-{-}
---.-.-.
}
Then run the javadoc utility to turn this documentation into
HTML format.
For conciseness, we omit the documentation of the other
classes, but they are shown at the
end of this example.
step 5 Implement your program.
Finally, the time has come to implement the ATM simulator.
The implementation phase is very
straight forward and should take much less time than the design
phase.
A good strategy for implementing the classes is to go “bottom-
up”. Start with the classes
that don’t depend on others, such as Keypad and BankAccount.
Then implement a class such as
Customer that depends only on the BankAccount class. This
“bottom-up” approach allows you to
test your classes individually. You will find the
implementations of these classes at the end of
this section.
The most complex class is the ATM class. In order to implement
the methods, you need to
declare the necessary instance variables. From the class
diagram, you can tell that the ATM has
a bank object. It becomes an instance variable of the class:
public-class-ATM
{-
---private-Bank-theBank;
---.-.-.
}
From the description of the ATM states, it is clear that we
require additional instance variables
to store the current state, customer, and bank account:
public-class-ATM
{-
---private-int-state;
---private-Customer-currentCustomer;
---private-BankAccount-currentAccount;
---.-.-.
}
we8 Chapter 12 Object-Oriented design
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
Most methods are very straightforward to implement. Consider
the selectCustomer method.
From the design documentation, we have the description
/**-
---Finds customer in bank.-
---If found sets state to ACCOUNT, else to START.-
---(Precondition: state is PIN)-
---@param-pin-the PIN of the current customer-
*/
This description can be almost literally translated to Java
instructions:
public-void-selectCustomer(int-pin)
{-
---currentCustomer-=-theBank.findCustomer(customerNumber,-
pin);
---if-(currentCustomer-==-null)-
---{
------state-=-START;
---}
---else-
---{
------state-=-ACCOUNT;
---}
}
We won’t go through a method-by-method description of the
ATM program. You should take
some time and compare the actual implementation to the CRC
cards and the UML diagram.
worked_example_1/bankaccount.java
1- /**
2- ---A bank account has a balance that can be changed by-
3- ---deposits and withdrawals.
4- */
5- public-class-BankAccount
6- {--
7- ---private-double-balance;-
8-
9- ---/**
10- ------Constructs a bank account with a zero balance.
11- ---*/
12- ---public-BankAccount()
13- ---{--
14- ------balance-=-0;
15- ---}
16-
17- ---/**
18- ------Constructs a bank account with a given balance.
19- ------@param-initialBalance-the initial balance
20- ---*/
21- ---public-BankAccount(double-initialBalance)
22- ---{--
23- ------balance-=-initialBalance;
24- ---}
25- -
26- ---/**-
27- ------Deposits money into the account.
28- ------@param-amount-the amount of money to withdraw
29- ---*/
30- ---public-void-deposit(double-amount)-
31- ---{--
simulating an automatic teller Machine we9
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
32- ------balance-=-balance-+-amount;
33- ---}
34-
35- ---/**-
36- ------Withdraws money from the account.
37- ------@param-amount-the amount of money to deposit
38- ---*/
39- ---public-void-withdraw(double-amount)-
40- ---{--
41- ------balance-=-balance---amount;
42- ---}
43-
44- ---/**-
45- ------Gets the account balance.
46- ------@return-the account balance
47- ---*/
48- ---public-double-getBalance()
49- ---{--
50- ------return-balance;-
51- ---}
52- }
worked_example_1/Customer.java
1- /**
2- ---A bank customer with a checking and a savings account.-
3- */
4- public-class-Customer
5- {-
6- ---private-int-customerNumber;
7- ---private-int-pin;
8- ---private-BankAccount-checkingAccount;
9- ---private-BankAccount-savingsAccount;
10-
11- ---/**
12- ------Constructs a customer with a given number and PIN.-
13- ------@param-aNumber-the customer number-
14- ------@param-aPin-the personal identification number-
15- ---*/
16- ---public-Customer(int-aNumber,-int-aPin)
17- ---{-
18- ------customerNumber-=-aNumber;
19- ------pin-=-aPin;
20- ------checkingAccount-=-new-BankAccount();
21- ------savingsAccount-=-new-BankAccount();
22- ---}
23- ---
24- ---/**-
25- ------Tests if this customer matches a customer number-
26- ------and PIN.-
27- ------@param-aNumber-a customer number-
28- ------@param-aPin-a personal identification number-
29- ------@return-true if the customer number and PIN match-
30- ---*/
31- ---public-boolean-match(int-aNumber,-int-aPin)
32- ---{-
33- ------return-customerNumber-==-aNumber-&&-pin-==-aPin;
34- ---}
35- ---
we10 Chapter 12 Object-Oriented design
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
36- ---/**-
37- ------Gets the checking account of this customer.-
38- ------@return-the checking account-
39- ---*/
40- ---public-BankAccount-getCheckingAccount()
41- ---{-
42- ------return-checkingAccount;
43- ---}
44- ---
45- ---/**-
46- ------Gets the savings account of this customer.-
47- ------@return-the checking account-
48- ---*/
49- ---public-BankAccount-getSavingsAccount()
50- ---{-
51- ------return-savingsAccount;
52- ---}
53- }
worked_example_1/bank.java
1- import-java.io.File;
2- import-java.io.IOException;
3- import-java.util.ArrayList;
4- import-java.util.Scanner;
5-
6- /**
7- ---A bank contains customers.-
8- */
9- public-class-Bank
10- {-
11- ---private-ArrayList<Customer>-customers;
12-
13- ---/**
14- ------Constructs a bank with no customers.-
15- ---*/
16- ---public-Bank()
17- ---{-
18- ------customers-=-new-ArrayList<Customer>();
19- ---}
20- ---
21- ---/**
22- ------Reads the customer numbers and pins.-
23- ------@param-filename-the name of the customer file-
24- ---*/
25- ---public-void-readCustomers(String-filename)-
26- ---------throws-IOException
27- ---{-
28- ------Scanner-in-=-new-Scanner(new-File(filename));
29- ------while-(in.hasNext())
30- ------{-
31- ---------int-number-=-in.nextInt();
32- ---------int-pin-=-in.nextInt();
33- ---------Customer-c-=-new-Customer(number,-pin);
34- ---------addCustomer(c);
35- ------}
36- ------in.close();
37- ---}
38- ---
simulating an automatic teller Machine we11
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
39- ---/**
40- ------Adds a customer to the bank.-
41- ------@param-c-the customer to add-
42- ---*/
43- ---public-void-addCustomer(Customer-c)
44- ---{-
45- ------customers.add(c);
46- ---}
47- ---
48- ---/**-
49- ------Finds a customer in the bank.-
50- ------@param-aNumber-a customer number-
51- ------@param-aPin-a personal identification number-
52- ------@return-the matching customer, or null if no
customer-
53- ------matches-
54- ---*/
55- ---public-Customer-findCustomer(int-aNumber,-int-aPin)
56- ---{-
57- ------for-(Customer-c-:-customers)
58- ------{-
59- ---------if-(c.match(aNumber,-aPin))
60- ---------{
61- ------------return-c;
62- ---------}
63- ------}
64- ------return-null;
65- ---}
66- }
worked_example_1/aTm.java
1- /**
2- ---An ATM that accesses a bank.
3- */
4- public-class-ATM-
5- {--
6- ---public-static-final-int-CHECKING-=-1;
7- ---public-static-final-int-SAVINGS-=-2;
8-
9- ---private-int-state;
10- ---private-int-customerNumber;
11- ---private-Customer-currentCustomer;
12- ---private-BankAccount-currentAccount;
13- ---private-Bank-theBank;
14- ---
15- ---public-static-final-int-START-=-1;
16- ---public-static-final-int-PIN-=-2;
17- ---public-static-final-int-ACCOUNT-=-3;
18- ---public-static-final-int-TRANSACT-=-4;
19-
20- ---/**
21- ------Constructs an ATM for a given bank.
22- ------@param-aBank-the bank to which this ATM connects
23- ---*/----
24- ---public-ATM(Bank-aBank)
25- ---{
26- ------theBank-=-aBank;
27- ------reset();
28- ---}
29-
we12 Chapter 12 Object-Oriented design
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
30- ---/**
31- ------Resets the ATM to the initial state.
32- ---*/
33- ---public-void-reset()
34- ---{
35- ------customerNumber-=--1;
36- ------currentAccount-=-null;
37- ------state-=-START;-------------
38- ---}
39-
40- ---/**-
41- ------Sets the current customer number-
42- ------and sets state to PIN.-
43- ------(Precondition: state is START)
44- ------@param-number-the customer number.
45- ---*/
46- ---public-void-setCustomerNumber(int-number)-
47- ---{
48- ------customerNumber-=-number;
49- ------state-=-PIN;
50- ---}
51-
52- ---/**-
53- ------Finds customer in bank.
54- ------If found sets state to ACCOUNT, else to START.
55- ------(Precondition: state is PIN)
56- ------@param-pin-the PIN of the current customer
57- ---*/
58- ---public-void-selectCustomer(int-pin)
59- ---{--
60- ------currentCustomer-
61- ---------=-theBank.findCustomer(customerNumber,-pin);
62- ------if-(currentCustomer-==-null)-
63- ------{
64- ---------state-=-START;
65- ------}
66- ------else-
67- ------{
68- ---------state-=-ACCOUNT;
69- ------}
70- ---}
71- ---
72- ---/**-
73- ------Sets current account to checking or savings. Sets-
74- ------state to TRANSACT.-
75- ------(Precondition: state is ACCOUNT or TRANSACT)
76- ------@param-account-one of CHECKING or SAVINGS
77- ---*/
78- ---public-void-selectAccount(int-account)
79- ---{
80- ------if-(account-==-CHECKING)
81- ------{
82-
---------currentAccount-=-currentCustomer.getCheckingAccount
();
83- ------}
84- ------else
85- ------{
86-
---------currentAccount-=-currentCustomer.getSavingsAccount()
;
87- ------}
88- ------state-=-TRANSACT;
89- ---}
simulating an automatic teller Machine we13
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
90-
91- ---/**-
92- ------Withdraws amount from current account.-
93- ------(Precondition: state is TRANSACT)
94- ------@param-value-the amount to withdraw
95- ---*/
96- ---public-void-withdraw(double-value)
97- ---{--
98- ------currentAccount.withdraw(value);
99- ---}
100-
101- ---/**-
102- ------Deposits amount to current account.-
103- ------(Precondition: state is TRANSACT)
104- ------@param-value-the amount to deposit
105- ---*/
106- ---public-void-deposit(double-value)
107- ---{--
108- ------currentAccount.deposit(value);
109- ---}
110-
111- ---/**-
112- ------Gets the balance of the current account.-
113- ------(Precondition: state is TRANSACT)
114- ------@return-the balance
115- ---*/
116- ---public-double-getBalance()
117- ---{--
118- ------return-currentAccount.getBalance();
119- ---}
120-
121- ---/**
122- ------Moves back to the previous state.
123- ---*/
124- ---public-void-back()
125- ---{
126- ------if-(state-==-TRANSACT)
127- ------{
128- ---------state-=-ACCOUNT;
129- ------}
130- ------else-if-(state-==-ACCOUNT)
131- ------{
132- ---------state-=-PIN;
133- ------}
134- ------else-if-(state-==-PIN)
135- ------{
136- ---------state-=-START;
137- ------}
138- ---}
139-
140- ---/**
141- ------Gets the current state of this ATM.
142- ------@return-the current state
143- ---*/
144- ---public-int-getState()
145- ---{
146- ------return-state;
147- ---}
148- }
we14 Chapter 12 Object-Oriented design
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
The following class implements a console-based user interface
for the ATM.
worked_example_1/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- ---------{
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- ------------{
47- ---------------theATM.selectAccount(ATM.CHECKING);
48- ------------}
49- ------------else-if-(command.equalsIgnoreCase("B"))
50- ------------{
51- ---------------theATM.selectAccount(ATM.SAVINGS);
52- ------------}
53- ------------else-if-(command.equalsIgnoreCase("C"))
54- ------------{
55- ---------------theATM.reset();
56- ------------}
simulating an automatic teller Machine we15
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
57- ------------else
58- ------------{
59-
---------------System.out.println("Illegal-input!");------------------
------
60- ------------}
61- ---------}
62- ---------else-if-(state-==-ATM.TRANSACT)
63- ---------{
64-
------------System.out.println("Balance="-+-theATM.getBalance
());
65-
------------System.out.print("A=Deposit,-B=Withdrawal,-C=Can
cel:-");
66- ------------String-command-=-in.next();
67- ------------if-(command.equalsIgnoreCase("A"))
68- ------------{
69- ---------------System.out.print("Amount:-");
70- ---------------double-amount-=-in.nextDouble();
71- ---------------theATM.deposit(amount);
72- ---------------theATM.back();
73- ------------}
74- ------------else-if-(command.equalsIgnoreCase("B"))
75- ------------{
76- ---------------System.out.print("Amount:-");
77- ---------------double-amount-=-in.nextDouble();
78- ---------------theATM.withdraw(amount);
79- ---------------theATM.back();
80- ------------}
81- ------------else-if-(command.equalsIgnoreCase("C"))
82- ------------{
83- ---------------theATM.back();
84- ------------}
85- ------------else
86- ------------{
87- ---------------System.out.println("Illegal-input!");
88- ------------}
89- ---------}
90- ------}
91- ---}
92- }
program run
Enter-customer-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
.-.-.
we16 Chapter 12 Object-Oriented design
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
Here are the user-interface classes for the GUI version of the
user interface.
worked_example_1/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 button pad labeled with digits.-
12- */
13- public-class-KeyPad-extends-JPanel
14- {
15- ---private-JPanel-buttonPanel;
16- ---private-JButton-clearButton;
17- ---private-JTextField-display;
18-
19- ---/**
20- ------Constructs the keypad panel.-
21- ---*/
22- ---public-KeyPad()
23- ---{-
24- ------setLayout(new-BorderLayout());
25- ---
26- ------//-Add display field-
27- ---
28- ------display-=-new-JTextField();
29- ------add(display,-"North");
30-
31- ------//-Make button panel-
32-
33- ------buttonPanel-=-new-JPanel();
34- ------buttonPanel.setLayout(new-GridLayout(4,-3));
35- ------
36- ------//-Add digit buttons-
37- ------
38- ------addButton("7");
39- ------addButton("8");
40- ------addButton("9");
41- ------addButton("4");
42- ------addButton("5");
43- ------addButton("6");
44- ------addButton("1");
45- ------addButton("2");
46- ------addButton("3");
47- ------addButton("0");------
48- ------addButton(".");
49- ------
50- ------//-Add clear entry button-
51- ------
52- ------clearButton-=-new-JButton("CE");
53- ------buttonPanel.add(clearButton);
54-
55- ------class-ClearButtonListener-implements-ActionListener
56- ------{-
simulating an automatic teller Machine we17
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
57- ---------public-void-actionPerformed(ActionEvent-event)
58- ---------{-
59- ------------display.setText("");
60- ---------}
61- ------}
62- ------ActionListener-listener-=-new-ClearButtonListener();-
63-
64- ------clearButton.addActionListener(new-
65- ------------ClearButtonListener());------------
66-
67- ------add(buttonPanel,-"Center");
68- ---}
69-
70- ---/**
71- ------Adds a button to the button panel.-
72- ------@param-label-the button label-
73- ---*/
74- ---private-void-addButton(final-String-label)
75- ---{-
76- ------class-DigitButtonListener-implements-ActionListener
77- ------{-
78- ---------public-void-actionPerformed(ActionEvent-event)
79- ---------{-
80­ ­­­­­­­­­­­­//­Don’t add two decimal points­
81- ------------if-(label.equals(".")-
82- ------------------&&-display.getText().indexOf(".")-!=--1)-
83- ------------{
84- ---------------return;
85- ------------}
86-
87- ------------//-Append label text to button-
88- ------------display.setText(display.getText()-+-label);
89- ---------}
90- ------}
91-
92- ------JButton-button-=-new-JButton(label);
93- ------buttonPanel.add(button);
94- ------ActionListener-listener-=-new-DigitButtonListener();
95- ------button.addActionListener(listener);
96- ---}
97-
98- ---/**-
99- ------Gets the value that the user entered.-
100- ------@return-the value in the text field of the keypad-
101 - ---*/
102 - ---public-double-getValue()
103 - ---{-
104 - ------return-Double.parseDouble(display.getText());
105 - ---}
106 - ---
107 - ---/**-
108 - ------Clears the display.-
109 - ---*/
110 - ---public-void-clear()
111 - ---{-
112 - ------display.setText("");
113 - ---}
114 - }
we18 Chapter 12 Object-Oriented design
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
worked_example_1/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
14- {-
15- ---private-static-final-int-FRAME_WIDTH-=-300;
16- ---private-static-final-int-FRAME_HEIGHT-=-300;
17-
18- ---private-JButton-aButton;
19- ---private-JButton-bButton;
20- ---private-JButton-cButton;
21- ---
22- ---private-KeyPad-pad;
23- ---private-JTextArea-display;
24-
25- ---private-ATM-theATM;
26-
27- ---/**
28- ------Constructs the user interface of the ATM frame.-
29- ---*/
30- ---public-ATMFrame(ATM-anATM)
31- ---{-
32- ------theATM-=-anATM;
33-
34- ------//-Construct components-
35- ------pad-=-new-KeyPad();
36-
37- ------display-=-new-JTextArea(4,-20);
38- ------
39- ------aButton-=-new-JButton("--A--");
40- ------aButton.addActionListener(new-AButtonListener());
41-
42- ------bButton-=-new-JButton("--B--");
43- ------bButton.addActionListener(new-BButtonListener());
44-
45- ------cButton-=-new-JButton("--C--");
46- ------cButton.addActionListener(new-CButtonListener());
47- ------
48- ------//-Add components-
49-
50- ------JPanel-buttonPanel-=-new-JPanel();
51- ------buttonPanel.add(aButton);
52- ------buttonPanel.add(bButton);
53- ------buttonPanel.add(cButton);
54- ------
55- ------setLayout(new-FlowLayout());
56- ------add(pad);
57- ------add(display);
58- ------add(buttonPanel);
simulating an automatic teller Machine we19
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
59- ------showState();
60-
61- ------setSize(FRAME_WIDTH,-FRAME_HEIGHT);
62- ---}
63-
64- ---/**-
65- ------Updates display message.-
66- ---*/
67- ---public-void-showState()
68- ---{-
69- ------int-state-=-theATM.getState();
70- ------pad.clear();
71- ------if-(state-==-ATM.START)
72- ------{
73-
---------display.setText("Enter-customer-numbernA-=-OK");
74- ------}
75- ------else-if-(state-==-ATM.PIN)
76- ------{
77- ---------display.setText("Enter-PINnA-=-OK");
78- ------}
79- ------else-if-(state-==-ATM.ACCOUNT)
80- ------{
81- ---------display.setText("Select-Accountn"-
82- ---------------+-"A-=-CheckingnB-=-SavingsnC-=-Exit");
83- ------}
84- ------else-if-(state-==-ATM.TRANSACT)
85- ------{
86- ---------display.setText("Balance-=-"-
87- ---------------+-theATM.getBalance()-
88- ---------------+-"nEnter-amount-and-select-transactionn"
89-
---------------+-"A-=-WithdrawnB-=-DepositnC-=-Cancel");
90- ------}
91- ---}
92- ---
93- ---class-AButtonListener-implements-ActionListener
94- ---{-
95- ------public-void-actionPerformed(ActionEvent-event)
96- ------{-
97- ---------int-state-=-theATM.getState();
98- ---------if-(state-==-ATM.START)
99- ---------{
100-
------------theATM.setCustomerNumber((int)-pad.getValue());
101- ---------}
102- ---------else-if-(state-==-ATM.PIN)
103- ---------{
104- ------------theATM.selectCustomer((int)-pad.getValue());
105- ---------}
106- ---------else-if-(state-==-ATM.ACCOUNT)
107- ---------{
108- ------------theATM.selectAccount(ATM.CHECKING);
109- ---------}
110- ---------else-if-(state-==-ATM.TRANSACT)
111- ---------{
112- ------------theATM.withdraw(pad.getValue());
113- ------------theATM.back();
114- ---------}
115- ---------showState();
116- ------}
117- ---}
118- ---
we20 Chapter 12 Object-Oriented design
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
119- ---class-BButtonListener-implements-ActionListener
120- ---{-
121- ------public-void-actionPerformed(ActionEvent-event)
122-- ------{-
123- ---------int-state-=-theATM.getState();
124- ---------if-(state-==-ATM.ACCOUNT)
125- ---------{
126- ------------theATM.selectAccount(ATM.SAVINGS);
127- ---------}
128- ---------else-if-(state-==-ATM.TRANSACT)
129- ---------{
130- ------------theATM.deposit(pad.getValue());
131- ------------theATM.back();
132- ---------}
133- ---------showState();
134- ------}
135- ---}
136-
137- ---class-CButtonListener-implements-ActionListener
138- ---{-
139- ------public-void-actionPerformed(ActionEvent-event)
140- ------{-
141- ---------int-state-=-theATM.getState();
142- ---------if-(state-==-ATM.ACCOUNT)
143- ---------{
144- ------------theATM.reset();
145- ---------}
146- ---------else-if-(state-==-ATM.TRANSACT)
147- ---------{
148- ------------theATM.back();
149- ---------}
150- ---------showState();
151- ------}
152- ---}
153- }
worked_example_1/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-ATM-Viewer
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- ------{-
simulating an automatic teller Machine we21
Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John
Wiley and Sons, Inc. All rights reserved.
22-
---------JOptionPane.showMessageDialog(null,-"Error-opening-a
ccounts-file.");
23- ---------return;
24- ------}
25-
26- ------JFrame-frame-=-new-ATMFrame(theATM);
27- ------frame.setTitle("First-National-Bank-of-Java");------
28-
------frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS
E);
29- ------frame.setVisible(true);
30- ---}
31- }
__MACOSX/._Chapter12 Worked out example.pdf
CPII-Chapter12Lab copy.docx
Computer Programming II
Chapter 12 Lab
Put your name here:
1. Please read the attached document and follow the instruction
and implement the program
2. Run the ATMsimulator program
An example input / output given below:
Enter customer 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: A
Balance=1000.0
A=Deposit, B=Withdrawal, C=Cancel: B
Amount: 500
A=Checking, B=Savings, C=Quit: a
Balance=500.0
A=Deposit, B=Withdrawal, C=Cancel:
An example screen shot is below. Place the screen shot of the
frame here.
(How to capture the screenshot:
While the program is running press ALT and PrtSc keys
together. Go to the word doc and do a paste)
3. In the ATMViewer file
Change the title to include your name: frame.setTitle("ATM
BY Annu Prabhakar");
Run the ATMviewer program. Place your screen shot like the
one below.
Submitting your work: Make sure that you saved your answers
in this document and that your file is correctly named:
Lastname_Firstname_Ch12Lab.docx using your name.
Use the Blackboard Assignment mechanism to submit your file.
__MACOSX/._CPII-Chapter12Lab copy.docx
customers.txt
1 1234
2 2468
3 3692
4 4826
5 5050
6 6284
7 7418
8 8642
9 9876
__MACOSX/._customers.txt

More Related Content

PPT
Csphtp1 06
PDF
JFokus 2016 - Beyond Lambdas - the Aftermath
PPTX
Ensure code quality with vs2012
PDF
JDays 2016 - Beyond Lambdas - the Aftermath
DOCX
Exercícios Netbeans - Vera Cymbron
PDF
Polygon .java package chegg2;public class Polygon { Var.pdf
PDF
Company Call System
Csphtp1 06
JFokus 2016 - Beyond Lambdas - the Aftermath
Ensure code quality with vs2012
JDays 2016 - Beyond Lambdas - the Aftermath
Exercícios Netbeans - Vera Cymbron
Polygon .java package chegg2;public class Polygon { Var.pdf
Company Call System

Similar to ch12.DS_Store__MACOSXch12._.DS_Storech12section_1.D.docx (20)

PPTX
20.1 Java working with abstraction
DOCX
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
DOCX
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
DOCX
New microsoft office word document
DOC
原创 读《大话设计模式》---外观模式(Facade) 收藏
PDF
Class 6 2ciclo
DOCX
ETM Server
PDF
GeeCon 2016 - Beyond Lambdas, the Aftermath
PDF
Spotify 2016 - Beyond Lambdas - the Aftermath
PDF
This is a C# project . I am expected to create as this image shows. .pdf
DOCX
C# labprograms
PPT
Csphtp1 08
PDF
Modern Android Architecture
PDF
TDD CrashCourse Part4: Improving Testing
PDF
Object oriented programming
PPT
Class & Object - User Defined Method
PDF
import java.util.Random;ASSIGNMENT #2 MATRIX ARITHMETIC Cla.pdf
PPTX
Применение шаблона проектирования MVVM при разработке архитектуры Windows Pho...
PPT
3433 Ch09 Ppt
PPT
Csphtp1 09
20.1 Java working with abstraction
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
New microsoft office word document
原创 读《大话设计模式》---外观模式(Facade) 收藏
Class 6 2ciclo
ETM Server
GeeCon 2016 - Beyond Lambdas, the Aftermath
Spotify 2016 - Beyond Lambdas - the Aftermath
This is a C# project . I am expected to create as this image shows. .pdf
C# labprograms
Csphtp1 08
Modern Android Architecture
TDD CrashCourse Part4: Improving Testing
Object oriented programming
Class & Object - User Defined Method
import java.util.Random;ASSIGNMENT #2 MATRIX ARITHMETIC Cla.pdf
Применение шаблона проектирования MVVM при разработке архитектуры Windows Pho...
3433 Ch09 Ppt
Csphtp1 09

More from cravennichole326 (20)

DOCX
Examine how nature is discussed throughout The Open Boat.”  Loo.docx
DOCX
Examine All Children Can Learn. Then, search the web for effec.docx
DOCX
Examine each of these items, which are available on the internet .docx
DOCX
Examine a web browser interface and describe the various forms .docx
DOCX
Examine a scenario that includes an inter-group conflict. In this sc.docx
DOCX
Examine a current law, or a bill proposing a law, that has to do wit.docx
DOCX
Exam IT 505Multiple Choice (20 questions , 2 points each)Pleas.docx
DOCX
EXAMEstructura 8.1 - Miniprueba AVerbosCom.docx
DOCX
Examine current practice guidelines related to suicide screeni.docx
DOCX
Examine Case Study Pakistani Woman with Delusional Thought Processe.docx
DOCX
Examination of Modern LeadershipModule 1 Leadership History, F.docx
DOCX
Examine current international OB issues that challenge organizat.docx
DOCX
Executive Program Practical Connection Assignment .docx
DOCX
Executive Program Practical Connection Assignment Component .docx
DOCX
Executive Program Group Project Assignment Component Profi.docx
DOCX
Executive Practical Connection Activityit is a priority that stu.docx
DOCX
Executive FunctionThe Search for an Integrated AccountMari.docx
DOCX
Executive Compensation and IncentivesMartin J. ConyonEx.docx
DOCX
Executing the StrategyLearning ObjectivesAfter reading.docx
DOCX
Executing Strategies in a Global Environment Examining the Case of .docx
Examine how nature is discussed throughout The Open Boat.”  Loo.docx
Examine All Children Can Learn. Then, search the web for effec.docx
Examine each of these items, which are available on the internet .docx
Examine a web browser interface and describe the various forms .docx
Examine a scenario that includes an inter-group conflict. In this sc.docx
Examine a current law, or a bill proposing a law, that has to do wit.docx
Exam IT 505Multiple Choice (20 questions , 2 points each)Pleas.docx
EXAMEstructura 8.1 - Miniprueba AVerbosCom.docx
Examine current practice guidelines related to suicide screeni.docx
Examine Case Study Pakistani Woman with Delusional Thought Processe.docx
Examination of Modern LeadershipModule 1 Leadership History, F.docx
Examine current international OB issues that challenge organizat.docx
Executive Program Practical Connection Assignment .docx
Executive Program Practical Connection Assignment Component .docx
Executive Program Group Project Assignment Component Profi.docx
Executive Practical Connection Activityit is a priority that stu.docx
Executive FunctionThe Search for an Integrated AccountMari.docx
Executive Compensation and IncentivesMartin J. ConyonEx.docx
Executing the StrategyLearning ObjectivesAfter reading.docx
Executing Strategies in a Global Environment Examining the Case of .docx

Recently uploaded (20)

PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
Indian roads congress 037 - 2012 Flexible pavement
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
PDF
Hazard Identification & Risk Assessment .pdf
PPTX
Digestion and Absorption of Carbohydrates, Proteina and Fats
PDF
1_English_Language_Set_2.pdf probationary
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PPTX
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
Cell Types and Its function , kingdom of life
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Introduction to Building Materials
PDF
Trump Administration's workforce development strategy
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
advance database management system book.pdf
PPTX
Unit 4 Skeletal System.ppt.pptxopresentatiom
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Paper A Mock Exam 9_ Attempt review.pdf.
Indian roads congress 037 - 2012 Flexible pavement
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
Hazard Identification & Risk Assessment .pdf
Digestion and Absorption of Carbohydrates, Proteina and Fats
1_English_Language_Set_2.pdf probationary
A powerpoint presentation on the Revised K-10 Science Shaping Paper
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
Final Presentation General Medicine 03-08-2024.pptx
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Cell Types and Its function , kingdom of life
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Introduction to Building Materials
Trump Administration's workforce development strategy
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
advance database management system book.pdf
Unit 4 Skeletal System.ppt.pptxopresentatiom
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape

ch12.DS_Store__MACOSXch12._.DS_Storech12section_1.D.docx

  • 1. ch12/.DS_Store __MACOSX/ch12/._.DS_Store ch12/section_1/.DS_Store __MACOSX/ch12/section_1/._.DS_Store ch12/section_1/CashRegister.javach12/section_1/CashRegister.j ava/** A cash register totals up sales and computes change due. */ publicclassCashRegister { privatedouble purchase; privatedouble payment; /** Constructs a cash register with no money in it. */ publicCashRegister() { purchase =0; payment =0; } /** Records the sale of an item. @param amount the price of the item */ publicvoid addItem(double amount) { double newTotal = purchase + amount;
  • 2. purchase = newTotal; } /** Enters the payment received from the customer; should be c alled once for each coin type. @param coinCount the number of coins @param coinType the type of the coins in the payment */ publicvoid enterPayment(int coinCount,Coin coinType) { payment = payment + coinCount * coinType.getValue(); } /** Computes the change due and resets the machine for the nex t customer. @return the change due to the customer */ publicdouble giveChange() { double change = payment - purchase; purchase =0; payment =0; return change; } } __MACOSX/ch12/section_1/._CashRegister.java ch12/section_1/CashRegister.java.html 1 /** 2 A cash register totals up sales and computes change due. 3 */ 4 public class CashRegister 5 { 6 private double purchase; 7 private double payment; 8 9 /** 10 Constructs a cash
  • 3. register with no money in it. 11 */ 12 public CashRegister() 13 { 14 purchase = 0; 15 payment = 0; 16 } 17 18 /** 19 Records the sale of an item. 20 @param amount the price of the item 21 */ 22 public void addItem(double amount) 23 { 24 double newTotal = purchase + amount; 25 purchase = newTotal; 26 } 27 28 /** 29 Enters the payment received from the customer; should be called once 30 for each coin type. 31 @param coinCount the number of coins 32 @param coinType the type of the coins in the payment 33 */ 34 public void enterPayment(int coinCount, Coin coinType) 35 { 36 payment = payment + coinCount * coinType.getValue(); 37 } 38 39 /** 40 Computes the change due and resets the machine for the next customer. 41 @return the change due to the customer 42 */ 43 public double giveChange() 44 { 45 double change = payment - purchase; 46 purchase = 0; 47 payment = 0; 48 return change; 49 } 50 } __MACOSX/ch12/section_1/._CashRegister.java.html ch12/section_1/CashRegisterTester.javach12/section_1/CashReg isterTester.java/** This program tests the CashRegister class. */ publicclassCashRegisterTester { publicstaticvoid main(String[] args) { CashRegister register1 =newCashRegister(); register1.addItem(1.95); register1.addItem(0.95); register1.addItem(2.50); Coin dollar =newCoin(1.0,"Dollar"); Coin quarter =newCoin(0.25,"Quarter");
  • 4. register1.enterPayment(6, dollar); register1.enterPayment(3, quarter); System.out.printf("Change: %.2fn", register1.giveChange()); } } __MACOSX/ch12/section_1/._CashRegisterTester.java ch12/section_1/CashRegisterTester.java.html 1 /** 2 This program tests the CashRegister class. 3 */ 4 public class CashRegisterTester 5 { 6 public static void main(String[] args) 7 { 8 CashRegister register1 = new CashRegister(); 9 register1.addItem(1.95); 10 register1.addItem(0.95); 11 register1.addItem(2.50); 12 13 Coin dollar = new Coin(1.0, "Dollar"); 14 Coin quarter = new Coin(0.25, "Quarter"); 15 16 register1.enterPayment(6, dollar); 17 register1.enterPayment(3, quarter); 18 19 System.out.printf("Change: %.2fn", register1.giveChange()); 20 } 21 } __MACOSX/ch12/section_1/._CashRegisterTester.java.html ch12/section_1/Coin.javach12/section_1/Coin.java/** A coin with a monetary value. */ publicclassCoin { privatedouble value; privateString name; /** Constructs a coin.
  • 5. @param aValue the monetary value of the coin. @param aName the name of the coin */ publicCoin(double aValue,String aName) { value = aValue; name = aName; } /** Gets the coin value. @return the value */ publicdouble getValue() { return value; } /** Gets the coin name. @return the name */ publicString getName() { return name; } } __MACOSX/ch12/section_1/._Coin.java ch12/section_1/Coin.java.html 1 /** 2 A coin with a monetary value. 3 */ 4 public class Coin 5 { 6 private double value; 7 private String name; 8 9 /** 10 Constructs a coin. 11 @param aValue the monetary value of the coin. 12 @param aName the name of the coin 13
  • 6. */ 14 public Coin(double aValue, String aName) 15 { 16 value = aValue; 17 name = aName; 18 } 19 20 /** 21 Gets the coin value. 22 @return the value 23 */ 24 public double getValue() 25 { 26 return value; 27 } 28 29 /** 30 Gets the coin name. 31 @return the name 32 */ 33 public String getName() 34 { 35 return name; 36 } 37 } __MACOSX/ch12/section_1/._Coin.java.html __MACOSX/ch12/._section_1 ch12/section_2/.DS_Store __MACOSX/ch12/section_2/._.DS_Store ch12/section_2/ChoiceQuestion.javach12/section_2/ChoiceQues tion.javaimport java.util.ArrayList; /** A question with multiple choices. */ publicclassChoiceQuestionextendsQuestion { privateArrayList<String> choices; /** Constructs a choice question with no choices. */ publicChoiceQuestion() { choices =newArrayList<String>(); } /** Adds an answer choice to this question.
  • 7. @param choice the choice to add @param correct true if this is the correct choice, false otherwise */ publicvoid addChoice(String choice,boolean correct) { choices.add(choice); if(correct) { // Convert choices.size() to string String choiceString =""+ choices.size(); setAnswer(choiceString); } } publicvoid display() { // Display the question text super.display(); // Display the answer choices for(int i =0; i < choices.size(); i++) { int choiceNumber = i +1; System.out.println(choiceNumber +": "+ choices.get(i)); } } } __MACOSX/ch12/section_2/._ChoiceQuestion.java ch12/section_2/ChoiceQuestion.java.html 1 import java.util.ArrayList; 2 3 /** 4 A question with multiple choices. 5 */ 6 public class ChoiceQuestion extends Question 7 { 8 private ArrayList<String> choices; 9 10 /** 11 Constructs a choice question with no choices. 12 */ 13
  • 8. public ChoiceQuestion() 14 { 15 choices = new ArrayList<String>(); 16 } 17 18 /** 19 Adds an answer choice to this question. 20 @param choice the choice to add 21 @param correct true if this is the correct choice, false otherwise 22 */ 23 public void addChoice(String choice, boolean correct) 24 { 25 choices.add(choice); 26 if (correct) 27 { 28 // Convert choices.size() to string 29 String choiceString = "" + choices.size(); 30 setAnswer(choiceString); 31 } 32 } 33 34 public void display() 35 { 36 // Display the question text 37 super.display(); 38 // Display the answer choices 39 for (int i = 0; i < choices.size(); i++) 40 { 41 int choiceNumber = i + 1; 42 System.out.println(choiceNumber + ": " + choices.get(i)); 43 } 44 } 45 } 46 __MACOSX/ch12/section_2/._ChoiceQuestion.java.html ch12/section_2/Question.javach12/section_2/Question.java/** A question with a text and an answer. */ publicclassQuestion { privateString text; privateString answer; /** Constructs a question with empty question and answer. */ publicQuestion() { text =""; answer =""; } /**
  • 9. Sets the question text. @param questionText the text of this question */ publicvoid setText(String questionText) { text = questionText; } /** Sets the answer for this question. @param correctResponse the answer */ publicvoid setAnswer(String correctResponse) { answer = correctResponse; } /** Checks a given response for correctness. @param response the response to check @return true if the response was correct, false otherwise */ publicboolean checkAnswer(String response) { return response.equals(answer); } /** Displays this question. */ publicvoid display() { System.out.println(text); } }
  • 10. __MACOSX/ch12/section_2/._Question.java ch12/section_2/Question.java.html 1 /** 2 A question with a text and an answer. 3 */ 4 public class Question 5 { 6 private String text; 7 private String answer; 8 9 /** 10 Constructs a question with empty question and answer. 11 */ 12 public Question() 13 { 14 text = ""; 15 answer = ""; 16 } 17 18 /** 19 Sets the question text. 20 @param questionText the text of this question 21 */ 22 public void setText(String questionText) 23 { 24 text = questionText; 25 } 26 27 /** 28 Sets the answer for this question. 29 @param correctResponse the answer 30 */ 31 public void setAnswer(String correctResponse) 32 { 33 answer = correctResponse; 34 } 35 36 /** 37 Checks a given response for correctness. 38 @param response the response to check 39 @return true if the response was correct, false otherwise 40 */ 41 public boolean checkAnswer(String response) 42 { 43 return response.equals(answer); 44 } 45 46 /** 47 Displays this question. 48 */ 49 public void display() 50 { 51 System.out.println(text); 52 } 53 } __MACOSX/ch12/section_2/._Question.java.html ch12/section_2/Quiz.javach12/section_2/Quiz.javaimport java.u til.ArrayList; import java.util.Scanner; /** A quiz contains a list of questions. */ publicclassQuiz { privateArrayList<Question> questions;
  • 11. /** Constructs a quiz with no questions. */ publicQuiz() { questions =newArrayList<Question>(); } /** Adds a question to this quiz. @param q the question */ publicvoid addQuestion(Question q) { questions.add(q); } /** Presents the questions to the user and checks the response. */ publicvoid presentQuestions() { Scanner in =newScanner(System.in); for(Question q : questions) { q.display(); System.out.print("Your answer: "); String response = in.nextLine(); System.out.println(q.checkAnswer(response)); } } }
  • 12. __MACOSX/ch12/section_2/._Quiz.java ch12/section_2/Quiz.java.html 1 import java.util.ArrayList; 2 import java.util.Scanner; 3 4 /** 5 A quiz contains a list of questions. 6 */ 7 public class Quiz 8 { 9 private ArrayList<Question> questions; 10 11 /** 12 Constructs a quiz with no questions. 13 */ 14 public Quiz() 15 { 16 questions = new ArrayList<Question>(); 17 } 18 19 /** 20 Adds a question to this quiz. 21 @param q the question 22 */ 23 public void addQuestion(Question q) 24 { 25 questions.add(q); 26 } 27 28 /** 29 Presents the questions to the user and checks the response. 30 */ 31 public void presentQuestions() 32 { 33 Scanner in = new Scanner(System.in); 34 35 for (Question q : questions) 36 { 37 q.display(); 38 System.out.print("Your answer: "); 39 String response = in.nextLine(); 40 System.out.println(q.checkAnswer(response)); 41 } 42 } 43 } 44 __MACOSX/ch12/section_2/._Quiz.java.html ch12/section_2/QuizDemo.javach12/section_2/QuizDemo.javap ublicclassQuizDemo { publicstaticvoid main(String[] args) { Question first =newQuestion(); first.setText("Who was the inventor of Java?"); first.setAnswer("James Gosling"); ChoiceQuestion second =newChoiceQuestion(); second.setText("In which country was the inventor of Java born?"); second.addChoice("Australia",false); second.addChoice("Canada",true);
  • 13. second.addChoice("Denmark",false); second.addChoice("United States",false); Quiz q =newQuiz(); q.addQuestion(first); q.addQuestion(second); q.presentQuestions(); } } __MACOSX/ch12/section_2/._QuizDemo.java ch12/section_2/QuizDemo.java.html 1 public class QuizDemo 2 { 3 public static void main(String[] args) 4 { 5 Question first = new Question(); 6 first.setText("Who was the inventor of Java?"); 7 first.setAnswer("James Gosling"); 8 9 ChoiceQuestion second = new ChoiceQuestion(); 10 second.setText("In which country was the inventor of Java born?"); 11 second.addChoice("Australia", false); 12 second.addChoice("Canada", true); 13 second.addChoice("Denmark", false); 14 second.addChoice("United States", false); 15 16 Quiz q = new Quiz(); 17 q.addQuestion(first); 18 q.addQuestion(second); 19 q.presentQuestions(); 20 } 21 } __MACOSX/ch12/section_2/._QuizDemo.java.html __MACOSX/ch12/._section_2 ch12/section_3/.DS_Store __MACOSX/ch12/section_3/._.DS_Store
  • 14. ch12/section_3/Address.javach12/section_3/Address.java/** Describes a mailing address. */ publicclassAddress { privateString name; privateString street; privateString city; privateString state; privateString zip; /** Constructs a mailing address. @param aName the recipient name @param aStreet the street @param aCity the city @param aState the two-letter state code @param aZip the ZIP postal code */ publicAddress(String aName,String aStreet, String aCity,String aState,String aZip) { name = aName; street = aStreet; city = aCity; state = aState; zip = aZip; } /** Formats the address. @return the address as a string with three lines */ publicString format() { return name +"n"+ street +"n"
  • 15. + city +", "+ state +" "+ zip; } } __MACOSX/ch12/section_3/._Address.java ch12/section_3/Address.java.html 1 /** 2 Describes a mailing address. 3 */ 4 public class Address 5 { 6 private String name; 7 private String street; 8 private String city; 9 private String state; 10 private String zip; 11 12 /** 13 Constructs a mailing address. 14 @param aName the recipient name 15 @param aStreet the street 16 @param aCity the city 17 @param aState the two-letter state code 18 @param aZip the ZIP postal code 19 */ 20 public Address(String aName, String aStreet, 21 String aCity, String aState, String aZip) 22 { 23 name = aName; 24 street = aStreet; 25 city = aCity; 26 state = aState; 27 zip = aZip; 28 } 29 30 /** 31 Formats the address. 32 @return the address as a string with three lines 33 */ 34 public String format() 35 { 36 return name + "n" + street + "n" 37 + city + ", " + state + " " + zip; 38 } 39 } 40 __MACOSX/ch12/section_3/._Address.java.html ch12/section_3/Invoice.javach12/section_3/Invoice.javaimport j ava.util.ArrayList; /** Describes an invoice for a set of purchased products. */ publicclassInvoice { privateAddress billingAddress;
  • 16. privateArrayList<LineItem> items; /** Constructs an invoice. @param anAddress the billing address */ publicInvoice(Address anAddress) { items =newArrayList<LineItem>(); billingAddress = anAddress; } /** Adds a charge for a product to this invoice. @param aProduct the product that the customer ordered @param quantity the quantity of the product */ publicvoid add(Product aProduct,int quantity) { LineItem anItem =newLineItem(aProduct, quantity); items.add(anItem); } /** Formats the invoice. @return the formatted invoice */ publicString format() { String r =" I N V O I C Enn" + billingAddress.format() +String.format("nn%-30s%8s%5s%8sn", "Description","Price","Qty","Total"); for(LineItem item : items) {
  • 17. r = r + item.format()+"n"; } r = r +String.format("nAMOUNT DUE: $%8.2f", getAmou ntDue()); return r; } /** Computes the total amount due. @return the amount due */ privatedouble getAmountDue() { double amountDue =0; for(LineItem item : items) { amountDue = amountDue + item.getTotalPrice(); } return amountDue; } } __MACOSX/ch12/section_3/._Invoice.java ch12/section_3/Invoice.java.html 1 import java.util.ArrayList; 2 3 /** 4 Describes an invoice for a set of purchased products. 5 */ 6 public class Invoice 7 { 8 private Address billingAddress; 9 private ArrayList<LineItem> items; 10 11 /** 12 Constructs an invoice. 13 @param anAddress the billing address 14 */ 15 public Invoice(Address anAddress) 16 { 17 items = new ArrayList<LineItem>(); 18 billingAddress = anAddress; 19 } 20 21 /** 22 Adds a charge for a product to this
  • 18. invoice. 23 @param aProduct the product that the customer ordered 24 @param quantity the quantity of the product 25 */ 26 public void add(Product aProduct, int quantity) 27 { 28 LineItem anItem = new LineItem(aProduct, quantity); 29 items.add(anItem); 30 } 31 32 /** 33 Formats the invoice. 34 @return the formatted invoice 35 */ 36 public String format() 37 { 38 String r = " I N V O I C Enn" 39 + billingAddress.format() 40 + String.format("nn%-30s%8s%5s%8sn", 41 "Description", "Price", "Qty", "Total"); 42 43 for (LineItem item : items) 44 { 45 r = r + item.format() + "n"; 46 } 47 48 r = r + String.format("nAMOUNT DUE: $%8.2f", getAmountDue()); 49 50 return r; 51 } 52 53 /** 54 Computes the total amount due. 55 @return the amount due 56 */ 57 private double getAmountDue() 58 { 59 double amountDue = 0; 60 for (LineItem item : items) 61 { 62 amountDue = amountDue + item.getTotalPrice(); 63 } 64 return amountDue; 65 } 66 } __MACOSX/ch12/section_3/._Invoice.java.html ch12/section_3/InvoicePrinter.javach12/section_3/InvoicePrinte r.java/** This program demonstrates the invoice classes by printing a sample invoice. */ publicclassInvoicePrinter { publicstaticvoid main(String[] args) { Address samsAddress =newAddress("Sam's Small Appliances", "100 Main Street","Anytown","CA","98765"); Invoice samsInvoice =newInvoice(samsAddress);
  • 19. samsInvoice.add(newProduct("Toaster",29.95),3); samsInvoice.add(newProduct("Hair dryer",24.95),1); samsInvoice.add(newProduct("Car vacuum",19.99),2); System.out.println(samsInvoice.format()); } } __MACOSX/ch12/section_3/._InvoicePrinter.java ch12/section_3/InvoicePrinter.java.html 1 /** 2 This program demonstrates the invoice classes by printing 3 a sample invoice. 4 */ 5 public class InvoicePrinter 6 { 7 public static void main(String[] args) 8 { 9 Address samsAddress 10 = new Address("Sam's Small Appliances", 11 "100 Main Street", "Anytown", "CA", "98765"); 12 13 Invoice samsInvoice = new Invoice(samsAddress); 14 samsInvoice.add(new Product("Toaster", 29.95), 3); 15 samsInvoice.add(new Product("Hair dryer", 24.95), 1); 16 samsInvoice.add(new Product("Car vacuum", 19.99), 2); 17 18 System.out.println(samsInvoice.format()); 19 } 20 } 21 22 23 __MACOSX/ch12/section_3/._InvoicePrinter.java.html ch12/section_3/LineItem.javach12/section_3/LineItem.java/** Describes a quantity of an article to purchase. */ publicclassLineItem { privateint quantity;
  • 20. privateProduct theProduct; /** Constructs an item from the product and quantity. @param aProduct the product @param aQuantity the item quantity */ publicLineItem(Product aProduct,int aQuantity) { theProduct = aProduct; quantity = aQuantity; } /** Computes the total cost of this line item. @return the total price */ publicdouble getTotalPrice() { return theProduct.getPrice()* quantity; } /** Formats this item. @return a formatted string of this item */ publicString format() { returnString.format("%-30s%8.2f%5d%8.2f", theProduct.getDescription(), theProduct.getPrice(), quantity, getTotalPrice()); } } __MACOSX/ch12/section_3/._LineItem.java
  • 21. ch12/section_3/LineItem.java.html 1 /** 2 Describes a quantity of an article to purchase. 3 */ 4 public class LineItem 5 { 6 private int quantity; 7 private Product theProduct; 8 9 /** 10 Constructs an item from the product and quantity. 11 @param aProduct the product 12 @param aQuantity the item quantity 13 */ 14 public LineItem(Product aProduct, int aQuantity) 15 { 16 theProduct = aProduct; 17 quantity = aQuantity; 18 } 19 20 /** 21 Computes the total cost of this line item. 22 @return the total price 23 */ 24 public double getTotalPrice() 25 { 26 return theProduct.getPrice() * quantity; 27 } 28 29 /** 30 Formats this item. 31 @return a formatted string of this item 32 */ 33 public String format() 34 { 35 return String.format("%- 30s%8.2f%5d%8.2f", 36 theProduct.getDescription(), theProduct.getPrice(), 37 quantity, getTotalPrice()); 38 } 39 } __MACOSX/ch12/section_3/._LineItem.java.html ch12/section_3/Product.javach12/section_3/Product.java/** Describes a product with a description and a price. */ publicclassProduct { privateString description; privatedouble price; /** Constructs a product from a description and a price. @param aDescription the product description @param aPrice the product price */ publicProduct(String aDescription,double aPrice) {
  • 22. description = aDescription; price = aPrice; } /** Gets the product description. @return the description */ publicString getDescription() { return description; } /** Gets the product price. @return the unit price */ publicdouble getPrice() { return price; } } __MACOSX/ch12/section_3/._Product.java ch12/section_3/Product.java.html 1 /** 2 Describes a product with a description and a price. 3 */ 4 public class Product 5 { 6 private String description; 7 private double price; 8 9 /** 10 Constructs a product from a description and a price. 11 @param aDescription the product description 12 @param aPrice the product price 13 */ 14 public Product(String aDescription, double aPrice) 15 { 16 description = aDescription; 17 price = aPrice; 18 } 19 20 /** 21 Gets the product description. 22
  • 23. @return the description 23 */ 24 public String getDescription() 25 { 26 return description; 27 } 28 29 /** 30 Gets the product price. 31 @return the unit price 32 */ 33 public double getPrice() 34 { 35 return price; 36 } 37 } 38 __MACOSX/ch12/section_3/._Product.java.html __MACOSX/ch12/._section_3 ch12/section_4/.DS_Store __MACOSX/ch12/section_4/._.DS_Store ch12/section_4/BankAccountTester.javach12/section_4/BankAc countTester.javaimport com.horstmann.BankAccount; /** This program tests the BankAccount class. */ publicclassBankAccountTester { /** Tests the methods of the BankAccount class. @param args not used */ publicstaticvoid main(String[] args) { BankAccount harrysAccount =newBankAccount(1000); harrysAccount.deposit(500);// Balance is now $1500 harrysAccount.withdraw(2000);// Balance is now $1490 harrysAccount.addInterest(1);// Balance is now $1490 + 14. 90 System.out.printf("%.2fn", harrysAccount.getBalance()); System.out.println("Expected: 1504.90"); }
  • 24. } __MACOSX/ch12/section_4/._BankAccountTester.java ch12/section_4/BankAccountTester.java.html 1 import com.horstmann.BankAccount; 2 3 /** 4 This program tests the BankAccount class. 5 */ 6 public class BankAccountTester 7 { 8 /** 9 Tests the methods of the BankAccount class. 10 @param args not used 11 */ 12 public static void main(String[] args) 13 { 14 BankAccount harrysAccount = new BankAccount(1000); 15 harrysAccount.deposit(500); // Balance is now $1500 16 harrysAccount.withdraw(2000); // Balance is now $1490 17 harrysAccount.addInterest(1); // Balance is now $1490 + 14.90 18 System.out.printf("%.2fn", harrysAccount.getBalance()); 19 System.out.println("Expected: 1504.90"); 20 } 21 } __MACOSX/ch12/section_4/._BankAccountTester.java.html ch12/section_4/com/.DS_Store __MACOSX/ch12/section_4/com/._.DS_Store ch12/section_4/com/horstmann/.DS_Store __MACOSX/ch12/section_4/com/horstmann/._.DS_Store ch12/section_4/com/horstmann/BankAccount.javach12/section_ 4/com/horstmann/BankAccount.javapackage com.horstmann; /** A bank account has a balance that can be changed by deposits and withdrawals. */
  • 25. publicclassBankAccount { privatedouble balance; /** Constructs a bank account with a zero balance. */ publicBankAccount() { balance =0; } /** Constructs a bank account with a given balance. @param initialBalance the initial balance */ publicBankAccount(double initialBalance) { balance = initialBalance; } /** Deposits money into this account. @param amount the amount to deposit */ publicvoid deposit(double amount) { balance = balance + amount; } /** Makes a withdrawal from this account, or charges a penalty if sufficient funds are not available. @param amount the amount of the withdrawal */
  • 26. publicvoid withdraw(double amount) { finaldouble PENALTY =10; if(amount > balance) { balance = balance - PENALTY; } else { balance = balance - amount; } } /** Adds interest to this account. @param rate the interest rate in percent */ publicvoid addInterest(double rate) { double amount = balance * rate /100; balance = balance + amount; } /** Gets the current balance of this account. @return the current balance */ publicdouble getBalance() { return balance; } } __MACOSX/ch12/section_4/com/horstmann/._BankAccount.jav a
  • 27. __MACOSX/ch12/section_4/com/._horstmann __MACOSX/ch12/section_4/._com __MACOSX/ch12/._section_4 ch12/worked_example_1/.DS_Store __MACOSX/ch12/worked_example_1/._.DS_Store ch12/worked_example_1/ATM.javach12/worked_example_1/AT M.java/** An ATM that accesses a bank. */ publicclass ATM { publicstaticfinalint CHECKING =1; publicstaticfinalint SAVINGS =2; privateint state; privateint customerNumber; privateCustomer currentCustomer; privateBankAccount currentAccount; privateBank theBank; publicstaticfinalint START =1; publicstaticfinalint PIN =2; publicstaticfinalint ACCOUNT =3; publicstaticfinalint TRANSACT =4; /** Constructs an ATM for a given bank. @param aBank the bank to which this ATM connects */ public ATM(Bank aBank)
  • 28. { theBank = aBank; reset(); } /** Resets the ATM to the initial state. */ publicvoid reset() { customerNumber =-1; currentAccount =null; state = START; } /** Sets the current customer number and sets state to PIN. (Precondition: state is START) @param number the customer number. */ publicvoid setCustomerNumber(int number) { customerNumber = number; state = PIN; } /** Finds customer in bank. If found sets state to ACCOUNT, else to START. (Precondition: state is PIN) @param pin the PIN of the current customer */ publicvoid selectCustomer(int pin) { currentCustomer
  • 29. = theBank.findCustomer(customerNumber, pin); if(currentCustomer ==null) { state = START; } else { state = ACCOUNT; } } /** Sets current account to checking or savings. Sets state to TRANSACT. (Precondition: state is ACCOUNT or TRANSACT) @param account one of CHECKING or SAVINGS */ publicvoid selectAccount(int account) { if(account == CHECKING) { currentAccount = currentCustomer.getCheckingAccount() ; } else { currentAccount = currentCustomer.getSavingsAccount(); } state = TRANSACT; } /** Withdraws amount from current account. (Precondition: state is TRANSACT) @param value the amount to withdraw */
  • 30. publicvoid withdraw(double value) { currentAccount.withdraw(value); } /** Deposits amount to current account. (Precondition: state is TRANSACT) @param value the amount to deposit */ publicvoid deposit(double value) { currentAccount.deposit(value); } /** Gets the balance of the current account. (Precondition: state is TRANSACT) @return the balance */ publicdouble getBalance() { return currentAccount.getBalance(); } /** Moves back to the previous state. */ publicvoid back() { if(state == TRANSACT) { state = ACCOUNT; } elseif(state == ACCOUNT) {
  • 31. state = PIN; } elseif(state == PIN) { state = START; } } /** Gets the current state of this ATM. @return the current state */ publicint getState() { return state; } } __MACOSX/ch12/worked_example_1/._ATM.java ch12/worked_example_1/ATM.java.html 1 /** 2 An ATM that accesses a bank. 3 */ 4 public class ATM 5 { 6 public static final int CHECKING = 1; 7 public static final int SAVINGS = 2; 8 9 private int state; 10 private int customerNumber; 11 private Customer currentCustomer; 12 private BankAccount currentAccount; 13 private Bank theBank; 14 15 public static final int START = 1; 16 public static final int PIN = 2; 17 public static final int ACCOUNT = 3; 18 public static final int TRANSACT = 4; 19 20 /** 21 Constructs an ATM for a given bank. 22 @param aBank the bank to which this ATM connects 23 */ 24 public ATM(Bank aBank) 25 { 26 theBank = aBank; 27 reset(); 28 } 29 30 /** 31 Resets the ATM to the initial state. 32 */ 33 public void reset() 34 { 35 customerNumber = -1; 36 currentAccount = null;
  • 32. 37 state = START; 38 } 39 40 /** 41 Sets the current customer number 42 and sets state to PIN. 43 (Precondition: state is START) 44 @param number the customer number. 45 */ 46 public void setCustomerNumber(int number) 47 { 48 customerNumber = number; 49 state = PIN; 50 } 51 52 /** 53 Finds customer in bank. 54 If found sets state to ACCOUNT, else to START. 55 (Precondition: state is PIN) 56 @param pin the PIN of the current customer 57 */ 58 public void selectCustomer(int pin) 59 { 60 currentCustomer 61 = theBank.findCustomer(customerNumber, pin); 62 if (currentCustomer == null) 63 { 64 state = START; 65 } 66 else 67 { 68 state = ACCOUNT; 69 } 70 } 71 72 /** 73 Sets current account to checking or savings. Sets 74 state to TRANSACT. 75 (Precondition: state is ACCOUNT or TRANSACT) 76 @param account one of CHECKING or SAVINGS 77 */ 78 public void selectAccount(int account) 79 { 80 if (account == CHECKING) 81 { 82 currentAccount = currentCustomer.getCheckingAccount(); 83 } 84 else 85 { 86 currentAccount = currentCustomer.getSavingsAccount(); 87 } 88 state = TRANSACT; 89 } 90 91 /** 92 Withdraws amount from current account. 93 (Precondition: state is TRANSACT) 94 @param value the amount to withdraw 95 */ 96 public void withdraw(double value) 97 { 98 currentAccount.withdraw(value); 99 }100 101 /** 102 Deposits amount to current account. 103 (Precondition: state is TRANSACT)104 @param value the amount to deposit105 */106 public void deposit(double value)107 { 108 currentAccount.deposit(value);109 }110 111 /** 112 Gets the balance of the current account. 113 (Precondition: state is TRANSACT)114 @return the balance115 */116 public double getBalance()117 { 118 return currentAccount.getBalance();119 }120 121 /**122
  • 33. Moves back to the previous state.123 */124 public void back()125 {126 if (state == TRANSACT)127 {128 state = ACCOUNT;129 }130 else if (state == ACCOUNT)131 {132 state = PIN;133 }134 else if (state == PIN)135 {136 state = START;137 }138 }139 140 /**141 Gets the current state of this ATM.142 @return the current state143 */144 public int getState()145 {146 return state;147 }148 } __MACOSX/ch12/worked_example_1/._ATM.java.html ch12/worked_example_1/ATMFrame.javach12/worked_example _1/ATMFrame.javaimport java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; /** A frame displaying the components of an ATM. */ publicclassATMFrameextendsJFrame { privatestaticfinalint FRAME_WIDTH =300; privatestaticfinalint FRAME_HEIGHT =300; privateJButton aButton; privateJButton bButton; privateJButton cButton; privateKeyPad pad; privateJTextArea display;
  • 34. private ATM theATM; /** Constructs the user interface of the ATM frame. */ publicATMFrame(ATM anATM) { theATM = anATM; // Construct components pad =newKeyPad(); display =newJTextArea(4,20); aButton =newJButton(" A "); aButton.addActionListener(newAButtonListener()); bButton =newJButton(" B "); bButton.addActionListener(newBButtonListener()); cButton =newJButton(" C "); cButton.addActionListener(newCButtonListener()); // Add components JPanel buttonPanel =newJPanel(); buttonPanel.add(aButton); buttonPanel.add(bButton); buttonPanel.add(cButton); setLayout(newFlowLayout()); add(pad); add(display); add(buttonPanel); showState();
  • 35. setSize(FRAME_WIDTH, FRAME_HEIGHT); } /** Updates display message. */ publicvoid showState() { int state = theATM.getState(); pad.clear(); if(state == ATM.START) { display.setText("Enter customer numbernA = OK"); } elseif(state == ATM.PIN) { display.setText("Enter PINnA = OK"); } elseif(state == ATM.ACCOUNT) { display.setText("Select Accountn" +"A = CheckingnB = SavingsnC = Exit"); } elseif(state == ATM.TRANSACT) { display.setText("Balance = " + theATM.getBalance() +"nEnter amount and select transactionn" +"A = WithdrawnB = DepositnC = Cancel"); } } classAButtonListenerimplementsActionListener { publicvoid actionPerformed(ActionEvent event) {
  • 36. int state = theATM.getState(); if(state == ATM.START) { theATM.setCustomerNumber((int) pad.getValue()); } elseif(state == ATM.PIN) { theATM.selectCustomer((int) pad.getValue()); } elseif(state == ATM.ACCOUNT) { theATM.selectAccount(ATM.CHECKING); } elseif(state == ATM.TRANSACT) { theATM.withdraw(pad.getValue()); theATM.back(); } showState(); } } classBButtonListenerimplementsActionListener { publicvoid actionPerformed(ActionEvent event) { int state = theATM.getState(); if(state == ATM.ACCOUNT) { theATM.selectAccount(ATM.SAVINGS); } elseif(state == ATM.TRANSACT) { theATM.deposit(pad.getValue()); theATM.back(); }
  • 37. showState(); } } classCButtonListenerimplementsActionListener { publicvoid actionPerformed(ActionEvent event) { int state = theATM.getState(); if(state == ATM.ACCOUNT) { theATM.reset(); } elseif(state == ATM.TRANSACT) { theATM.back(); } showState(); } } } __MACOSX/ch12/worked_example_1/._ATMFrame.java ch12/worked_example_1/ATMFrame.java.html 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 14 { 15 private static final int FRAME_WIDTH = 300; 16 private static final int FRAME_HEIGHT = 300; 17 18 private JButton aButton; 19 private JButton bButton; 20 private JButton cButton; 21
  • 38. 22 private KeyPad pad; 23 private JTextArea display; 24 25 private ATM theATM; 26 27 /** 28 Constructs the user interface of the ATM frame. 29 */ 30 public ATMFrame(ATM anATM) 31 { 32 theATM = anATM; 33 34 // Construct components 35 pad = new KeyPad(); 36 37 display = new JTextArea(4, 20); 38 39 aButton = new JButton(" A "); 40 aButton.addActionListener(new AButtonListener()); 41 42 bButton = new JButton(" B "); 43 bButton.addActionListener(new BButtonListener()); 44 45 cButton = new JButton(" C "); 46 cButton.addActionListener(new CButtonListener()); 47 48 // Add components 49 50 JPanel buttonPanel = new JPanel(); 51 buttonPanel.add(aButton); 52 buttonPanel.add(bButton); 53 buttonPanel.add(cButton); 54 55 setLayout(new FlowLayout()); 56 add(pad); 57 add(display); 58 add(buttonPanel); 59 showState(); 60 61 setSize(FRAME_WIDTH, FRAME_HEIGHT); 62 } 63 64 /** 65 Updates display message. 66 */ 67 public void showState() 68 { 69 int state = theATM.getState(); 70 pad.clear(); 71 if (state == ATM.START) 72 { 73 display.setText("Enter customer numbernA = OK"); 74 } 75 else if (state == ATM.PIN) 76 { 77 display.setText("Enter PINnA = OK"); 78 } 79 else if (state == ATM.ACCOUNT) 80 { 81 display.setText("Select Accountn" 82 + "A = CheckingnB = SavingsnC = Exit"); 83 } 84 else if (state == ATM.TRANSACT) 85 { 86 display.setText("Balance = " 87 + theATM.getBalance() 88 + "nEnter amount and select transactionn" 89 + "A = WithdrawnB = DepositnC = Cancel"); 90 } 91 } 92 93 class AButtonListener implements ActionListener 94 { 95 public void actionPerformed(ActionEvent event) 96 { 97 int state = theATM.getState(); 98 if (state == ATM.START) 99 {100
  • 39. theATM.setCustomerNumber((int) pad.getValue());101 }102 else if (state == ATM.PIN)103 {104 theATM.selectCustomer((int) pad.getValue());105 }106 else if (state == ATM.ACCOUNT)107 {108 theATM.selectAccount(ATM.CHECKING);109 }110 else if (state == ATM.TRANSACT)111 {112 theATM.withdraw(pad.getValue());113 theATM.back();114 }115 showState();116 }117 }118 119 class BButtonListener implements ActionListener120 { 121 public void actionPerformed(ActionEvent event)122 { 123 int state = theATM.getState();124 if (state == ATM.ACCOUNT)125 {126 theATM.selectAccount(ATM.SAVINGS);127 }128 else if (state == ATM.TRANSACT)129 {130 theATM.deposit(pad.getValue());131 theATM.back();132 }133 showState();134 }135 }136 137 class CButtonListener implements ActionListener138 { 139 public void actionPerformed(ActionEvent event)140 { 141 int state = theATM.getState();142 if (state == ATM.ACCOUNT)143 {144 theATM.reset();145 }146 else if (state == ATM.TRANSACT)147 {148 theATM.back();149 }150 showState();151 }152 }153 } __MACOSX/ch12/worked_example_1/._ATMFrame.java.html ch12/worked_example_1/ATMSimulator.javach12/worked_exam ple_1/ATMSimulator.javaimport java.io.IOException; import java.util.Scanner; /** A text-based simulation of an automatic teller machine. */ publicclassATMSimulator
  • 40. { publicstaticvoid main(String[] args) { ATM theATM; try { Bank theBank =newBank(); theBank.readCustomers("customers.txt"); theATM =new ATM(theBank); } catch(IOException e) { System.out.println("Error opening accounts file."); return; } Scanner in =newScanner(System.in); while(true) { int state = theATM.getState(); if(state == ATM.START) { System.out.print("Enter customer number: "); int number = in.nextInt(); theATM.setCustomerNumber(number); } elseif(state == ATM.PIN) { System.out.print("Enter PIN: "); int pin = in.nextInt(); theATM.selectCustomer(pin); } elseif(state == ATM.ACCOUNT) { System.out.print("A=Checking, B=Savings, C=Quit: ");
  • 41. String command = in.next(); if(command.equalsIgnoreCase("A")) { theATM.selectAccount(ATM.CHECKING); } elseif(command.equalsIgnoreCase("B")) { theATM.selectAccount(ATM.SAVINGS); } elseif(command.equalsIgnoreCase("C")) { theATM.reset(); } else { System.out.println("Illegal input!"); } } elseif(state == ATM.TRANSACT) { System.out.println("Balance="+ theATM.getBalance()); System.out.print("A=Deposit, B=Withdrawal, C=Cancel: "); String command = in.next(); if(command.equalsIgnoreCase("A")) { System.out.print("Amount: "); double amount = in.nextDouble(); theATM.deposit(amount); theATM.back(); } elseif(command.equalsIgnoreCase("B")) { System.out.print("Amount: "); double amount = in.nextDouble(); theATM.withdraw(amount); theATM.back();
  • 42. } elseif(command.equalsIgnoreCase("C")) { theATM.back(); } else { System.out.println("Illegal input!"); } } } } } __MACOSX/ch12/worked_example_1/._ATMSimulator.java ch12/worked_example_1/ATMSimulator.java.html 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 { 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
  • 43. } 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 { 47 theATM.selectAccount(ATM.CHECKING); 48 } 49 else if (command.equalsIgnoreCase("B")) 50 { 51 theATM.selectAccount(ATM.SAVINGS); 52 } 53 else if (command.equalsIgnoreCase("C")) 54 { 55 theATM.reset(); 56 } 57 else 58 { 59 System.out.println("Illegal input!"); 60 } 61 } 62 else if (state == ATM.TRANSACT) 63 { 64 System.out.println("Balance=" + theATM.getBalance()); 65 System.out.print("A=Deposit, B=Withdrawal, C=Cancel: "); 66 String command = in.next(); 67 if (command.equalsIgnoreCase("A")) 68 { 69 System.out.print("Amount: "); 70 double amount = in.nextDouble(); 71 theATM.deposit(amount); 72 theATM.back(); 73 } 74 else if (command.equalsIgnoreCase("B")) 75 { 76 System.out.print("Amount: "); 77 double amount = in.nextDouble(); 78 theATM.withdraw(amount); 79 theATM.back(); 80 } 81 else if (command.equalsIgnoreCase("C")) 82 { 83 theATM.back(); 84 } 85 else 86 { 87 System.out.println("Illegal input!"); 88 } 89 } 90 } 91 } 92 } 93 __MACOSX/ch12/worked_example_1/._ATMSimulator.java.ht ml ch12/worked_example_1/ATMViewer.javach12/worked_exampl e_1/ATMViewer.javaimport java.io.IOException; import javax.swing.JFrame; import javax.swing.JOptionPane;
  • 44. /** A graphical simulation of an automatic teller machine. */ publicclassATMViewer { publicstaticvoid main(String[] args) { ATM theATM; try { Bank theBank =newBank(); theBank.readCustomers("customers.txt"); theATM =new ATM(theBank); } catch(IOException e) { JOptionPane.showMessageDialog(null,"Error opening accounts file."); return; } JFrame frame =newATMFrame(theATM); frame.setTitle("First National Bank of Java"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ; frame.setVisible(true); } } __MACOSX/ch12/worked_example_1/._ATMViewer.java ch12/worked_example_1/ATMViewer.java.html 1 import java.io.IOException; 2 import javax.swing.JFrame; 3 import
  • 45. javax.swing.JOptionPane; 4 5 /** 6 A graphical simulation of an automatic teller machine. 7 */ 8 public class ATMViewer 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, "Error opening accounts file."); 23 return; 24 } 25 26 JFrame frame = new ATMFrame(theATM); 27 frame.setTitle("First National Bank of Java"); 28 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 29 frame.setVisible(true); 30 } 31 } 32 __MACOSX/ch12/worked_example_1/._ATMViewer.java.html ch12/worked_example_1/Bank.javach12/worked_example_1/Ba nk.javaimport java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; /** A bank contains customers. */ publicclassBank { privateArrayList<Customer> customers; /** Constructs a bank with no customers. */ publicBank() { customers =newArrayList<Customer>(); }
  • 46. /** Reads the customer numbers and pins. @param filename the name of the customer file */ publicvoid readCustomers(String filename) throwsIOException { Scanner in =newScanner(newFile(filename)); while(in.hasNext()) { int number = in.nextInt(); int pin = in.nextInt(); Customer c =newCustomer(number, pin); addCustomer(c); } in.close(); } /** Adds a customer to the bank. @param c the customer to add */ publicvoid addCustomer(Customer c) { customers.add(c); } /** Finds a customer in the bank. @param aNumber a customer number @param aPin a personal identification number @return the matching customer, or null if no customer matches */ publicCustomer findCustomer(int aNumber,int aPin)
  • 47. { for(Customer c : customers) { if(c.match(aNumber, aPin)) { return c; } } returnnull; } } __MACOSX/ch12/worked_example_1/._Bank.java ch12/worked_example_1/Bank.java.html 1 import java.io.File; 2 import java.io.IOException; 3 import java.util.ArrayList; 4 import java.util.Scanner; 5 6 /** 7 A bank contains customers. 8 */ 9 public class Bank 10 { 11 private ArrayList<Customer> customers; 12 13 /** 14 Constructs a bank with no customers. 15 */ 16 public Bank() 17 { 18 customers = new ArrayList<Customer>(); 19 } 20 21 /** 22 Reads the customer numbers and pins. 23 @param filename the name of the customer file 24 */ 25 public void readCustomers(String filename) 26 throws IOException 27 { 28 Scanner in = new Scanner(new File(filename)); 29 while (in.hasNext()) 30 { 31 int number = in.nextInt(); 32 int pin = in.nextInt(); 33 Customer c = new Customer(number, pin); 34 addCustomer(c); 35 } 36 in.close(); 37 } 38 39 /** 40 Adds a customer to the bank. 41 @param c the customer to add 42 */ 43 public void addCustomer(Customer c) 44 { 45 customers.add(c); 46 } 47 48 /** 49 Finds a
  • 48. customer in the bank. 50 @param aNumber a customer number 51 @param aPin a personal identification number 52 @return the matching customer, or null if no customer 53 matches 54 */ 55 public Customer findCustomer(int aNumber, int aPin) 56 { 57 for (Customer c : customers) 58 { 59 if (c.match(aNumber, aPin)) 60 { 61 return c; 62 } 63 } 64 return null; 65 } 66 } 67 68 __MACOSX/ch12/worked_example_1/._Bank.java.html ch12/worked_example_1/BankAccount.javach12/worked_examp le_1/BankAccount.java/** A bank account has a balance that can be changed by deposits and withdrawals. */ publicclassBankAccount { privatedouble balance; /** Constructs a bank account with a zero balance. */ publicBankAccount() { balance =0; } /** Constructs a bank account with a given balance. @param initialBalance the initial balance */ publicBankAccount(double initialBalance) { balance = initialBalance; }
  • 49. /** Deposits money into the account. @param amount the amount of money to withdraw */ publicvoid deposit(double amount) { balance = balance + amount; } /** Withdraws money from the account. @param amount the amount of money to deposit */ publicvoid withdraw(double amount) { balance = balance - amount; } /** Gets the account balance. @return the account balance */ publicdouble getBalance() { return balance; } } __MACOSX/ch12/worked_example_1/._BankAccount.java ch12/worked_example_1/BankAccount.java.html 1 /** 2 A bank account has a balance that can be changed by 3 deposits and withdrawals. 4 */ 5 public class BankAccount 6
  • 50. { 7 private double balance; 8 9 /** 10 Constructs a bank account with a zero balance. 11 */ 12 public BankAccount() 13 { 14 balance = 0; 15 } 16 17 /** 18 Constructs a bank account with a given balance. 19 @param initialBalance the initial balance 20 */ 21 public BankAccount(double initialBalance) 22 { 23 balance = initialBalance; 24 } 25 26 /** 27 Deposits money into the account. 28 @param amount the amount of money to withdraw 29 */ 30 public void deposit(double amount) 31 { 32 balance = balance + amount; 33 } 34 35 /** 36 Withdraws money from the account. 37 @param amount the amount of money to deposit 38 */ 39 public void withdraw(double amount) 40 { 41 balance = balance - amount; 42 } 43 44 /** 45 Gets the account balance. 46 @return the account balance 47 */ 48 public double getBalance() 49 { 50 return balance; 51 } 52 } 53 __MACOSX/ch12/worked_example_1/._BankAccount.java.html ch12/worked_example_1/Customer.javach12/worked_example_1 /Customer.java/** A bank customer with a checking and a savings account. */ publicclassCustomer { privateint customerNumber; privateint pin; privateBankAccount checkingAccount; privateBankAccount savingsAccount; /** Constructs a customer with a given number and PIN. @param aNumber the customer number @param aPin the personal identification number */
  • 51. publicCustomer(int aNumber,int aPin) { customerNumber = aNumber; pin = aPin; checkingAccount =newBankAccount(); savingsAccount =newBankAccount(); } /** Tests if this customer matches a customer number and PIN. @param aNumber a customer number @param aPin a personal identification number @return true if the customer number and PIN match */ publicboolean match(int aNumber,int aPin) { return customerNumber == aNumber && pin == aPin; } /** Gets the checking account of this customer. @return the checking account */ publicBankAccount getCheckingAccount() { return checkingAccount; } /** Gets the savings account of this customer. @return the checking account */ publicBankAccount getSavingsAccount() { return savingsAccount;
  • 52. } } __MACOSX/ch12/worked_example_1/._Customer.java ch12/worked_example_1/Customer.java.html 1 /** 2 A bank customer with a checking and a savings account. 3 */ 4 public class Customer 5 { 6 private int customerNumber; 7 private int pin; 8 private BankAccount checkingAccount; 9 private BankAccount savingsAccount; 10 11 /** 12 Constructs a customer with a given number and PIN. 13 @param aNumber the customer number 14 @param aPin the personal identification number 15 */ 16 public Customer(int aNumber, int aPin) 17 { 18 customerNumber = aNumber; 19 pin = aPin; 20 checkingAccount = new BankAccount(); 21 savingsAccount = new BankAccount(); 22 } 23 24 /** 25 Tests if this customer matches a customer number 26 and PIN. 27 @param aNumber a customer number 28 @param aPin a personal identification number 29 @return true if the customer number and PIN match 30 */ 31 public boolean match(int aNumber, int aPin) 32 { 33 return customerNumber == aNumber && pin == aPin; 34 } 35 36 /** 37 Gets the checking account of this customer. 38 @return the checking account 39 */ 40 public BankAccount getCheckingAccount() 41 { 42 return checkingAccount; 43 } 44 45 /** 46 Gets the savings account of this customer. 47 @return the checking account 48 */ 49 public BankAccount getSavingsAccount() 50 { 51 return savingsAccount; 52 } 53 } __MACOSX/ch12/worked_example_1/._Customer.java.html ch12/worked_example_1/customers.txt 1 1234
  • 53. 2 2468 3 3692 4 4826 5 5050 6 6284 7 7418 8 8642 9 9876 __MACOSX/ch12/worked_example_1/._customers.txt ch12/worked_example_1/KeyPad.javach12/worked_example_1/ KeyPad.javaimport java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JTextField; /** A component that lets the user enter a number, using a button pad labeled with digits. */ publicclassKeyPadextendsJPanel {
  • 54. privateJPanel buttonPanel; privateJButton clearButton; privateJTextField display; /** Constructs the keypad panel. */ publicKeyPad() { setLayout(newBorderLayout()); // Add display field display =newJTextField(); add(display,"North"); // Make button panel buttonPanel =newJPanel(); buttonPanel.setLayout(newGridLayout(4,3)); // Add digit buttons addButton("7"); addButton("8"); addButton("9"); addButton("4"); addButton("5"); addButton("6"); addButton("1"); addButton("2"); addButton("3"); addButton("0"); addButton("."); // Add clear entry button
  • 55. clearButton =newJButton("CE"); buttonPanel.add(clearButton); classClearButtonListenerimplementsActionListener { publicvoid actionPerformed(ActionEvent event) { display.setText(""); } } ActionListener listener =newClearButtonListener(); clearButton.addActionListener(new ClearButtonListener()); add(buttonPanel,"Center"); } /** Adds a button to the button panel @param label the button label */ privatevoid addButton(finalString label) { classDigitButtonListenerimplementsActionListener { publicvoid actionPerformed(ActionEvent event) { // Don't add two decimal points if(label.equals(".") && display.getText().indexOf(".")!=-1) { return; }
  • 56. // Append label text to button display.setText(display.getText()+ label); } } JButton button =newJButton(label); buttonPanel.add(button); ActionListener listener =newDigitButtonListener(); button.addActionListener(listener); } /** Gets the value that the user entered. @return the value in the text field of the keypad */ publicdouble getValue() { returnDouble.parseDouble(display.getText()); } /** Clears the display. */ publicvoid clear() { display.setText(""); } } __MACOSX/ch12/worked_example_1/._KeyPad.java ch12/worked_example_1/KeyPad.java.html 1 import java.awt.BorderLayout; 2 import java.awt.GridLayout; 3
  • 57. 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 button pad labeled with digits. 12 */ 13 public class KeyPad extends JPanel 14 { 15 private JPanel buttonPanel; 16 private JButton clearButton; 17 private JTextField display; 18 19 /** 20 Constructs the keypad panel. 21 */ 22 public KeyPad() 23 { 24 setLayout(new BorderLayout()); 25 26 // Add display field 27 28 display = new JTextField(); 29 add(display, "North"); 30 31 // Make button panel 32 33 buttonPanel = new JPanel(); 34 buttonPanel.setLayout(new GridLayout(4, 3)); 35 36 // Add digit buttons 37 38 addButton("7"); 39 addButton("8"); 40 addButton("9"); 41 addButton("4"); 42 addButton("5"); 43 addButton("6"); 44 addButton("1"); 45 addButton("2"); 46 addButton("3"); 47 addButton("0"); 48 addButton("."); 49 50 // Add clear entry button 51 52 clearButton = new JButton("CE"); 53 buttonPanel.add(clearButton); 54 55 class ClearButtonListener implements ActionListener 56 { 57 public void actionPerformed(ActionEvent event) 58 { 59 display.setText(""); 60 } 61 } 62 63 ActionListener listener = new ClearButtonListener(); 64 65 clearButton.addActionListener(new 66 ClearButtonListener()); 67 68 add(buttonPanel, "Center"); 69 } 70 71 /** 72 Adds a button to the button panel 73 @param label the button label 74 */ 75 private void addButton(final String label) 76 { 77 class DigitButtonListener implements ActionListener 78 { 79 public void actionPerformed(ActionEvent event) 80 { 81 // Don't add two decimal points 82 if (label.equals(".") 83 && display.getText().indexOf(".") != -1) 84 { 85
  • 58. return; 86 } 87 88 // Append label text to button 89 display.setText(display.getText() + label); 90 } 91 } 92 93 JButton button = new JButton(label); 94 buttonPanel.add(button); 95 ActionListener listener = new DigitButtonListener(); 96 button.addActionListener(listener); 97 } 98 99 /** 100 Gets the value that the user entered. 101 @return the value in the text field of the keypad102 */103 public double getValue()104 { 105 return Double.parseDouble(display.getText());106 }107 108 /** 109 Clears the display. 110 */111 public void clear()112 { 113 display.setText("");114 }115 }116 __MACOSX/ch12/worked_example_1/._KeyPad.java.html __MACOSX/ch12/._worked_example_1 __MACOSX/._ch12 Chapter12 Worked out example.pdf simulating an automatic teller Machine we1 Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. step 1 Gather requirements. The purpose of this project is to simulate an automatic teller machine (ATM). The ATM is used by the customers of a bank. Each customer has two accounts: a checking account and a savings account. Each customer also has a customer number and a personal identification number (PIN); both are required to gain access to the accounts.
  • 59. (In a real ATM, the customer number would be recorded on the magnetic strip of the ATM card. In this simulation, the customer will need to type it in.) With the ATM, customers can select an account (checking or savings). The balance of the selected account is displayed. Then the customer can deposit and withdraw money. This process is repeated until the customer chooses to exit. The details of the user interaction depend on the user interface that we choose for the simu- lation. We will develop two separate interfaces: a graphical interface that closely mimics an actual ATM (see Figure 12), and a text-based interface that allows you to test the ATM and bank classes without being dis tracted by GUI programming. In the GUI interface, the ATM has a keypad to enter numbers, a display to show messages, and a set of buttons, labeled A, B, and C, whose function depends on the state of the machine. Specifically, the user interaction is as follows. When the ATM starts up, it expects a user to enter a cus tomer number. The display shows the following message: Enter-customer-number A-=-OK The user enters the customer number on the keypad and presses the A button. The display message changes to Enter-PIN
  • 60. A-=-OK Next, the user enters the PIN and presses the A button again. If the customer number and ID match those of one of the customers in the bank, then the customer can proceed. If not, the user is again prompted to enter the customer number. w O r k e d e x a M p L e 1 2 . 1 simulating an automatic Teller machine In this Worked Example, we apply the object-oriented design methodology to the simulation of an automatic teller machine that works with both a console-based and graphical user interface. Figure 12 graphical User interface for the automatic teller Machine we2 Chapter 12 Object-Oriented design Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. If the customer has been authorized to use the system, then the display message changes to Select-Account A-=-Checking B-=-Savings C-=-Exit If the user presses the C button, the ATM reverts to its original
  • 61. state and asks the next user to enter a cus tomer number. If the user presses the A or B buttons, the ATM remembers the selected account, and the display mes sage changes to Balance-=-balance of selected account- Enter-amount-and-select-transaction A-=-Withdraw B-=-Deposit C-=-Cancel If the user presses the A or B buttons, the value entered in the keypad is withdrawn from or deposited into the selected account. (This is just a simulation, so no money is dispensed and no deposit is accepted.) Afterward, the ATM reverts to the preceding state, allowing the user to select another account or to exit. If the user presses the C button, the ATM reverts to the preceding state without executing any transac tion. In the text-based interaction, we read input from System.in instead of the buttons. Here is a typical dia log: Enter-customer-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
  • 62. In our solution, only the user interface classes are affected by the choice of user interface. The remainder of the classes can be used for both solutions—they are decoupled from the user interface. Because this is a simulation, the ATM does not actually communicate with a bank. It simply loads a set of customer numbers and PINs from a file. All accounts are initialized with a zero balance. step 2 Use CRC cards to find classes, responsibilities, and collaborators. We will again follow the recipe of Section 12.2 and show how to discover classes, responsibili- ties, and rela tionships and how to obtain a detailed design for the ATM program. Recall that the first rule for finding classes is “Look for nouns in the problem description”. Here is a list of the nouns: ATM User Keypad Display Display-message Button State Bank-account Checking-account Savings-account Customer
  • 63. Customer-number PIN Bank simulating an automatic teller Machine we3 Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. Of course, not all of these nouns will become names of classes, and we may yet discover the need for classes that aren’t in this list, but it is a good start. Users and customers represent the same concept in this program. Let’s use a class Customer. A customer has two bank accounts, and we will require that a Customer object should be able to locate these accounts. (Another possible design would make the Bank class responsible for locating the accounts of a given cus tomer—see Exercise P12.10.) A customer also has a customer number and a PIN. We can, of course, require that a cus- tomer object give us the customer number and the PIN. But perhaps that isn’t so secure. Instead, simply require that a customer object, when given a customer number and a PIN, will tell us whether it matches its own infor mation or not. get accounts match number and PIN Customer
  • 64. A bank contains a collection of customers. When a user walks up to the ATM and enters a customer num ber and PIN, it is the job of the bank to find the matching customer. How can the bank do this? It needs to check for each customer whether its customer number and PIN match. Thus, it needs to call the match number and PIN method of the Customer class that we just discovered. Because the find customer method calls a Customer method, it collaborates with the Customer class. We record that fact in the right-hand col umn of the CRC card. When the simulation starts up, the bank must also be able to read customer information from a file. find customer Customer read customers Bank The BankAccount class is our familiar class with methods to get the balance and to deposit and withdraw money. In this program, there is nothing that distinguishes checking accounts from savings accounts. The ATM does not add interest or deduct fees. Therefore, we decide not to imple- ment separate subclasses for check ing and savings accounts. Finally, we are left with the ATM class itself. An important notion of the ATM is the state. The current machine state determines the text of the prompts
  • 65. and the function of the buttons. For example, when you first log in, you use the A and B buttons to select an account. Next, you use the same buttons to choose between deposit and withdrawal. The ATM must remem- ber the current state so that it can correctly interpret the buttons. we4 Chapter 12 Object-Oriented design Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. Figure 13 state diagram for the atM Class START PIN Customer not found Customer found Account selected Customer number entered Exit selected Transaction completed or canceled
  • 66. ACCOUNT TRANSACT There are four states: 1. START: Enter customer ID 2. PIN: Enter PIN 3. ACCOUNT: Select account 4. TRANSACT: Select transaction To understand how to move from one state to the next, it is useful to draw a state diagram (Figure 13). The UML notation has standardized shapes for state diagrams. Draw states as rectangles with rounded corners. Draw state changes as arrows, with labels that indicate the reason for the change. The user must type a valid customer number and PIN. Then the ATM can ask the bank to find the cus tomer. This calls for a select customer method. It collaborates with the bank, ask- ing the bank for the cus tomer that matches the customer number and PIN. Next, there must be a select account method that asks the current customer for the checking or savings account. Finally, the ATM must carry out the selected transaction on the current account. manage state Customer Bank BankAccount select customer
  • 67. select account execute transaction ATM simulating an automatic teller Machine we5 Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. Of course, discovering these classes and methods was not as neat and orderly as it appears from this dis cussion. When I designed these classes for this book, it took me several trials and many torn cards to come up with a satisfactory design. It is also important to remember that there is seldom one best design. This design has several advantages. The classes describe clear concepts. The methods are sufficient to implement all necessary tasks. (I mentally walked through every ATM usage sce- nario to verify that.) There are not too many collaboration dependencies between the classes. Thus, I was satisfied with this design and proceeded to the next step. step 3 Use UML diagrams to record class relationships. To draw the dependencies, use the “collaborator” columns from the CRC cards. Looking at those col umns, you find that the dependencies are as follows: • ATM knows about Bank, Customer, and BankAccount. • Bank knows about Customer.
  • 68. • Customer knows about BankAccount. ATM BankAccount Customer Bank It is easy to see some of the aggregation relationships. A bank has customers, and each cus- tomer has two bank accounts. Does the ATM class aggregate Bank? To answer this question, ask yourself whether an ATM object needs to store a reference to a bank object. Does it need to locate the same bank object across multiple method calls? Indeed it does. Therefore, aggregation is the appropriate rela- tionship. Does an ATM aggregate customers? Clearly, the ATM is not responsible for storing all of the bank’s customers. That’s the bank’s job. But in our design, the ATM remembers the current customer. If a cus tomer has logged in, subsequent commands refer to the same customer. The ATM needs to either store a reference to the customer, or ask the bank to look up the object whenever it needs the current customer. It is a design decision: either store the object, or look it up when needed. We will decide to store the cur rent customer object. That is, we will use aggregation. Note that the choice of aggregation is not an auto matic consequence of the prob-
  • 69. lem description—it is a design decision. Similarly, we will decide to store the current bank account (checking or savings) that the user selects. Therefore, we have an aggregation relationship between ATM and BankAccount. Figure 14 shows the relationships between these classes, using the graphical user interface. (The console user interface uses a single class ATMSimulator instead of the ATMFrame, ATMViewer, and Keypad classes.) we6 Chapter 12 Object-Oriented design Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. Figure 14 relationships between the atM Classes ATMFrame ATMViewer Keypad ATM BankAccount Customer Bank 1
  • 70. 1 1 2 * The class diagram is a good tool to visualize dependencies. Look at the GUI classes. They are com pletely independent from the rest of the ATM system. You can replace the GUI with a console interface, and you can take out the Keypad class and use it in another application. Also, the Bank, BankAccount, and Cus-tomer classes, although dependent on each other, don’t know any- thing about the ATM class. That makes sense—you can have banks without ATMs. As you can see, when you analyze relationships, you look for both the absence and presence of relation- ships. step 4 Use javadoc to document method behavior. Now you are ready for the final step of the design phase: documenting the classes and methods that you discovered. Here is a part of the documentation for the ATM class: /** ---An ATM that accesses a bank.- */ public-class-ATM- {- ---.-.-. ---/** ------Constructs an ATM for a given bank.-
  • 71. ------@param-aBank-the bank to which this ATM connects- ---*/---- ---public-ATM(Bank-aBank)-{-} ---/**- ------Sets the current customer number- ------and sets state to PIN.- ------(Precondition: state is START) ------@param-number-the customer number- ---*/ ---public-void-setCustomerNumber(int-number)-{-} simulating an automatic teller Machine we7 Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. ---/**- ------Finds customer in bank.- ------If found sets state to ACCOUNT, else to START.- ------(Precondition: state is PIN)- ------@param-pin-the PIN of the current customer- ---*/ ---public-void-selectCustomer(int-pin)-{-} ---/**- ------Sets current account to checking or savings. Sets- ------state to TRANSACT.- ------(Precondition: state is ACCOUNT or TRANSACT)- ------@param-account-one of CHECKING or SAVINGS- ---*/ ---public-void-selectAccount(int-account)-{-} ---/**-
  • 72. ------Withdraws amount from current account.- ------(Precondition: state is TRANSACT)- ------@param-value-the amount to withdraw ---*/ ---public-void-withdraw(double-value)-{-} ---.-.-. } Then run the javadoc utility to turn this documentation into HTML format. For conciseness, we omit the documentation of the other classes, but they are shown at the end of this example. step 5 Implement your program. Finally, the time has come to implement the ATM simulator. The implementation phase is very straight forward and should take much less time than the design phase. A good strategy for implementing the classes is to go “bottom- up”. Start with the classes that don’t depend on others, such as Keypad and BankAccount. Then implement a class such as Customer that depends only on the BankAccount class. This “bottom-up” approach allows you to test your classes individually. You will find the implementations of these classes at the end of this section. The most complex class is the ATM class. In order to implement the methods, you need to declare the necessary instance variables. From the class diagram, you can tell that the ATM has
  • 73. a bank object. It becomes an instance variable of the class: public-class-ATM {- ---private-Bank-theBank; ---.-.-. } From the description of the ATM states, it is clear that we require additional instance variables to store the current state, customer, and bank account: public-class-ATM {- ---private-int-state; ---private-Customer-currentCustomer; ---private-BankAccount-currentAccount; ---.-.-. } we8 Chapter 12 Object-Oriented design Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. Most methods are very straightforward to implement. Consider the selectCustomer method. From the design documentation, we have the description /**- ---Finds customer in bank.- ---If found sets state to ACCOUNT, else to START.- ---(Precondition: state is PIN)- ---@param-pin-the PIN of the current customer-
  • 74. */ This description can be almost literally translated to Java instructions: public-void-selectCustomer(int-pin) {- ---currentCustomer-=-theBank.findCustomer(customerNumber,- pin); ---if-(currentCustomer-==-null)- ---{ ------state-=-START; ---} ---else- ---{ ------state-=-ACCOUNT; ---} } We won’t go through a method-by-method description of the ATM program. You should take some time and compare the actual implementation to the CRC cards and the UML diagram. worked_example_1/bankaccount.java 1- /** 2- ---A bank account has a balance that can be changed by- 3- ---deposits and withdrawals. 4- */ 5- public-class-BankAccount 6- {-- 7- ---private-double-balance;- 8- 9- ---/**
  • 75. 10- ------Constructs a bank account with a zero balance. 11- ---*/ 12- ---public-BankAccount() 13- ---{-- 14- ------balance-=-0; 15- ---} 16- 17- ---/** 18- ------Constructs a bank account with a given balance. 19- ------@param-initialBalance-the initial balance 20- ---*/ 21- ---public-BankAccount(double-initialBalance) 22- ---{-- 23- ------balance-=-initialBalance; 24- ---} 25- - 26- ---/**- 27- ------Deposits money into the account. 28- ------@param-amount-the amount of money to withdraw 29- ---*/ 30- ---public-void-deposit(double-amount)- 31- ---{-- simulating an automatic teller Machine we9 Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. 32- ------balance-=-balance-+-amount; 33- ---} 34- 35- ---/**- 36- ------Withdraws money from the account. 37- ------@param-amount-the amount of money to deposit
  • 76. 38- ---*/ 39- ---public-void-withdraw(double-amount)- 40- ---{-- 41- ------balance-=-balance---amount; 42- ---} 43- 44- ---/**- 45- ------Gets the account balance. 46- ------@return-the account balance 47- ---*/ 48- ---public-double-getBalance() 49- ---{-- 50- ------return-balance;- 51- ---} 52- } worked_example_1/Customer.java 1- /** 2- ---A bank customer with a checking and a savings account.- 3- */ 4- public-class-Customer 5- {- 6- ---private-int-customerNumber; 7- ---private-int-pin; 8- ---private-BankAccount-checkingAccount; 9- ---private-BankAccount-savingsAccount; 10- 11- ---/** 12- ------Constructs a customer with a given number and PIN.- 13- ------@param-aNumber-the customer number- 14- ------@param-aPin-the personal identification number- 15- ---*/ 16- ---public-Customer(int-aNumber,-int-aPin) 17- ---{-
  • 77. 18- ------customerNumber-=-aNumber; 19- ------pin-=-aPin; 20- ------checkingAccount-=-new-BankAccount(); 21- ------savingsAccount-=-new-BankAccount(); 22- ---} 23- --- 24- ---/**- 25- ------Tests if this customer matches a customer number- 26- ------and PIN.- 27- ------@param-aNumber-a customer number- 28- ------@param-aPin-a personal identification number- 29- ------@return-true if the customer number and PIN match- 30- ---*/ 31- ---public-boolean-match(int-aNumber,-int-aPin) 32- ---{- 33- ------return-customerNumber-==-aNumber-&&-pin-==-aPin; 34- ---} 35- --- we10 Chapter 12 Object-Oriented design Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. 36- ---/**- 37- ------Gets the checking account of this customer.- 38- ------@return-the checking account- 39- ---*/ 40- ---public-BankAccount-getCheckingAccount() 41- ---{- 42- ------return-checkingAccount; 43- ---} 44- --- 45- ---/**-
  • 78. 46- ------Gets the savings account of this customer.- 47- ------@return-the checking account- 48- ---*/ 49- ---public-BankAccount-getSavingsAccount() 50- ---{- 51- ------return-savingsAccount; 52- ---} 53- } worked_example_1/bank.java 1- import-java.io.File; 2- import-java.io.IOException; 3- import-java.util.ArrayList; 4- import-java.util.Scanner; 5- 6- /** 7- ---A bank contains customers.- 8- */ 9- public-class-Bank 10- {- 11- ---private-ArrayList<Customer>-customers; 12- 13- ---/** 14- ------Constructs a bank with no customers.- 15- ---*/ 16- ---public-Bank() 17- ---{- 18- ------customers-=-new-ArrayList<Customer>(); 19- ---} 20- --- 21- ---/** 22- ------Reads the customer numbers and pins.- 23- ------@param-filename-the name of the customer file- 24- ---*/
  • 79. 25- ---public-void-readCustomers(String-filename)- 26- ---------throws-IOException 27- ---{- 28- ------Scanner-in-=-new-Scanner(new-File(filename)); 29- ------while-(in.hasNext()) 30- ------{- 31- ---------int-number-=-in.nextInt(); 32- ---------int-pin-=-in.nextInt(); 33- ---------Customer-c-=-new-Customer(number,-pin); 34- ---------addCustomer(c); 35- ------} 36- ------in.close(); 37- ---} 38- --- simulating an automatic teller Machine we11 Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. 39- ---/** 40- ------Adds a customer to the bank.- 41- ------@param-c-the customer to add- 42- ---*/ 43- ---public-void-addCustomer(Customer-c) 44- ---{- 45- ------customers.add(c); 46- ---} 47- --- 48- ---/**- 49- ------Finds a customer in the bank.- 50- ------@param-aNumber-a customer number- 51- ------@param-aPin-a personal identification number- 52- ------@return-the matching customer, or null if no
  • 80. customer- 53- ------matches- 54- ---*/ 55- ---public-Customer-findCustomer(int-aNumber,-int-aPin) 56- ---{- 57- ------for-(Customer-c-:-customers) 58- ------{- 59- ---------if-(c.match(aNumber,-aPin)) 60- ---------{ 61- ------------return-c; 62- ---------} 63- ------} 64- ------return-null; 65- ---} 66- } worked_example_1/aTm.java 1- /** 2- ---An ATM that accesses a bank. 3- */ 4- public-class-ATM- 5- {-- 6- ---public-static-final-int-CHECKING-=-1; 7- ---public-static-final-int-SAVINGS-=-2; 8- 9- ---private-int-state; 10- ---private-int-customerNumber; 11- ---private-Customer-currentCustomer; 12- ---private-BankAccount-currentAccount; 13- ---private-Bank-theBank; 14- --- 15- ---public-static-final-int-START-=-1; 16- ---public-static-final-int-PIN-=-2; 17- ---public-static-final-int-ACCOUNT-=-3;
  • 81. 18- ---public-static-final-int-TRANSACT-=-4; 19- 20- ---/** 21- ------Constructs an ATM for a given bank. 22- ------@param-aBank-the bank to which this ATM connects 23- ---*/---- 24- ---public-ATM(Bank-aBank) 25- ---{ 26- ------theBank-=-aBank; 27- ------reset(); 28- ---} 29- we12 Chapter 12 Object-Oriented design Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. 30- ---/** 31- ------Resets the ATM to the initial state. 32- ---*/ 33- ---public-void-reset() 34- ---{ 35- ------customerNumber-=--1; 36- ------currentAccount-=-null; 37- ------state-=-START;------------- 38- ---} 39- 40- ---/**- 41- ------Sets the current customer number- 42- ------and sets state to PIN.- 43- ------(Precondition: state is START) 44- ------@param-number-the customer number. 45- ---*/
  • 82. 46- ---public-void-setCustomerNumber(int-number)- 47- ---{ 48- ------customerNumber-=-number; 49- ------state-=-PIN; 50- ---} 51- 52- ---/**- 53- ------Finds customer in bank. 54- ------If found sets state to ACCOUNT, else to START. 55- ------(Precondition: state is PIN) 56- ------@param-pin-the PIN of the current customer 57- ---*/ 58- ---public-void-selectCustomer(int-pin) 59- ---{-- 60- ------currentCustomer- 61- ---------=-theBank.findCustomer(customerNumber,-pin); 62- ------if-(currentCustomer-==-null)- 63- ------{ 64- ---------state-=-START; 65- ------} 66- ------else- 67- ------{ 68- ---------state-=-ACCOUNT; 69- ------} 70- ---} 71- --- 72- ---/**- 73- ------Sets current account to checking or savings. Sets- 74- ------state to TRANSACT.- 75- ------(Precondition: state is ACCOUNT or TRANSACT) 76- ------@param-account-one of CHECKING or SAVINGS 77- ---*/ 78- ---public-void-selectAccount(int-account) 79- ---{ 80- ------if-(account-==-CHECKING) 81- ------{
  • 83. 82- ---------currentAccount-=-currentCustomer.getCheckingAccount (); 83- ------} 84- ------else 85- ------{ 86- ---------currentAccount-=-currentCustomer.getSavingsAccount() ; 87- ------} 88- ------state-=-TRANSACT; 89- ---} simulating an automatic teller Machine we13 Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. 90- 91- ---/**- 92- ------Withdraws amount from current account.- 93- ------(Precondition: state is TRANSACT) 94- ------@param-value-the amount to withdraw 95- ---*/ 96- ---public-void-withdraw(double-value) 97- ---{-- 98- ------currentAccount.withdraw(value); 99- ---} 100- 101- ---/**- 102- ------Deposits amount to current account.- 103- ------(Precondition: state is TRANSACT) 104- ------@param-value-the amount to deposit
  • 84. 105- ---*/ 106- ---public-void-deposit(double-value) 107- ---{-- 108- ------currentAccount.deposit(value); 109- ---} 110- 111- ---/**- 112- ------Gets the balance of the current account.- 113- ------(Precondition: state is TRANSACT) 114- ------@return-the balance 115- ---*/ 116- ---public-double-getBalance() 117- ---{-- 118- ------return-currentAccount.getBalance(); 119- ---} 120- 121- ---/** 122- ------Moves back to the previous state. 123- ---*/ 124- ---public-void-back() 125- ---{ 126- ------if-(state-==-TRANSACT) 127- ------{ 128- ---------state-=-ACCOUNT; 129- ------} 130- ------else-if-(state-==-ACCOUNT) 131- ------{ 132- ---------state-=-PIN; 133- ------} 134- ------else-if-(state-==-PIN) 135- ------{ 136- ---------state-=-START; 137- ------} 138- ---} 139- 140- ---/**
  • 85. 141- ------Gets the current state of this ATM. 142- ------@return-the current state 143- ---*/ 144- ---public-int-getState() 145- ---{ 146- ------return-state; 147- ---} 148- } we14 Chapter 12 Object-Oriented design Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. The following class implements a console-based user interface for the ATM. worked_example_1/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();
  • 86. 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- ---------{ 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- ------------{ 47- ---------------theATM.selectAccount(ATM.CHECKING); 48- ------------}
  • 87. 49- ------------else-if-(command.equalsIgnoreCase("B")) 50- ------------{ 51- ---------------theATM.selectAccount(ATM.SAVINGS); 52- ------------} 53- ------------else-if-(command.equalsIgnoreCase("C")) 54- ------------{ 55- ---------------theATM.reset(); 56- ------------} simulating an automatic teller Machine we15 Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. 57- ------------else 58- ------------{ 59- ---------------System.out.println("Illegal-input!");------------------ ------ 60- ------------} 61- ---------} 62- ---------else-if-(state-==-ATM.TRANSACT) 63- ---------{ 64- ------------System.out.println("Balance="-+-theATM.getBalance ()); 65- ------------System.out.print("A=Deposit,-B=Withdrawal,-C=Can cel:-"); 66- ------------String-command-=-in.next(); 67- ------------if-(command.equalsIgnoreCase("A")) 68- ------------{ 69- ---------------System.out.print("Amount:-"); 70- ---------------double-amount-=-in.nextDouble();
  • 88. 71- ---------------theATM.deposit(amount); 72- ---------------theATM.back(); 73- ------------} 74- ------------else-if-(command.equalsIgnoreCase("B")) 75- ------------{ 76- ---------------System.out.print("Amount:-"); 77- ---------------double-amount-=-in.nextDouble(); 78- ---------------theATM.withdraw(amount); 79- ---------------theATM.back(); 80- ------------} 81- ------------else-if-(command.equalsIgnoreCase("C")) 82- ------------{ 83- ---------------theATM.back(); 84- ------------} 85- ------------else 86- ------------{ 87- ---------------System.out.println("Illegal-input!"); 88- ------------} 89- ---------} 90- ------} 91- ---} 92- } program run Enter-customer-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 .-.-.
  • 89. we16 Chapter 12 Object-Oriented design Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. Here are the user-interface classes for the GUI version of the user interface. worked_example_1/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 button pad labeled with digits.- 12- */ 13- public-class-KeyPad-extends-JPanel 14- { 15- ---private-JPanel-buttonPanel; 16- ---private-JButton-clearButton; 17- ---private-JTextField-display; 18- 19- ---/** 20- ------Constructs the keypad panel.- 21- ---*/ 22- ---public-KeyPad() 23- ---{- 24- ------setLayout(new-BorderLayout()); 25- ---
  • 90. 26- ------//-Add display field- 27- --- 28- ------display-=-new-JTextField(); 29- ------add(display,-"North"); 30- 31- ------//-Make button panel- 32- 33- ------buttonPanel-=-new-JPanel(); 34- ------buttonPanel.setLayout(new-GridLayout(4,-3)); 35- ------ 36- ------//-Add digit buttons- 37- ------ 38- ------addButton("7"); 39- ------addButton("8"); 40- ------addButton("9"); 41- ------addButton("4"); 42- ------addButton("5"); 43- ------addButton("6"); 44- ------addButton("1"); 45- ------addButton("2"); 46- ------addButton("3"); 47- ------addButton("0");------ 48- ------addButton("."); 49- ------ 50- ------//-Add clear entry button- 51- ------ 52- ------clearButton-=-new-JButton("CE"); 53- ------buttonPanel.add(clearButton); 54- 55- ------class-ClearButtonListener-implements-ActionListener 56- ------{- simulating an automatic teller Machine we17
  • 91. Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. 57- ---------public-void-actionPerformed(ActionEvent-event) 58- ---------{- 59- ------------display.setText(""); 60- ---------} 61- ------} 62- ------ActionListener-listener-=-new-ClearButtonListener();- 63- 64- ------clearButton.addActionListener(new- 65- ------------ClearButtonListener());------------ 66- 67- ------add(buttonPanel,-"Center"); 68- ---} 69- 70- ---/** 71- ------Adds a button to the button panel.- 72- ------@param-label-the button label- 73- ---*/ 74- ---private-void-addButton(final-String-label) 75- ---{- 76- ------class-DigitButtonListener-implements-ActionListener 77- ------{- 78- ---------public-void-actionPerformed(ActionEvent-event) 79- ---------{- 80­ ­­­­­­­­­­­­//­Don’t add two decimal points­ 81- ------------if-(label.equals(".")- 82- ------------------&&-display.getText().indexOf(".")-!=--1)- 83- ------------{ 84- ---------------return; 85- ------------} 86- 87- ------------//-Append label text to button- 88- ------------display.setText(display.getText()-+-label); 89- ---------}
  • 92. 90- ------} 91- 92- ------JButton-button-=-new-JButton(label); 93- ------buttonPanel.add(button); 94- ------ActionListener-listener-=-new-DigitButtonListener(); 95- ------button.addActionListener(listener); 96- ---} 97- 98- ---/**- 99- ------Gets the value that the user entered.- 100- ------@return-the value in the text field of the keypad- 101 - ---*/ 102 - ---public-double-getValue() 103 - ---{- 104 - ------return-Double.parseDouble(display.getText()); 105 - ---} 106 - --- 107 - ---/**- 108 - ------Clears the display.- 109 - ---*/ 110 - ---public-void-clear() 111 - ---{- 112 - ------display.setText(""); 113 - ---} 114 - } we18 Chapter 12 Object-Oriented design Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. worked_example_1/aTmFrame.java
  • 93. 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 14- {- 15- ---private-static-final-int-FRAME_WIDTH-=-300; 16- ---private-static-final-int-FRAME_HEIGHT-=-300; 17- 18- ---private-JButton-aButton; 19- ---private-JButton-bButton; 20- ---private-JButton-cButton; 21- --- 22- ---private-KeyPad-pad; 23- ---private-JTextArea-display; 24- 25- ---private-ATM-theATM; 26- 27- ---/** 28- ------Constructs the user interface of the ATM frame.- 29- ---*/ 30- ---public-ATMFrame(ATM-anATM) 31- ---{- 32- ------theATM-=-anATM; 33- 34- ------//-Construct components- 35- ------pad-=-new-KeyPad();
  • 94. 36- 37- ------display-=-new-JTextArea(4,-20); 38- ------ 39- ------aButton-=-new-JButton("--A--"); 40- ------aButton.addActionListener(new-AButtonListener()); 41- 42- ------bButton-=-new-JButton("--B--"); 43- ------bButton.addActionListener(new-BButtonListener()); 44- 45- ------cButton-=-new-JButton("--C--"); 46- ------cButton.addActionListener(new-CButtonListener()); 47- ------ 48- ------//-Add components- 49- 50- ------JPanel-buttonPanel-=-new-JPanel(); 51- ------buttonPanel.add(aButton); 52- ------buttonPanel.add(bButton); 53- ------buttonPanel.add(cButton); 54- ------ 55- ------setLayout(new-FlowLayout()); 56- ------add(pad); 57- ------add(display); 58- ------add(buttonPanel); simulating an automatic teller Machine we19 Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. 59- ------showState(); 60- 61- ------setSize(FRAME_WIDTH,-FRAME_HEIGHT); 62- ---} 63-
  • 95. 64- ---/**- 65- ------Updates display message.- 66- ---*/ 67- ---public-void-showState() 68- ---{- 69- ------int-state-=-theATM.getState(); 70- ------pad.clear(); 71- ------if-(state-==-ATM.START) 72- ------{ 73- ---------display.setText("Enter-customer-numbernA-=-OK"); 74- ------} 75- ------else-if-(state-==-ATM.PIN) 76- ------{ 77- ---------display.setText("Enter-PINnA-=-OK"); 78- ------} 79- ------else-if-(state-==-ATM.ACCOUNT) 80- ------{ 81- ---------display.setText("Select-Accountn"- 82- ---------------+-"A-=-CheckingnB-=-SavingsnC-=-Exit"); 83- ------} 84- ------else-if-(state-==-ATM.TRANSACT) 85- ------{ 86- ---------display.setText("Balance-=-"- 87- ---------------+-theATM.getBalance()- 88- ---------------+-"nEnter-amount-and-select-transactionn" 89- ---------------+-"A-=-WithdrawnB-=-DepositnC-=-Cancel"); 90- ------} 91- ---} 92- --- 93- ---class-AButtonListener-implements-ActionListener 94- ---{- 95- ------public-void-actionPerformed(ActionEvent-event) 96- ------{- 97- ---------int-state-=-theATM.getState();
  • 96. 98- ---------if-(state-==-ATM.START) 99- ---------{ 100- ------------theATM.setCustomerNumber((int)-pad.getValue()); 101- ---------} 102- ---------else-if-(state-==-ATM.PIN) 103- ---------{ 104- ------------theATM.selectCustomer((int)-pad.getValue()); 105- ---------} 106- ---------else-if-(state-==-ATM.ACCOUNT) 107- ---------{ 108- ------------theATM.selectAccount(ATM.CHECKING); 109- ---------} 110- ---------else-if-(state-==-ATM.TRANSACT) 111- ---------{ 112- ------------theATM.withdraw(pad.getValue()); 113- ------------theATM.back(); 114- ---------} 115- ---------showState(); 116- ------} 117- ---} 118- --- we20 Chapter 12 Object-Oriented design Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. 119- ---class-BButtonListener-implements-ActionListener 120- ---{- 121- ------public-void-actionPerformed(ActionEvent-event) 122-- ------{- 123- ---------int-state-=-theATM.getState();
  • 97. 124- ---------if-(state-==-ATM.ACCOUNT) 125- ---------{ 126- ------------theATM.selectAccount(ATM.SAVINGS); 127- ---------} 128- ---------else-if-(state-==-ATM.TRANSACT) 129- ---------{ 130- ------------theATM.deposit(pad.getValue()); 131- ------------theATM.back(); 132- ---------} 133- ---------showState(); 134- ------} 135- ---} 136- 137- ---class-CButtonListener-implements-ActionListener 138- ---{- 139- ------public-void-actionPerformed(ActionEvent-event) 140- ------{- 141- ---------int-state-=-theATM.getState(); 142- ---------if-(state-==-ATM.ACCOUNT) 143- ---------{ 144- ------------theATM.reset(); 145- ---------} 146- ---------else-if-(state-==-ATM.TRANSACT) 147- ---------{ 148- ------------theATM.back(); 149- ---------} 150- ---------showState(); 151- ------} 152- ---} 153- } worked_example_1/aTmviewer.java 1- import-java.io.IOException; 2- import-javax.swing.JFrame; 3- import-javax.swing.JOptionPane;
  • 98. 4- 5- /** 6- ---A graphical simulation of an automatic teller machine.- 7- */ 8- public-class-ATM-Viewer 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- ------{- simulating an automatic teller Machine we21 Big Java, Late Objects, Cay Horstmann, Copyright © 2013 John Wiley and Sons, Inc. All rights reserved. 22- ---------JOptionPane.showMessageDialog(null,-"Error-opening-a ccounts-file."); 23- ---------return; 24- ------} 25- 26- ------JFrame-frame-=-new-ATMFrame(theATM); 27- ------frame.setTitle("First-National-Bank-of-Java");------ 28-
  • 99. ------frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E); 29- ------frame.setVisible(true); 30- ---} 31- } __MACOSX/._Chapter12 Worked out example.pdf CPII-Chapter12Lab copy.docx Computer Programming II Chapter 12 Lab Put your name here: 1. Please read the attached document and follow the instruction and implement the program 2. Run the ATMsimulator program An example input / output given below: Enter customer 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: A Balance=1000.0 A=Deposit, B=Withdrawal, C=Cancel: B Amount: 500 A=Checking, B=Savings, C=Quit: a Balance=500.0 A=Deposit, B=Withdrawal, C=Cancel:
  • 100. An example screen shot is below. Place the screen shot of the frame here. (How to capture the screenshot: While the program is running press ALT and PrtSc keys together. Go to the word doc and do a paste) 3. In the ATMViewer file Change the title to include your name: frame.setTitle("ATM BY Annu Prabhakar"); Run the ATMviewer program. Place your screen shot like the one below. Submitting your work: Make sure that you saved your answers in this document and that your file is correctly named: Lastname_Firstname_Ch12Lab.docx using your name. Use the Blackboard Assignment mechanism to submit your file. __MACOSX/._CPII-Chapter12Lab copy.docx customers.txt 1 1234 2 2468 3 3692 4 4826 5 5050
  • 101. 6 6284 7 7418 8 8642 9 9876 __MACOSX/._customers.txt