Академический Документы
Профессиональный Документы
Культура Документы
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
) h a
c o m
ฺ
ail eฺ
Java Programming g mLanguage,
id
Java SE 6 11 @ G u
2 e n t
9 2 0 ud
n t S t
( s ai this
A e - Volume 2
NActivityusGuide
L TR e to
O BE ens SL-275-SE6 G.2
E N le lic
M OR ferab
A RO -trans
GEN non
D61748GC11
Edition 1.1
June 2010
D67983
7i Business Solutions, SฺAฺ de CฺVฺ
Copyright © 2009, 2010, Oracle and/or its affiliates. All rights reserved.
Disclaimer
This document contains proprietary information, is provided under a license agreement containing restrictions on use and
disclosure, and is protected by copyright and other intellectual property laws. You may copy and print this document solely for
your own use in an Oracle training course. The document may not be modified or altered in any way. Except as expressly
permitted in your license agreement or allowed by law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express
authorization of Oracle.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
The information contained in this document is subject to change without notice. If you find any problems in the document,
please report them in writing to: Oracle University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This
document is not warranted to be error-free.
This training manual may include references to materials, offerings, or products that were previously offered by Sun
Microsystems, Inc. Certain materials, offerings, services, or products may no longer be offered or provided.Oracle and its
affiliates cannot be held responsible for any such references should they appear in the text provided.
s a
U.S. GOVERNMENT RIGHTS
The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or disclose these training materials are
) h a
c o m
restricted by the terms of the applicable Oracle license agreement and/or the applicable U.S. Government contract.
ฺ
ail eฺ
Trademark Notice
g m id
@ G u
owners.
0 2 11 ent
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective
t 9 2
S t ud
AMD, Opteron, the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced Micro
n
( sai this
Devices. Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are used
under license and are trademarks or registered trademarks of SPARC International, Inc. UNIX is a registered trademark
AN use
licensed through X/Open Company, Ltd.
R
LT se to
E
B en
O
N le lic
E
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Table of Contents
About This Workbook .......................................................Preface-xvii
Lab Goals ............................................................................... Preface-xvii
s a
Performing the Exercises ....................................................... Preface-xviii
) h a
c o m
Conventions ............................................................................. Preface-xix
ail eฺฺ
Typographical Conventions ............................................ Preface-xix
g m
Additional Conventions ................................................... Preface-xx
id
@ G u
0 2 11 ent
Getting Started..................................................................................1-1
t 9 2 t u d
Objectives ............................................................................................ 1-1
Exercise 1: Exploring Java™
a inProgram i s S
Errors...................................... 1-2
s h
N ( Compilation t
Preparation ................................................................................... 1-2
A s e
ExerciseL R atoTestu Program (Level
Task – Correcting
2:TCreating
and Runtime Errors ................... 1-2
1)..................................... 1-4
E
B en
Preparation s e
................................................................................... 1-4
O
N leTask lic1 – Copying the Account Class ......................................... 1-5
E
M OR ferab Task 2 – Creating the TestAccount Class ................................ 1-5
Task 3 – Compiling the TestAccount Class............................. 1-6
A RO -trans Task 4 – Running the TestAccount Program ........................... 1-6
E N n
G no Exercise 2: Creating a Test Program (Level 2)..................................... 1-7
Preparation ................................................................................... 1-7
Task 1 – Copying the Account Class ......................................... 1-8
Task 2 – Creating the TestAccount Class ................................ 1-8
Task 3 – Compiling the TestAccount Class............................. 1-9
Task 4 – Running the TestAccount Program ........................... 1-9
Exercise 2: Creating a Test Program (Level 3)................................... 1-10
Preparation ................................................................................. 1-10
Task 1 – Copying the Account Class ....................................... 1-11
Task 2 – Creating the TestAccount Class .............................. 1-11
Task 3 – Compiling the TestAccount Class........................... 1-12
Task 4 – Running the TestAccount Program ......................... 1-12
Exercise Summary .............................................................................. 1-13
Object-Oriented Programming ........................................................2-1
Objectives ............................................................................................ 2-1
v
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
LT se to
Exercise 3: Exploring Encapsulation, Version 2 (Level 1) ................ 2-12
E
B en Preparation ................................................................................. 2-12
O
N le lic Task 1 – Modifying the Account Class.................................... 2-13
E Task 2 – Modifying the TestAccount Class........................... 2-13
M OR ferab Task 3 – Compiling the TestAccount Class........................... 2-13
EN non
Exercise 3: Exploring Encapsulation, Version 2 (Level 2) ................ 2-14
G Preparation ................................................................................. 2-14
Task 1 – Modifying the Account Class.................................... 2-14
Task 2 – Modifying the TestAccount Class........................... 2-15
Task 3 – Compiling the TestAccount Class........................... 2-15
Task 4 – Running the TestAccount Program ......................... 2-15
Exercise 3: Exploring Encapsulation, Version 2 (Level 3) ................ 2-16
Preparation ................................................................................. 2-16
Task 1 – Modifying the Account Class.................................... 2-16
Task 2 – Modifying the TestAccount Class........................... 2-17
Task 3 – Compiling the TestAccount Class........................... 2-17
Task 4 – Running the TestAccount Program ......................... 2-17
Exercise 4: Creating Java Packages.................................................... 2-18
Preparation ................................................................................. 2-19
Task 1 – Creating the Java Packages ......................................... 2-19
Task 2 – Moving and Modifying the Account Class ............... 2-19
0 2 11 ent
Task 1 – Creating the Customer Class....................................... 3-9
n t 2
S t ud
Task 2 – Copying the TestBanking Class ................................ 3-9
9
sai this
Task 3 – Compiling the TestBanking Class............................. 3-9
(
Task 4 – Running the TestBanking Program ......................... 3-10
R AN use
Exercise 2: Creating Customer Accounts (Level 3) ........................... 3-11
E LT se to Preparation ................................................................................. 3-11
O B en Task 1 – Creating the Customer Class..................................... 3-12
E N le lic Task 2 – Copying the TestBanking Class .............................. 3-13
RO -trans
Task 4 – Running the TestBanking Program ......................... 3-13
A Exercise Summary .............................................................................. 3-14
GEN non Expressions and Flow Control........................................................4-1
Objectives ............................................................................................ 4-1
Exercise 1: Using Loops and Branching Statements ............................ 4-2
Preparation ................................................................................... 4-3
Task 1 – Creating the FooBarBaz Class..................................... 4-3
Task 2 – Compiling the FooBarBaz Class ................................. 4-3
Task 3 – Running the FooBarBaz Program ............................... 4-4
Hints............................................................................................. 4-4
Exercise 2: Using Conditional Statements in the Account Class (Level 1)
4-5
Preparation ................................................................................... 4-5
Task 1 – Modifying the Account Class ....................................... 4-6
Task 2 – Deleting the Current TestBanking Class....................... 4-6
Task 3 – Copying the TestBanking Class ................................ 4-6
Task 4 – Compiling the TestBanking Class............................. 4-6
vii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
ix
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
LT se to
Task 3 – Copying the TestReport Class ................................ 6-26
E
B en Task 4 – Compiling the TestReport Class ............................. 6-26
O
N le lic Task 5 – Running the TestReport Program ........................... 6-26
E Exercise 3: Creating a Batch Program (Advanced) ............................ 6-27
M OR ferab Preparation ................................................................................. 6-28
EN non
Task 2 – Creating the AccumulateSavingsBatch
G Class........................................................................................ 6-28
Task 3 – Copying the TestBatch Class................................... 6-29
Task 4 – Compiling the TestBatch Class ............................... 6-29
Task 5 – Running the TestBatch Program ............................. 6-29
Exercise Summary .............................................................................. 6-31
Advanced Class Features ............................................................... 7-1
Objectives ............................................................................................ 7-1
Exercise 1: Applying Static Members to a Design (Level 1) ............... 7-2
Preparation ................................................................................... 7-3
Task 1 – Modifying the Bank Class ............................................ 7-3
Task 2 – Modifying the CustomerReport Class ...................... 7-3
Task 3 – Deleting the Current TestReport Class ..................... 7-3
Task 4 – Copying the TestReport Class .................................. 7-4
Task 5 – Compiling the TestReport Class ............................... 7-4
EN non
Task 5 – Running the TestAnimals Program ......................... 7-20
G Exercise 2: Working With Interfaces and Abstract Classes
(Level 3)........................................................................................... 7-21
Preparation ................................................................................. 7-21
Task 1 – Creating the Pet Interface............................................ 7-21
Task 2 – Creating the Animal Classes ....................................... 7-22
Task 3 – Creating the TestAnimals Class .............................. 7-25
Task 4 – Compiling the TestAnimals Class........................... 7-26
Task 5 – Running the TestAnimals Program ......................... 7-26
Exercise Summary .............................................................................. 7-27
Exceptions and Assertions .............................................................8-1
Objectives ............................................................................................ 8-1
Exercise: Creating Your Own Exception (Level 1).............................. 8-2
Task 1 – Creating the OverdraftException Class................. 8-4
Task 2 – Modifying the Account Class...................................... 8-4
xi
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
R EN Preparation
b l ................................................................................... 9-3
e 1 – Modifying
M O feraTask 2 – Modifying the
Task Bank Class ............................................ 9-3
OR ferab
Task 3 – Creating the DataSource Class .............................. 11-12
M Task 4 – Deleting Unnecessary Classes .................................. 11-15
xiii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
R O rans Exercise:
Task 4 – Running the TestThreeThreads Program .............. 15-7
xv
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
Lab Preface
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Lab Goals
Upon completion of this workbook, you should be able to: a
Write a Java™ technology program using the fundamental language) h
●
as
c
elements: primitive types, reference types, arithmetic operators,o m
relational
ฺ
ail eฺ
operators, conditional statements, and iterative statements
g m d
@
Write a Java technology program using good1object-orientedG uiprogramming
●
2
concepts and principles: encapsulation,0inheritance, n t
1 einterfaces,
polymorphism, object association,t9
n and
S t ud in associations
2 multiplicity
( sai program
Write a robust Java technology t h isusing exception handling, generic
AN ucontrol se
●
R
collections, and concurrency
to program using the graphical user interface
T technology
LJava
E
Write a rich
● s e
B enprogramming interfaces (APIs), input/output (I/O) APIs,
O
(GUI)
lic APIs
application
N networking
E l e
OR ferab
and
M
A nsworkbook presents the lab exercises for each module of the Student Guide.
RO -traThis
GEN non
Lab Preface-xvii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Performing the Exercises
● Level 1 – This version of the lab provides the least amount of guidance.
Each bulleted paragraph provides a task description, but you must
determine your own way of accomplishing each task.
● Level 2 – This version of the lab provides more guidance. Although each
step describes what you should do, you must determine which commands
(and options) to input.
● Level 3 – This version of the lab is the easiest to accomplish because each
step provides exactly what you should input to the system. This level also
includes the task solutions for all three levels. s a
) h a
c o m
Also, several modules have advanced labs. These labs are optional. These labs are
ฺ
ail eฺ
intended for more advanced students who complete the primary labs easily.
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
Conventions
The following conventions are used in this course to represent various training
elements and alternative learning resources.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Typographical Conventions
Courier is used for the names of commands, files, directories, programming
code, and on-screen computer output; for example:
Use dir to list all files.
system% You have mail.
s a
Courier is also used to indicate programming constructs, such as class names,
) h a
methods, and keywords; for example:
c o m
ฺ
ail eฺ
The getServletInfo method is used to get author information.
g m id
The java.awt.Dialog class contains Dialog constructor.
@ G u
0 2 11 ent
Courier bold is used for characters and
t 9 d you type; for example:
2numberstuthat
n S
( sai type:
To list the files in this directory, t h is
# dir
R AN use
E LT se to
Courier bold
O B is also e nused for each line of programming code that is referenced
N le
in a textual l i c
description; for example:
E
M OR f1erimport
ab java.io.*;
A RO -trans 23 import javax.servlet.*;
Courier italics is used for variables and command-line placeholders that are
replaced with a real name or value; for example:
To delete a file, use the rm filename command.
Palatino italics is used for book titles, new words or terms, or words that you
want to emphasize; for example:
Read Chapter 6 in the User’s Guide.
These are called class options.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Additional Conventions
Java programming language examples use the following additional conventions:
● Method names are not followed with parentheses unless a formal or actual
parameter list is shown; for example:
“The doIt method...” refers to any method called doIt.
“The doIt() method...” refers to a method called doIt that takes no s a
arguments. ) h a
c o m
● ฺ
ail eฺ
Line breaks occur only where there are separations (commas), conjunctions
g m id
(operators), or white space in the code. Broken code is indented four spaces
@ G u
under the starting code.
0 2 11 ent
●
different from a command used ininthe
2 System
If a command used in the Solaris™ Operating
t9Microsoft
S ud (Solaris
tWindows OS) is
platform, both
( sa this
commands are shown; for example:
If working in the T R AN OS o u
se
E L se t
Solaris
B en
$ cd $SERVER_ROOT/bin
O
IfEworking lic Windows
N lineMicrosoft
M ORC:\>e r a b%SERVER_ROOT%\bin
O ransf
cd
A R t
G EN non-
Lab 1
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Getting Started
Objectives
Upon completion of this lab, you should be able to:
● Diagnose simple compilation and runtime errors s a
Create a test program for an existing class ) h a
●
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 1-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Exploring Java™ Program Errors
Preparation
No preparation is needed for this exercise.
s a
Tool Reference – Tool references used in this exercise: ) h a
c o m
● Java Development: Java Classes: Opening Java Classes ฺ
ail eฺ
Java Development: Java Classes: Modifying Java Classes: m
g Compilingid Java
●
@ G u
Classes
0 2 11 ent
●
t 9
Java Development: Java Classes: Modifying d Executing Java
2 JavatuClasses:
n S
Programs
( sai this
R AN u se
L T e to
For this exercise, you work in the TestProject project in the
E ns
d:\labs\student\exercises\01_intro\exercise1
B directory.
NO le lic e
E
R rab Compilation and Runtime Errors
TaskM–OCorrecting
fe
O n s
N AR n-Intrathis task, you are presented with four Java programs that contain errors. The
G E no errors can be either compilation or runtime errors. Your job is to diagnose and fix
those errors so the programs will execute.
N ( e th
T R A
t o us
B EL nse
N O lice
O RE rable
O M sfe
A R -tran
N on
GE n
additional hints.
Figure 1-1 shows the definition of the Account class using a Unified Modeling
Language (UML) Class diagram.
Account
«constructors»
+Account(initBalance:double)
s a
«methods»
+getBalance():double ) h a
+deposit(amt:double):void
c o m
+withdraw(amt:double):void ฺ
ail eฺ
g m id
@ G u
Figure 1-1 Banking Account Class
0 2 11 ent
t 9 2 t u d
n S
( sai sections:
This exercise contains the following
t h is
“Task 1 – CopyingAthe
●
R
NAccount
u seClass”
LT sthe
“Task 2 –ECreating
●
e to
TestAccount Class”
B n
N
“Task ●
l ce the TestAccount Class”
O 3 – Compiling
i
O RE “Taska b le– Running the TestAccount Program”
M sfer
●4
O
R -tran
A
G EN noPreparation
n
No preparation is needed for this exercise.
t 9 2 t u d
n S
sai this source file from the directory
2. Copy the pre-provided Account.java
(
se project.
ANof the uBankPrj
d:\labs\student\resources\01_intro\exercise2
R
to the source package
LT se to
E
B en
Task 2 E –N
O
Creating lic the TestAccount Class
l e
M OR ferab
s task, you complete the following steps to create a new TestAccount
RO -traInnthis
A
GEN non Java class.
Tool Reference – Java Development: Java Classes: Creating Java Classes
1. Create a new Java class in the BankPrj project with the following
characteristics:
Class Name: TestAccount
Project: BankPrj
Location: Source Packages
Package: default package
2. Edit the source file for the TestAccount class to add a main method.
The main method of the TestAccount class creates an Account object
with an initial balance of 100. It deposits 50 to and then withdraws 147
from the Account object. Finally, it must print out the balance of the
Account object to the standard output stream.
s a
Preparation
) h a
c o m
No preparation is needed for this exercise. ฺ
ail eฺ
g m id
@ G u
11 ent
Tool Reference – Tool references used in this2exercise:
0
t 9 d Projects
2Projects:tuCreating
n
Java Development: Java Application S
sai Modifying
●
output stream.
snippets.
s a
) h a
Preparation m
ฺ c o
a il
No preparation is needed for this exercise. g m i d eฺ
1 1 @ t Gu
Tool Reference – Tool references used in this 9 2 02 uden
exercise:
i n t S t
a
(s eProjects:
Java Development: Java Application
● i s
th Creating Projects
N s
AClasses:uModifying
●
L T R
Java Development: Java
t o Java Classes: Copying Java
Classes
B E nse
JavaN
● O liceJava Classes: Creating Java Classes
Development:
E Development:
RJava b le Java Classes: Modifying Java Classes: Compiling Java
O ●
M Classes
f er a
O s
R -tranJava Development: Java Classes: Modifying Java Classes: Executing Java
A
G EN non ●
Programs
t 9 2 t u d
n S
sai this source file from the directory
2. Copy the pre-provided Account.java
(
se project.
ANof the uBankPrj
d:\labs\student\resources\01_intro\exercise2
R
to the source package
LT se to
E
B en
Task 2 E –N
O
Creating lic the TestAccount Class
l e
M OR ferab
s task, you complete the following steps to create a new TestAccount
RO -traInnthis
A
GEN non Java class.
Tool Reference – Java Development: Java Classes: Creating Java Classes
1. Create a Java class with the following characteristics:
Class Name: TestAccount
Project: BankPrj
Location: Source Packages
Package: default package
2. Add the main method to the TestAccount class:
public class TestAccount {
public static void main(String[] args) {
// code here
}
}
acct.deposit(50.0);
5. Use the withdraw method to subtract 147 from the account.
acct.withdraw(147.0);
6. Use the getBalance method to retrieve the new account balance and use
the System.out.println method to display the balance to the standard
output stream.
System.out.println(“Final account balance is ” + acct.getBalance());
s a
Task 3 – Compiling the TestAccount Class ) h a
c o m
ฺ
atoilcorrecteฺ
Compile the TestAccount class, and make necessary changes
g m id
@ G u
11 ent
compilation errors.
0 2
n t 9 2
S t ud
Task 4 – Running the TestAccount ( sai thisProgram
R AN use
Run the TestAccount
E LTprogram.
e toIf there are runtime errors, make necessary
s
B en class, recompile it and run the program again.
changes to the TestAccount
O
N le lic
E
M OR
The
e r b TestAccount program should be similar to the following:
output ofathe
R O Final
a n sf
A tr
EN non-
account balance is: 3.0
G
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Lab 2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Object-Oriented Programming
Objectives
Upon completion of this lab, you should be able to:
● Use the Java API documentation to research a class s a
Explore information hiding and encapsulation ) h a
●
c o m
Use packages to organize your classes
● ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 2-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Using the Java API Documentation
Preparation
You must have a web browser window open.
s a
) h a
Task – Using the Java API Documentation m
ฺ c o
m ail eฺ
g
Complete the following steps to use the Java API documentation:
@ u id
1. Open the Java™ Platform, Standard Edition 2 61
1 nt G
2 0 d e
API Specification Web page
in the browser.
i n t9 Stu
( sa this
ANfor Java
u e
sPlatform
L T R
Note – The API documentation
t o SE 6 can be found at
E nse
http://java.sun.com/javase/6/docs/api.
B
N O lice
E thebjava.text
Rpanel
2. Select le package in the package list in the upper-left corner
O a
M sfeofr the API frameset.
O
R -t3.ranSelect the NumberFormat class in the class list in the lower-left panel.
A
G EN non 4. Read about the class in the top part of the documentation window on the
right panel of the frameset. Review the format and parse methods.
version, you create an Account class with public data members. You will then
create a test program that demonstrates the danger of using the public data
directly.
Figure 2-1 shows the UML class diagram of the Account class that you will
create in this exercise. This class will have one public data member (or instance
variable), called balance, that maintains the monetary value of the customer’s
bank account.
Account
s a
+balance : double ) h a
c o m
«constructors» ฺ
ail eฺ
+Account(initBalance:double)
g m id
@
1 NonHidingG u
Figure 2-1 UML Class Diagram of Account 2 1With e t
9 2 0 ud
i n t S t
saapplies
There is only one business rule(that t htoisthe Account class: The balance of
A
the bank account must never
R
Ngo below
u sezero. In this exercise, you will discover
LT cannot
that the Account class
E e toensure this business rule.
B en s
O lic the following sections:
N lcontains
This exercise
E e
M OR f“Taske
● rab1 – Deleting the Account Class”
A RO -trans “Task 2 – Creating the Account Class”
●
Preparation
No preparation is needed for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
After creating the Account class, add an instance variable balance and a
constructor according to the UML diagram in Figure 2-1. Initialize the balance
instance variable with the parameter of the constructor.
This class acts as a program to create an Account object with an initial balance
of 100. The test program will then add 47 and then subtract 150. Finally, the test
program must print out the balance of the object to the standard output stream.
s a
) h a
Task 4 – Compiling the TestAccount2 Class ilฺcom
g ma ideฺ
In this task, you compile the TestAccount2 class, 1 @ G
and make u
necessary
1 t
changes to correct compilation errors.
9 2 02 uden
a i nt is St
Task 5 – Running the N (s e th
TestAccount2 Program
R A u s
E LT se to
B run ethenTestAccount2 program.
In this task, you
O
E N le lic
R output
OThe r a bshould be similar to the following:
M e
sf account balance is -3.0
O raFinal
R n
E NA on-t
G n
M ORJavafeDevelopment:
● rab Java Classes: Modifying Java Classes: Executing Java
O s
R -tranPrograms
A
G EN non For this exercise, you work in the BankPrj project in the
d:\labs\student\projects directory.
In this task, you compile the TestAccount2 class and the Account class, and
make necessary changes to correct compilation errors.
s a
The output should be similar to the following:
) h a
c o m
Final account balance is -3.0
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
E Classes
M OR fJava
e ●
b
raDevelopment: Java Classes: Modifying Java Classes: Executing Java
O s
R -tran Programs
A
GEN non For this exercise, you work in the BankPrj project in the
d:\labs\student\projects directory.
3. Declare a variable within the main method of type Account named acct.
Also, in the same statement, initialize the variable acct to a new instance
of Account by passing 100.00 to the constructor as the initial balance.
Account acct = new Account(100.0);
4. Use the addition operator to add 47 to the account object’s balance.
acct.balance = acct.balance + 47.0;
5. Use the subtraction operator to subtract 150 from the account object’s
balance.
s a
acct.balance = acct.balance - 150.0;
) h a
6. m
Use the System.out.println method to display the balance to the
c o
standard output stream. ฺ
ail eฺ
System.out.println(“Final account balance is ” + acct.balance); g m id
@ G u
0 2 11 ent
Task 4 – Compiling the TestAccount2 n t 9 2
S t udClass
( sai this
R
In this task, you compile u se
AtheNTestAccount2
to compilation class
LT stoecorrect
make necessaryEchanges
and the Account class, and
errors.
O B en
E N le lic
Task
M OR a
5 – eRunning
f r b the TestAccount2 Program
A RO -trans
GEN non In this task, you run the TestAccount2 program.
The output should be similar to the following:
Final account balance is -3.0
manipulate the balance. You then use the test program that you created in Lab 1
to test that the business rule (balance must not fall below zero) is satisfied.
Figure 2-2 shows the UML class diagram of the Account class that you create.
This design for the Account class hides the instance variable, balance, and
supplies public methods to manipulate the account balance. The deposit
method adds money to the account. The withdraw method removes money from
the account. The getBalance method returns the current value of the balance
instance variable.
s a
Account
) h a
c o m
-balance : double
ฺ
ail eฺ
«constructors»
g m id
+Account(initBalance:double) @ G u
0 2 11 ent
ud
«methods»
t 9 2 t
+getBalance():double
n S
+deposit(amt:double):void
( sai this
AN use
+withdraw(amt:double):void
Figure 2-2
R
LT Diagram toof Account With Information Hiding
E
UML Class
B en s e
O licone business rule that must be maintained: The balance
Nthere lisestill
E
R raccount
Remember,
b must never go below zero. This business rule should be
MofO
the banke a
R a n sfin the withdraw method.
O enforced
A tr
G EN non- This exercise contains the following sections:
● “Task 1 – Modifying the Account Class”
● “Task 2 – Modifying the TestAccount Class”
● “Task 3 – Compiling the TestAccount Class”
● “Task 4 – Running the TestAccount Program”
Preparation
There is no preparation for this exercise.
The 150 withdraw command did not take effect, because it would have made the
balance drop below zero. However, the Account object did not tell program that
the withdraw command failed, it ignored the command. You will fix this problem
in future exercises.
s a
Preparation
) h a
c o m
There is no preparation for this exercise. ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
Tool Reference – Tool references used in this exercise:
t 9 d Compiling Java
2 JavatuClasses:
n
Java Development: Java Classes: Modifying S
sai this
●
Classes (
R
Java Development: Java se
N uModifying
AClasses: Java Classes: Executing Java
●
L T e to
BE ens
Programs
O
N lyou c in the BankPrj project in the
liwork
For thisEexercise, e
M OR ferab
d:\labs\student\projects directory.
A RO -trans
G EN Task
non 1 – Modifying the Account Class
In this task, you complete the following steps to modify the Account class:
1. Change the balance instance variable from public to private.
2. Add the deposit method that takes an amount (of type double) and adds
that amount to the balance. Save the new balance in the instance variable.
3. Add the withdraw method that takes an amount (of type double) and
subtracts that amount from the balance. Save the new balance in the
instance variable.
This operation might set the balance to a value below zero if the amount to
withdraw is larger than the current balance. You must use a conditional
statement to verify that the amount is not greater than the balance before
doing the subtraction. The conditional statement looks like the following:
if ( <boolean_test> ) {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
<statement_when_true>*
} else {
<statement_when_false>*
}
4. Add the getBalance method to return the balance instance variable.
s a
Preparation
) h a
c o m
There is no preparation for this exercise. ฺ
ail eฺ
g m id
@ G u
11 ent
Tool Reference – Tool references used in this2exercise:
0
Java Development: Java Classes:n t 9 2
S
Modifyingt ud Classes: Compiling Java
Java
sai this
●
Classes (
R
Java Development:
N Classes:
AJava u seModifying Java Classes: Executing Java
ProgramsELT to
●
B en s e
O
N exercise, c work in the BankPrj project in the
liyou
ForEthis l e
R rab
Od:\labs\student\projects
M f e directory.
A RO -trans
G EN noTask
n 1 – Modifying the Account Class
In this task, you complete the following steps to modify the Account class:
1. Change the balance instance variable from public to private.
private double balance;
2. Add the deposit method that takes an amount (of type double) and adds
that amount to the balance. Save the new balance in the balance instance
variable.
public void deposit(double amt) {
balance = balance + amt;
}
3. Add the withdraw method that takes an amount (of type double) and
subtracts that amount from the balance. Save the new balance in the
balance instance variable.
E N le lic
Task
M OR rab
4 –feRunning the TestAccount Program
O
R -tran s
A
GEN non In this task, you run the TestAccount program. The output should be similar
to the following:
Final account balance is 147.0
Figure 2-3 shows a UML diagram of the packages that you will create in this
exercise. The Account class is placed in the com.mybank.domain package and
the TestAccount class is placed in the com.mybank.test package.
com.mybank
test domain
s a
TestAccount Account ) h a
c o m
ฺ
ail eฺ
-balance : double
+main(args:String[])
g m id
«constructors»
@ G u
0 2 11 ent
+Account(initBalance:double)
n 9 2
«methods»
t S t ud
sai +deposit(amt:double):void
is
+getBalance():double
( t h
R AN use+withdraw(amt:double):void
E LT se to
O B en
Figure E2-3N The l e lic Structure of the Banking Project
Package
M OR ferab
RO -This s contains the following sections:
anexercise
A t r
G EN non Task 1 – Creating the Java Packages
●
Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
n t 9 2
S t ud
Task 5 – Running the TestAccount ( sai thisProgram
R AN use
LTTestAccount
In this task, you run the
E e to program. The code has not changed, so
the output shouldBbe similare s
nto the following:
O l i c
N lebalance is 147.0
R Eaccount
M O ferab
Final
A RO -trans
G EN non
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Lab 3
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Objectives
Upon completion of this lab, you should be able to:
● Explore reference variable assignment s a
Use a reference variable to encode an object association ) h a
●
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 3-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Investigating Reference Assignment
Figure 3-1 shows a class diagram for the MyPoint class that is provided in the
exercise directory. Notice that the instance variables, x and y, are both public so
you can access these data members in your test program directly. Also, the
toString method is used when you print the object using the
System.out.println method.
MyPoint
+x : int
+y : int s a
) h a
+toString() : String
c o m
ฺ
ail eฺ
Figure 3-1 UML Class Diagram for the MyPoint Class g m id
@ G u
0 211object
e n t
Your task is to create a test program that 2
n t 9 explores
S t ud references.
( sai sections:
This exercise contains the following t h is
R u se Class”
AtheNTestMyPoint
●
E LT se to
“Task 1 – Creating
“Task B e
2 – Compilingn the TestMyPoint Class”
●
O l i c
R EN “Taskb3le
● – Running the TestMyPoint Program”
O
M sfer a
O an
R Preparation
r
A - t
G EN non
No preparation is needed for this exercise.
GEN non Compiling the TestMyPoint Class” and “Task 3 – Running the
TestMyPoint Program”). If you do so, the output will look
something like the following:
Start point is [10,10]
End point is [20,30]
e. Declare a new variable of type MyPoint and call it stray. Assign
stray the reference value of the existing variable end.
f. Print out stray and end.
g. Assign new values to the x (such as 47) and y (such as 50) members
of the variable stray.
h. Print out stray, end, and start.
s a
Stray point is [20,30]
) h a
End point is [20,30]
c o m
ฺ
ail eฺ
Stray point is [47,50]
g m id
End point is [47,50] @ G u
Start point is [10,10]
0 2 11 ent
n t 9 2
S t ud
i
The values reported by end reflect theachange
s is in stray, indicating that
made
(
both variables refer to the sameNMyPointe t h
changed, which indicates R s object.of However,
Ait is independent
u
start has not
L T e to
that the other two variables.
O BE ens
E N le lic
M OR ferab
A RO -trans
G EN non
Figure 3-2 shows the UML class diagram of the Customer class and its
relationship to the Account class. This relationship can be read as: A customer
has one account.
com.mybank.domain
has-a 1
Customer Account
-firstName : String -balance : double
-lastName : String
s a
-account : Account
«constructors»
) h a
c o m
+Account(initBalance:double)
«constructors»
ฺ
ail eฺ
«methods»
+Customer(f:String, l:String)
g m id
+getBalance():double
«methods»
@ G u
11 ent
+deposit(amt:double):void
+getFirstName():String
0 2 +withdraw(amt:double):void
+getLastName():String
n t 9 2
S t ud
sai this
+getAccount():Account
+setAccount(acct:Account):void (
R AN use
Figure 3-2 E
UML to for the Customer Class
LTClassseDiagram
O B en
E e lic the following sections:
N lcontains
OR ferab
This exercise
M
O rans “Task 1 – Creating the Customer Class”
●
A R t
GEN non- ● “Task 2 – Copying the TestBanking Class”
● “Task 3 – Compiling the TestBanking Class”
● “Task 4 – Running the TestBanking Program”
Preparation
No preparation is needed for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
E N BankPrj
Project:
l e lic
M ORLocation:
e r a bSource Packages
R sf
O ranPackage:
N A n-t com.mybank.domain
G E no In the constructor, initialize the firstName and lastName instance variables
with the constructor parameters.
s a
Preparation
) h a
c o m
No preparation is needed for this exercise. ฺ
ail eฺ
g m id
@ G u
Tool Reference – Tool references used in this exercise:
0 2 11 ent
n t
Java Development: Java Classes: Creating 9 S t ud
2 Java Classes
●
i
saModifying isJava Classes: Copying Java
( t h
AN use
Java Development: Java Classes:
●
Classes R to
LTJavasClasses:
E
B en
Java Development:
● e Modifying Java Classes: Compiling Java
O
N le lic
Classes
E
M ORJavafeDevelopment:
●
r ab Java Classes: Modifying Java Classes: Executing Java
RO -trans
Programs
A
G EN non For this exercise, you work in the BankPrj project in the
d:\labs\student\projects directory.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
snippets.
s a
) h a
Preparation m
ฺ c o
a il
No preparation is needed for this exercise. g m i d eฺ
1 1 @ t Gu
Tool Reference – Tool references used 9 02exercise:
in2this u d en
i n t S t
a
(s eCreating
Java Development: Java Classes:
● i s
th Java Classes
N us Modifying Java Classes: Copying Java
AJava Classes:
Java Development:
●
T R t o
Classes EL
B e n se
N ODevelopment:
Java
●
l ic Java Classes: Modifying Java Classes: Compiling Java
E
R Classes bl e
O
M sfJava r a
e Development: Java Classes: Modifying Java Classes: Executing Java
O n ●
N AR n-tra Programs
GE no
For this exercise, you work in the BankPrj project in the
d:\labs\student\projects directory.
O M sfe variable.
A R String
public
- t r an getFirstName() {
G EN return
non firstName;
}
public String getLastName() {
return lastName;
}
5. Declare the getAccount method to retrieve the account instance
variable.
public Account getAccount() {
return account;
}
6. Declare the setAccount method to assign the account instance variable.
public void setAccount(Account acct) {
account = acct;
}
s a
Task 4 – Running the TestBanking Program
) h a
c o m
ฺ
il beฺ similar
In this task, you run the TestBanking program. The outputashould
to the following:
@ g m
u ide
Creating the customer Jane Smith.021
1 nt G
Creating her account with a 500.00 t 9 t de
2 balance.
u
Withdraw 150.00 s a in is S
N ( e th
us
Deposit 22.50
Withdraw 47.62 TR
A
t o
Customer [Smith,
B EL nJane] se has a balance of 324.88
NO le lic e
E
M OR ferab
A RO -trans
GEN non
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications
●
R AN use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR_____________________________________________________________
e r a b
R O ransf
A t
G EN non-
Lab 4
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Objectives
Upon completion of this lab, you should be able to:
● Use a simple for loop s a
Using conditional statements in business logic ) h a
●
c o m
ฺ
a l eฺ
(Optional) Use nested loops to implement a string search ioperation
●
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 4-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Using Loops and Branching Statements
Create a program that loops from 1–50 and prints each value on a separate line.
Also print foo for every multiple of three, bar for every multiple of five, and
baz for every multiple of seven. For example:
Preparation
There is no preparation required for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
O REClassa b le FooBarBaz
Name:
O er LoopProject
M sfProject:
A R -tran Location: Source Packages
GEN non
Package: default package
3. Declare the main method.
4. Use a for loop to iterate from 1–50 in the main method.
a. Print the current number.
b. Use three if statements to test if the current number is divisible by
three, five, or seven; if so, then print foo, bar, and baz as necessary.
Hints
These hints might help you to solve this exercise:
● Use the System.out.print method to print a string or value without
printing a new line character. You can use multiple print methods to print
a single line of text. You can use a single println method, with no
s a
arguments, to print a new line character.
) h a
● o m
The % operator calculates an integer remainder.
c
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
Figure 4-1 shows the UML class diagram of the Banking Project. The Account
class now includes a design change to the deposit and withdraw methods;
these methods must now return a boolean value to indicate the success (true)
or failure (false) of the operation.
com.mybank.domain
s a
Customer
has-a 1
Account ) h a
c o m
-firstName : String -balance : double ฺ
ail eฺ
-lastName : String
g m id
«constructors»
@ G u
11 ent
-account : Account
+Account(initBalance:double)
«constructors»
2 0 2 d
n t 9
«methods»
S t u
sai +getBalance():double
+Customer(f:String, l:String)
«methods» ( t h is
+getFirstName():String A N use+withdraw(amt:double):boolean
+deposit(amt:double):boolean
+getLastName():String R
LT se to
+getAccount():Account E
B en
O
N le lic
+setAccount(acct:Account):void
E
R rab
M OFigurefe4-1 UML Class Diagram of Banking Project
O n s
N AR n-tra
GE no This exercise contains the following sections:
● “Task 1 – Modifying the Account Class”
● “Task 2 – Deleting the Current TestBanking Class”
● “Task 3 – Copying the TestBanking Class”
● “Task 4 – Compiling the TestBanking Class”
● “Task 5 – Running the TestBanking Program”
Preparation
There is no preparation required for this exercise.
Classes
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Classes: Executing Java Programs
s a
Task 1 – Modifying the Account Class
) h a
c o m
In this task, you modify the Account class source file. This class a ฺ
il satisfyฺ the
must
m
UML diagram in Figure 4-1. In particular, the deposit andgwithdrawidmethods e
@ G u
1in this exercise.
must return a boolean value as described previously
2 1 n t
t 9 20 tude
a n is S
iTestBanking
Task 2 – Deleting the Current s
( e th Class
A N us
T R t
L the current o
B E
In this task, you delete
e n seof the
TestBanking class in the
O lic
com.mybank.test
N
package BankPrj project.
O RE rable
Task
O n fe
M3 – Copying
s the TestBanking Class
A R -tra
G EN non In this task, you copy the new version of the TestBanking.java file from the
d:\labs\student\resources\04_stmts\ directory into the
com.mybank.test package of the BankPrj project.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
M ● ra
O JavafeDevelopment: Java Classes: Modifying Java Classes: Compiling Java
O s
R -tranClasses
A
G EN non Java Development: Java Classes: Modifying Java Classes: Executing Java
●
Programs
M ● ra
O JavafeDevelopment: Java Classes: Modifying Java Classes: Compiling Java
O s
R -tranClasses
A
G EN non Java Development: Java Classes: Modifying Java Classes: Executing Java
●
Programs
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
Note – There are several advanced exercises in this course. These exercises are
optional and should only be attempted if you completed all of the previous
exercises for this module. s a
) h a
c o m
ฺ
ail eฺ
Preparation g m id
@ G u
0 2 11 ent
n t 2
There is no preparation required for this exercise.
9 S t ud
( s ai this
Tool Reference – Tool references
N uused ein this exercise:
A s
L TR Java
Java Development:
●
e o
tApplication Projects: Opening Projects
E s
B en Java Classes: Modifying Java Classes: Compiling Java
Java
● O
N le lic
Development:
E Classes
M OR fJava
e
b
raDevelopment:
O n s ● Java Classes: Modifying Java Classes: Executing Java
N AR n-tra Programs
GE no For this exercise, you work in the AdvancedLoopProject project in the
d:\labs\student\exercises\04_stmts\exercise3 directory.
There is an easy way to do this by using the indexOf method of the String
class. You can determine if a String s is a substring of some String x by
evaluating the expression x.indexOf(s) != -1. However, the purpose of this
exercise is to practice using loops, so you should solve the problem by using only
the charAt method and nested loops.
s a
In this task, you compile the TestIsSubString class.
) h a
c o m
Task 3 – Running the TestIsSubString Program ฺ
ail eฺ
g m id
@ G u
0 2
In this task, you run the TestIsSubString program.11 Theenoutput
t of the
9
program should be similar to the example tshown
n S t ud1 – Writing the
2 in ‘‘Task
isSubString Method’’ on page L4-13.
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
Hints
These hints might help you to solve this exercise.
● Use the charAt(int index) method in the String class to retrieve a
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
specific character from a string; the index starts with zero. For example.
"cat".charAt(0) is ‘c’, "cat".charAt(1) is ‘a’, and
"cat".charAt(2) is ‘t’.
● The length method returns the number of characters in the string; for
example, "cat".length() is 3.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications
●
R AN use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR_____________________________________________________________
e r a b
R O ransf
A t
G EN non-
Lab 5
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Arrays
Objectives
Upon completion of this lab, you should be able to:
● Declare, create, and manipulate one-dimensional primitive arrays s a
Use an array to represent a one-to-many object relationship ) h a
●
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 5-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1 – Using Primitive Arrays (Level 1)
Preparation
s a
) h a
There is no preparation for this exercise.
c o m
ฺ
ail eฺ
Tool Reference – Tool references used in this exercise: g m id
@
1 nProjectsG u
Java Development: Java Application Projects: 2 1Opening
e t
●
9 0 ud
2 Java Classes
●
i n t
Java Development: Java Classes: Creating S t
( saModifying
t h isJava Classes: Compiling Java
AN use
● Java Development: Java Classes:
Classes R to
LTJavasClasses:
● E
B en
Java Development: e Modifying Java Classes: Executing Java
O
N le lic
Programs
E
M OR ferab you work in the ArrayProject project in the
ans
For this exercise,
A RO -d:\labs\student\exercises\05_arrays\exercise1
t r directory.
E N n
G no
Task 1 – Creating the TestArrays Class
Complete the following steps:
1. Open the ArrayProject project in the
d:\labs\student\exercises\05_arrays\exercise1 directory.
4. Using the curly-brace notation, {}, initialize array1 to the first eight prime
numbers.
5. Display the contents of array1.
6. Assign the array2 variable equal to the array1. Modify the even indexed
element in array2 to be equal to the index value (for example,
array2[0] = 0; and array2[2] = 2; and so on). Print out array1.
A
GEN non
Preparation
s a
) h a
There is no preparation for this exercise.
c o m
ฺ
ail eฺ
Tool Reference – Tool references used in this exercise:gm id
@ G u
2 11 Opening
Java Development: Java Application Projects:
●
0 e n t Projects
n
Java Development: Java Classes:t 9 2 t udClasses
CreatingSJava
sai Modifying
●
N AR n-trad:\labs\student\exercises\05_arrays\exercise1 directory.
G E no
Task 1 – Creating the TestArrays Class
Complete the following steps:
1. Open the ArrayProject project in the
d:\labs\student\exercises\05_arrays\exercise1 directory.
Hint
The printArray support method might help you to solve this exercise, as
follows:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
N ( e th
T R A
t o us
B EL nse
N O lice
O RE rable
O M sfe
A R -tran
G EN non
Preparation
s a
) h a
There is no preparation for this exercise.
c o m
ฺ
ail eฺ
Tool Reference – Tool references used in this exercise: gm id
@ G u
● 2 11Opening
Java Development: Java Application Projects:
0 e n t Projects
n
Java Development: Java Classes: t 9 2 Java
Creating S t udClasses
sai Modifying
●
N AR n-trad:\labs\student\exercises\05_arrays\exercise1 directory.
GE no
Task 1 – Creating the TestArrays Class
Complete the following steps:
1. Open the ArrayProject project in the
d:\labs\student\exercises\05_arrays\exercise1 directory.
A N use
method (see ‘‘Hint’’ on page L5-6) display these integer arrays.
System.out.print("array1 isT");
L R to
printArray(array1); BE
e n se
NO le lic
System.out.println();
E
6.ORAssign athebarray2 variable equal to the array1. Modify the even indexed
M e r
R sf in array2 to be equal to the index value (for example,
O ranelement
N A n-t array2[0] = 0; and array2[2] = 2; and so on).
G E array2
no= array1;
// modify array2
array2[0] = 0;
array2[2] = 2;
array2[4] = 4;
array2[6] = 6;
// print array 1
System.out.print("array1 is ");
printArray(array1);
System.out.println();
System.out.print(array[i]);
// print a comma delimiter if not the last element
if ( (i + 1) < array.length ) {
System.out.print(", ");
}
}
System.out.print(’>’);
}
s a
) h a
Task 2 – Compiling the TestArrays Class c o m
ฺ
ail eฺ
In this task, you compile the TestArrays class. @g
m id
G u
0 2 11 ent
n t 9 2
S t ud
Task 3 – Running the TestArrays
( sai this Program
R AN useprogram. The output should be similar to
E L se to
In this task, you runTthe TestArrays
the following:
O B en
N is l<2, c 5, 7, 11, 13, 17, 19>
li3,
E
array1 e
R raisb <0, 3, 2, 7, 4, 13, 6, 19>
M Oarray1fe
O n s
N AR n-tra
GE no
Figure 5-1 shows the UML class diagram of the Banking Project. Your
assignment is to create the Bank class. A bank object keeps track of an
association between itself and its customers. You implement this one-to-many
association with an array of customer objects. You will also need to keep an
integer instance variable that keeps track of how many customers currently exist
in the bank.
s a
com.mybank.domain
) h a
c o m
Bank
ฺ
ail eฺ
g m id
@ G u
11 ent
-customers : Customer[]
-numberOfCustomers : int
0 2
n t 9 2
S t ud
sai this
«constructors»
+Bank()
(
«methods»
+addCustomer(f:String, l:String) TR
AN use
E L se to
+getNumOfCustomers():int
O B en
N le lic
+getCustomer(index:int):Customer
E
M OR ferab
R O rans serves
A t
EN non-
has-a 1
Customer Account
0..*
G
Figure 5-1 UML Class Diagram of Banking Project
Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
M OR fJava
e●
b
raDevelopment: Other Files: Deleting Files
O s
R -tran Java Development: Java Classes: Modifying Java Classes: Compiling Java
A ●
R EN ble
M
Task 2
O– Deleting
f e ra the Current TestBanking Class
A RO -trans
G EN non In this task, you delete the current TestBanking class in the
com.mybank.test source package of the BankPrj project.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
M ORJavafeDevelopment:
● rab Other Files: Deleting Files
O s
R -tranJava Development: Java Classes: Modifying Java Classes: Compiling Java
A ●
G EN non Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
Lab 6
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Class Design
Objectives
Upon completion of this lab, you should be able to:
● Create subclasses with inheritance and overriding of methods s a
Create a heterogeneous collection and use polymorphism ) h a
●
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 6-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Creating Bank Account Subclasses (Level 1)
O RE ra«methods»
ble
#Account(initBalance:double)
O M sfe +getBalance():double
A R -tran
E N on +deposit(amt:double):boolean
G n +withdraw(amt:double):boolean
SavingsAccount CheckingAccount
-interestRate : double -overdraftAmount : double
«constructors» «constructors»
+SavingsAccount(initBalance:double, +CheckingAccount(initBalance:double,
interestRate:double) overdraft:double)
+CheckingAccount(initBalance:double)
«methods»
+withdraw(amt:double):boolean
Preparation
s a
) h a
There is no preparation for this exercise.
c o m
ฺ
ail eฺ
Tool Reference – Tool references used in this exercise: gm id
@
1 Classes G u
Java Development: Java Classes: Creating
●
2 1Java e n t
9 0
2 Filestud
n t
Java Development: Other Files: Deleting
●
i S
s a h i s
●
A N ( useModifying
Java Development: Java Classes: t Java Classes: Copying Java
TR e to
Classes
L
●
O BE ensJava Classes: Modifying Java Classes: Compiling Java
Java Development:
E N le lic
Classes
M OR fJava
e
●
r b
aDevelopment: Java Classes: Modifying Java Classes: Executing Java
R O rans Programs
A t
GEN non- For this exercise, you work in the BankPrj project in the
d:\labs\student\projects directory.
following characteristics:
Class Name: SavingsAccount
Project: BankPrj
Location: Source Packages
Package: com.mybank.domain
s a
This class must satisfy the UML diagram in Figure 6-1 on page L6-2 and the
) h a
c o m
business rules defined in the introduction to ‘‘Exercise 1: Creating Bank Account
Subclasses (Level 1)’’ on page L6-2. ฺ
ail eฺ
g m id
@ G u
Task 3 – Creating the CheckingAccount 0 2 11 Class
e n t
n t 9 2
S t ud
( sai thiclass
In this task, you create the CheckingAccount s source file in the
com.mybank.domain source
R A N sethe BankPrj project with the
package of
u
LT se to
following characteristics:
E
O B CheckingAccount
e n
Class Name:
l i c
R EN BankPrj
Project: b le
O
M Location:f a
er Source Packages
O
R -tran s
A
G EN non Package: com.mybank.domain
This class must satisfy the UML diagram in Figure 6-1 on page L6-2 and the
business rules defined in the introduction to ‘‘Exercise 1: Creating Bank Account
Subclasses (Level 1)’’ on page L6-2.
s a
Task 7 – Running the TestBanking Program
) h a
c o m
ฺ
il beฺ similar
In this task, you run the TestBanking program. The outputashould
to the following:
@ g m
u ide
2 1 1 nt G
Creating the customer Jane Smith.
Creating her Savings Account with a 500.00 tbalance9 20 tand u de3% interest.
Creating the customer Owen Bryant. s a in is S
Creating his Checking Account withNa 500.00
h
( e tbalance
A u s and no overdraft
protection.
Creating the customer TimESoley. LTR se to
O B ewith n a 500.00 balance and 500.00 in
Creating his Checking Account
l i c
R EN ble
overdraft protection.
M
Creating theOcustomer
f e raMaria Soley.
RO -traher
Maria shares
A nsChecking Account with her husband Tim.
N on
ERetrieving
G n the customer Jane Smith with her savings account.
Withdraw 150.00: true
Deposit 22.50: true
Withdraw 47.62: true
Withdraw 400.00: false
Customer [Simms, Jane] has a balance of 324.88
Retrieving the customer Owen Bryant with his checking account with no
overdraft protection.
Withdraw 150.00: true
Deposit 22.50: true
Withdraw 47.62: true
Withdraw 400.00: false
Customer [Bryant, Owen] has a balance of 324.88
Retrieving the customer Tim Soley with his checking account that has
overdraft protection.
Withdraw 150.00: true
Deposit 22.50: true
Withdraw 47.62: true
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Retrieving the customer Maria Soley with her joint checking account with
husband Tim.
Deposit 150.00: true
Withdraw 750.00: false
Customer [Soley, Maria] has a balance of 150.0
E N Development:
l e
OR fJava b
Java
●
M e raDevelopment:
R O rans Classes
● Java Classes: Modifying Java Classes: Copying Java
A t
GEN non- Java Development: Java Classes: Modifying Java Classes: Compiling Java
●
Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs
Retrieving the customer Owen Bryant with his checking account with no
overdraft protection.
Withdraw 150.00: true
Deposit 22.50: true
Withdraw 47.62: true
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Retrieving the customer Tim Soley with his checking account that has
overdraft protection.
Withdraw 150.00: true
Deposit 22.50: true
Withdraw 47.62: true
Withdraw 400.00: true
Customer [Soley, Tim] has a balance of 0.0
s a
) h a
c o m
Retrieving the customer Maria Soley with her joint checking account with
husband Tim. ฺ
ail eฺ
Deposit 150.00: true
g m id
@ G u
11 ent
Withdraw 750.00: false
0 2
Customer [Soley, Maria] has a balance of 150.0
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
this.interestRate = interestRate;
}
s a
Complete the following steps:
) h a
1. Create the CheckingAccount class source file in the c o m
ฺ
ail eฺ
com.mybank.domain source package of the BankPrj project with the
g m id
following characteristics:
@ G u
Class Name: CheckingAccount
0 2 11 ent
n t 9 2
S t ud
Project: BankPrj
( s ai this
AN use
Location: Source Packages
R
LT se to
Package: com.mybank.domain
E
O B that CheckingAccount
e n extends the Account class.
Add code
N
so
l i c
O RE rable
O M sfe
package com.mybank.domain;
publicAclass
- t an
R CheckingAccount
r extends Account {
N
E insert n
G
}
//
no code here
2. Add the overdraftAmount instance variable to the CheckingAccount
class.
private double overdraftAmount;
3. Add a public constructor that takes two arguments: initBalance and
overdraftAmount. Pass the initBalance parameter to the super
constructor. Save the overdraftAmount parameter to the instance
variable.
public CheckingAccount(double initBalance, double overdraftAmount) {
super(initBalance);
this.overdraftAmount = overdraftAmount;
}
}
5. Override the withdraw method to use the overdraftAmount variable.
public boolean withdraw(double amount) {
boolean result = true;
if ( balance < amount ) {
double overdraftNeeded = amount - balance;
if ( overdraftAmount < overdraftNeeded ) {
result = false;
} else {
s a
balance = 0.0;
) h a
overdraftAmount -= overdraftNeeded;
c o m
} ฺ
ail eฺ
} else { g m id
@ G u
}
balance -= amount;
0 2 11 ent
return result;
n t 9 2
S t ud
}
( sai this
R AN use
Task 4 – Deleting E to
LTtheseCurrent TestBanking Class
B e n
E NO le lic
Rthis task,
a byou delete the current TestBanking class in the
Ocom.mybank.test
In
r
O M s f e source package of the BankPrj project.
AR n-tra n
E N
G no Task 5 – Copying the TestBanking Class
In this task, you copy the TestBanking.java file from the
d:\labs\student\resources\06_class1 directory into the
com.mybank.test source package of the BankPrj project. The new
TestBanking class sets CheckingAccount and SavingsAccount
objects to different customers.
Retrieving the customer Maria Soley with her joint checking account with
husband Tim.
Deposit 150.00: true
Withdraw 750.00: false
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
customers to accounts. That is, a given customer can have several accounts of
different types.
Figure 6-2 shows the UML class diagram of the relationships between bank,
customers, and accounts. What has changed is that a Customer object may now
have more than one account and these accounts may be of different types,
subclasses of the Account class.
com.mybank.domain s a
) h a
serves
c o m
Bank 0..* Customer
has-a
ฺ
0..*
ail eฺ
Account
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
SavingsAccount CheckingAccount
A N use
Figure 6-2 R
CustomerTWith Oneto
L se or More Different Accounts
E
B en
O
Nto modify c Customer class to support a heterogeneous collection
lithe
ofO
E
Your job
R ra
Account
is
b l e
objects.
M
O This sf e
A R a n
tr exercise contains the following sections:
G EN non- ● “Task 1 – Modifying the Customer Class”
● “Task 2 – Copying and Completing the CustomerReport Class”
● “Task 3 – Copying the TestReport Class”
● “Task 4 – Compiling the TestReport Class”
● “Task 5 – Running the TestReport Program”
Preparation
There is no preparation required for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
customers to accounts. That is, a given customer can have several accounts of
different types.
c o m
ฺ
ail eฺ
g m id
Preparation @ G u
0 2 11 ent
n t
There is no preparation required for this9 2
S
exercise. t ud
( sai this
AN uused
Tool Reference – Tool references
R sein this exercise:
LT sJava e o
tPackages:
E
B en
Java Development:
● Creating Java Packages
O lic Java Classes: Modifying Java Classes: Copying Java
N Development:
E Java
●
l e
M OR fClasses
e rab
A RO -trans Java
● Development: Java Classes: Modifying Java Classes: Compiling Java
N AR n-tra
G E no
M OR ferab
A RO -trans
GEN non
customers to accounts. That is, a given customer can have several accounts of
different types.
c o m
ฺ
ail eฺ
g m id
Preparation @ G u
0 2 11 ent
There is no preparation required for n t
this9 2
S
exercise. t ud
( sai this
Tool Reference – Tool A
R
N uused
references se in this exercise:
E LT sJava e toPackages: Creating Java Packages
O
●
B en
Java Development:
E N ●
l e lic Java Classes: Modifying Java Classes: Copying Java
Java Development:
M OR feClasses
rab
A RO -trans Java ● Development: Java Classes: Modifying Java Classes: Compiling Java
G EN non Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs
1. Add two instance variables to the Customer class: accounts (an array of
Account objects) and numberOfAccounts (an integer that keeps track of
the next accounts array index). This replaces the single account
reference variable, which should be removed.
private Account[] accounts;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
blocks that start and end with /*** ... ***/. These comments indicate
the location of the code that you must supply.
a. Use the instanceof operator to test what type of account this is and
set account_type to an appropriate value, such as Savings
Account or Checking Account.
if ( account instanceof SavingsAccount ) {
account_type = "Savings Account";
} else if ( account instanceof CheckingAccount ) {
account_type = "Checking Account";
} else { s a
account_type = "Unknown Account Type"; ) h a
}
c o m
il ฺ
b. Print out the type of account and the balance. ma eฺ
g
@current i d
ubalance
System.out.println(" " + account_type + ":
1 1 t G is "
9 2 02 uden
+ account.getBalance());
a i nt is St
Task 3 – Copying the N (s e th Class
TestReport
T R A
t o us
In this task, B ELcopy nthesTestReport.java
e
O you
l i c e file from the
EN ble source package of the BankPrj
d:\labs\student\resources\06_class1
R
directory into the
M O fera
com.mybank.test project.
A RO -trans
G EN noTask
n 4 – Compiling the TestReport Class
In this task, you compile the TestReport class.
Note – This is an advanced exercise. This exercise is optional and should only be
attempted if you completed all of the previous exercises for this module.
Figure 6-3 shows the dependencies between the class used by the TestBatch
program.
TestBatch
s a
) h a
c o m
ฺ
ail eฺ
g m id
AccumulateSavingsBatch
@ u
CustomerReport
G
-bank : Bank
0 2 11: Bank
-bank
e n t
«methods»
n t 9 S t ud
2 «methods»
+setBank(bank:Bank):void(s
+doBatch():void ai thi+generateReport():void
s
AN use
+setBank(bank:Bank):void
R
LT se to
E
B en
O lic
N SavingsAccount
E l e
M OR-interestRate
f e r a b
O n s : double
N AR n-tra «constructors»
GE no +SavingsAccount(initBalance:double,
interestRate:double)
«methods»
+accumulateInterest():void
Preparation
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
variable.
4. Add a doBatch method using the following hints:
for each Customer in the Bank do
for each Account in the Customer do
if the Account is a SavingsAccount,
then call the accumulateInterest method
CUSTOMERS REPORT
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
================
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
Lab 7
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Objectives
Upon completion of this lab, you should be able to:
● Apply static class members to resolve a design decision. s a
Create abstract classes and interfaces, and explore the polymorphic ) h a
●
c o m
properties of these types of components ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 7-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Applying Static Members to a Design (Level 1)
which contains the set of customers for the bank. The project team has decided
that this is a risky design because it would be possible to instantiate multiple
Bank objects each with the potential to contain different sets of customers.
The design team has decided to make the Bank class a utility class. A utility class
is one that is not instantiated and all of its members are static. Figure 7-1 shows
the new design for the Bank class. Your job is to program these changes to the
Bank class and to all of the classes that use the Bank class.
s a
com.mybank.domain
) h a
c o m
Bank
ฺ
ail eฺ
g m id
-customers : Customer[] @ G u
-numberOfCustomers : int
0 2 11 ent
«constructors»
n t 9 2
S t ud
-Bank()
( sai this
«methods»
R AN use
+getNumOfCustomers():int EL
T e to
+addCustomer(f:String, l:String)
O B ens
N le lic
+getCustomer(index:int):Customer
E
M OR ferab
R O rans serves
Preparation
There is no preparation required for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
which contains the set of customers for the bank. The project team has decided
that this is a risky design because it would be possible to instantiate multiple
Bank objects each with the potential to contain different sets of customers.
The design team has decided to make the Bank class a utility class. A utility class
is one that is not instantiated and all of its members are static. Figure 7-1 on
page L7-2 shows the new design for the Bank class. Your job is to program these
changes to the Bank class and to all of the classes that use the Bank class.
c o m
● “Task 2 – Modifying the CustomerReport Class” ฺ
ail eฺ
g m id
●“Task 3 – Deleting the Current TestReport Class”
@ G u
●“Task 4 – Copying the TestReport Class”
0 2 11 ent
t 9 2 Class”tud
●
a i n
“Task 5 – Compiling the TestReport
i s S
s h
( e t Program”
●“Task 6 – Running the
A NTestReport
us
T R t o
B EL nse
Preparation
N O lice
O RE rable
O M There
n s feis no preparation required for this exercise.
N AR n-tra
GE no Tool Reference – Tool references used in this exercise:
● Java Development: Java Application Projects: Opening Projects
● Java Development: Other Files: Deleting Files
● Java Development: Java Classes: Modifying Java Classes: Copying Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs
which contains the set of customers for the bank. The project team has decided
that this is a risky design because it would be possible to instantiate multiple
Bank objects each with the potential to contain different sets of customers.
The design team has decided to make the Bank class a utility class. A utility class
is one that is not instantiated and all of its members are static. Figure 7-1 on
page L7-2 shows the new design for the Bank class. Your job is to program these
changes to the Bank class and to all of the classes that use the Bank class.
c o m
● “Task 2 – Modifying the CustomerReport Class” ฺ
ail eฺ
g m id
“Task 3 – Deleting the Current TestReport Class”
●
@ G u
“Task 4 – Copying the TestReport Class”
●
0 2 11 ent
t 9 2 Class”tud
●
a i n
“Task 5 – Compiling the TestReport
i s S
s h
( e t Program”
“Task 6 – Running the
●
A NTestReport
us
T R t o
B EL nse
Preparation
N O lice
O RE rable
O M There
n s feis no preparation required for this exercise.
N AR n-tra
G E no Tool Reference – Tool references used in this exercise:
● Java Development: Java Application Projects: Opening Projects
● Java Development: Other Files: Deleting Files
● Java Development: Java Classes: Modifying Java Classes: Copying Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Animal
{abstract} «interface»
Pet
#legs : int
«constructors» +getName():String
s a
#Animal(legs:int) +setName(n:String):void
) h a
«methods»
+play()
c o m
+walk():void ฺ
ail eฺ
+eat():void
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
Spider Cat ( sai thisFish
e : String
AN us-name
-name : String R
LT se to «constructors»
«constructors» E
B en
«constructors»
+Spider()
N O
+Cat(n:String)
l ic +Fish()
«methods» E
R rabl
+Cat() e «methods»
+eat():void O f e
M s«methods» +getName():String
O
R -tran +getName():String +setName(n:String):void
A
N on +play():void
G E n
+setName(n:String):void
+play():void +walk():void
+eat():void +eat():void
Preparation
There is no preparation required for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
The Pet interface must satisfy the UML diagram in Figure 7-1 on page L7-2.
The Animal class must satisfy the UML diagram in Figure 7-1 on page L7-2.
The action methods (walk and eat) print a statement to standard output that
reflects the animal. For example, the walk method for the Animal class might
s a
say something similar to This animal walks on 4 legs, where 4 is the
) h a
value of the legs instance variable.
c o m
ฺ
ail eofฺ the
m
2. Create the Spider, Cat, and Fish classes in the Source Packages
id 7-1 on
g in Figure
@
InterfaceProject project to satisfy the UML diagram
G u
page L7-2.
0 2 11 ent
n t 9 2
S t ud
( s ai this
Task 3 – Creating the TestAnimals N use Class
A
L TR e to
BE steps:
Complete the following
O e n s
1. InEthis
c the TestAnimals class with the following
N task,leyoulicreate
M ORcharacteristics:
e r a b
R sf Name: TestAnimals
O ranClass
A t
G EN non- Project: InterfaceProject
Location: Source Packages
Package: default package
2. Add the main method to create and manipulate instances of the classes you
created previously.
Start with:
Fish d = new Fish();
Cat c = new Cat("Fluffy");
Animal a = new Fish();
Animal e = new Spider();
Pet p = new Cat();
Experiment by:
● Calling the methods in each object
● Casting objects
Using polymorphism
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
G EN non Java Development: Java Classes: Modifying Java Classes: Compiling Java
●
Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs
The Pet interface must satisfy the UML diagram in Figure 7-1 on page L7-2.
O REb. raDeclare
ble a protected integer instance variable called legs, which
O M sfe records the number of legs for this animal.
A R -tran c. Define a protected constructor that initializes the legs instance
GEN non variable.
d. Declare an abstract method eat.
e. Declare a concrete method walk that prints out something about how
the animals walks (include the number of legs).
EN non
constructor to specify that all cats have four legs.
G d. Define another constructor that takes no parameters. Have this
constructor call the previous constructor (using the this keyword)
and pass an empty string as the argument.
e. Implement the Pet interface methods.
f. Implement the eat method.
4. Create the Fish class.
a. Create the Fish class with the following characteristics:
Class Name: Fish
Project: InterfaceProject
Location: Source Packages
Package: default package
Add code so that Fish extends the Animal class and implements the
Pet interface.
b. This class must include a String instance variable to store the name
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
of the pet.
c. Define a no-arg constructor that calls the superclass constructor to
specify that fish do not have legs.
d. Implement the Pet interface methods.
e. Override the walk method. This method should call the super method
and they print a message that fish do not walk
f. Implement the eat method.
s a
) h a
Task 3 – Creating the TestAnimals Class m
ฺ c o
a il
Complete the following steps: g m i d eฺ
1 1 @ t Gu
1. In this task, you create the TestAnimals
0 2 dwith
class
e nthe following
characteristics: 2
t9 Stu
i n
Class Name: TestAnimals ( sa this
R AN use
Project: InterfaceProject
E LT sPackages
e to
B en
Location:
O
Source
E N ledefault
Package: lic package
R b
rathe main method to create and manipulate instances of the classes you
O2. f.Add
M e
A RO -trans created previously.
GEN non Start with:
Fish d = new Fish();
Cat c = new Cat("Fluffy");
Animal a = new Fish();
Animal e = new Spider();
Pet p = new Cat();
Experiment by:
● Calling the methods in each object
● Casting objects
● Using polymorphism
● Using super to call superclass methods
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
class Animal. Several of the animal classes implement an interface called Pet.
Use Figure 7-2 on page L7-12 as a reference. You experiment with variations of
these animals, their methods, and polymorphism.
A RO -trans Java
● Development: Java Classes: Modifying Java Classes: Compiling Java
The Pet interface must satisfy the UML diagram in Figure 7-1 on page L7-2.
public interface Pet {
public String getName();
public void setName(String n);
public void play();
}
s a
) h a
Task 2 – Creating the Animal Classes c o m
ฺ
ail eฺ
g m id
Complete the following steps: @ G u
0 2 11 ent
1. Create the Animal class.
n t 9 2
S t ud
a. ai thethfollowing
Create the Animal classswith
( is characteristics:
AN use
Class Name: Animal
R
Project:E LT se to
InterfaceProject
O B en
E N le lSource
Location: ic Packages
M OR fePackage:
rab default package
A RO -trana.s Declare a protected integer instance variable called legs, which
EN non
Gprotected
records the number of legs for this animal.
int legs;
b. Define a protected constructor that initializes the legs instance
variable.
protected Animal(int legs) {
this.legs = legs;
}
c. Declare an abstract method eat.
public abstract void eat();
d. Declare a concrete method walk that prints out something about how
the animals walks (include the number of legs).
public void walk() {
System.out.println("This animal walks on " + legs + " legs.");
}
2. Create the Spider class.
a. Create the Spider class with the following characteristics:
Class Name: Spider
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Project: InterfaceProject
Location: Source Packages
Package: default package
Add code so that Spider extends the Animal class.
a. The Spider class extends the Animal class.
public class Spider extends Animal {
// more code here
s a
}
) h a
b. o m
Define a no-arg constructor that calls the superclass constructor to
c
specify that all spiders have eight legs. ฺ
ail eฺ
g m id
public Spider() { @ G u
super(8);
0 2 11 ent
}
n t 9 2
S t ud
sai this
c. Implement the eat method.
(
public void eat() {
R AN use
T eeats
System.out.println("TheLspider
E to a fly.");
} B en s
O
N the
3. ECreate lic class.
l e Cat
M OR fa.eraCreate
b
the Cat class with the following characteristics:
O n s
N AR n-tra Class Name: Cat
GE n o Project: InterfaceProject
Location: Source Packages
Package: default package
Add code so that Cat extends the Animal class and implements the
Pet interface.
b. This class must include a String instance variable to store the name
of the pet.
private String name;
c. Define a constructor that takes one String parameter that specifies
the cat’s name. This constructor must also call the superclass
constructor to specify that all cats have four legs.
public Cat(String n) {
super(4);
name = n;
}
d. Define another constructor that takes no parameters. Have this
constructor call the previous constructor (using the this keyword)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
return name;
}
public void play() {
System.out.println("Fish swim in their tanks all day.");
}
e. Override the walk method. This method should call the super method
and they print a message that fish do not walk
public void walk() {
super.walk();
s a
System.out.println("Fish, of course, can’t walk; they swim.");
) h a
}
c o m
f. Implement the eat method.
ฺ
ail eฺ
g m id
public void eat() { @ G u
System.out.println("Fish eat pond scum."); 211 n t
2 0 ud e
}
n t 9 S t
( sai this
Task 3 – CreatingTthe R AN u se
TestAnimals Class
L t o
B E nse
N Othe following
Complete l i ce steps:
O REIn rthis
1. a le you create the TestAnimals class with the following
btask,
O e
M sfcharacteristics:
n
AR n-tra Class Name: TestAnimals
E N
G no Project: InterfaceProject
Location: Source Packages
Package: default package
2. Add the main method to create and manipulate instances of the classes you
created previously.
Here is a sample test program:
public class TestAnimals {
public static void main(String[] args) {
Fish f = new Fish();
Cat c = new Cat("Fluffy");
Animal a = new Fish();
Animal e = new Spider();
s a
) h a
Task 4 – Compiling the TestAnimals Class o m
ฺ c
m ail eฺ
In this task, you compile the TestAnimals class.
@ g u id
11 ent G
0 2
Task 5 – Running the TestAnimals n t 9 S t ud
2 Program
( sai this
e
AN usprogram.
R
In this task, you run the TestAnimals
LT se to
E
B en
O
N le lic
E
M OR ferab
A RO -trans
G EN non
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Lab 8
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Objectives
Upon completion of this lab, you should be able to create an application
exception and apply the declare-or-handle rule to the account classes.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 8-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise: Creating Your Own Exception (Level 1)
and withdraw methods return a Boolean flag to indicate whether the operation
was successful or not. This design has several flaws, one of which is that a false
return value does not give the calling client any indication of why the operation
was not successful. In the new design, you will use exceptions to indicate
operation failure.
Figure 8-1 shows UML class diagram of this new design. In UML parlance, the
«send» dependency indicates that the method on the source operation (the
withdraw method) may throw an OverdraftException.
s a
) h a
com.mybank.domain m
ฺ c o
m ail eฺ
Account
«exception»g
@ u id
#balance : double 1 nt
1java.lang}
Exception G
2 0 2
{from
de
«constructors»
t 9 S t u
#Account(initBalance:double)
s a in«constructors»
i s
h
N ( use+Exception(msg:String)
t
«methods»
A
+getBalance():double
+deposit(amt:double):void EL
TR e to «methods»
O B ens +getMessage():String
+withdraw(amt:double):void
l i c
R EN ble «send»
M O fera
R O a n s
CheckingAccount
«exception»
NA on-tr : double
OverdraftException
G E-overdraftAmount
n -deficit : double
«constructors»
«constructors»
+CheckingAccount(initBalance:double,
overdraft:double) +OverdraftException(msg:String,
deficit:double)
+CheckingAccount(initBalance:double)
«methods»
«methods»
«send» +getDeficit():double
+withdraw(amt:double):boid
Preparation
There is no preparation required for this exercise.
O M sfe
A R -tran
GEN non
following characteristics:
Class Name: OverdraftException
Project: BankPrj
Location: Source Packages
Package: com.mybank.domain
Add code so that OverdraftException extends the Exception class.
This class must satisfy the UML diagram in Figure 8-1 on page L8-2.
s a
) h a
c o m
Task 2 – Modifying the Account Class ฺ
ail eฺ
g m id
@ G u
In this task, you modify the Account class source file
0 2 11in theent
com.mybank.domain source package of the 2
t 9 t d This class must
BankPrjuproject.
a i
satisfy the UML diagram in Figure 8-1 on n page s
L8-2.
i S In particular, the deposit
s h
and withdraw methods should not( return a boolean
A N use t flag.
L TR e to
Task 3 – Modifying O BE the e n sCheckingAccount Class
E N le lic
InO
R ryou a bmodify the CheckingAccount class source file in the
M e
this task,
sf
O com.mybank.domain
A R t r a n source package of the BankPrj project. This class must
withdraw method so that it does not return a value (that is, void). Declare that
this method throws the OverdraftException. Modify the code to throw an
exception when the overdraftProtection amount is not sufficient to cover
the deficit; use the message Insufficient funds for overdraft
protection for this exception.
A RO -trans
G EN Task
non 7 – Running the TestBanking Program
In this task, you run the TestBanking program.
E N Development:
l e
OR fJava b
Java
●
M e raDevelopment:
R O rans Classes
● Java Classes: Modifying Java Classes: Copying Java
A t
GEN non- Java Development: Java Classes: Modifying Java Classes: Compiling Java
●
Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs
s a
package com.mybank.domain;
) h a
public class OverdraftException extends Exception {
c o m
// insert code here ฺ
ail eฺ
} g m id
@ G u
2. Add a private instance variable called deficit
0 2 11 thate n t a double.
holds
private final double deficit;
n t 9 2
S t ud
i twoisarguments: message and deficit. The
satakes
3. Add a public constructor(that
N e th
message parameterAshould be
T R t o uthespassed to the superclass constructor. The
E L se
deficit parameter initializes deficit instance variable.
O B en msg, double deficit) {
lic
public OverdraftException(String
super(msg); EN l e
OR f=edeficit;
this.deficit
M rab
}
A RO -trans
G EN non 4. Add a public accessor called getDeficit.
public double getDeficit() {
return deficit;
}
Modify the withdraw method so that it does not return a value (that is, void).
Declare that this method throws the OverdraftException. Modify the code to
throw an exception if necessary. There are two cases that need to be handled.
First, there is a deficit with no overdraft protection; use the message No
overdraft protection for this exception. Second, the
overdraftProtection amount is not sufficient to cover the deficit; use the
message Insufficient funds for overdraft protection for this
exception.
protection",
overdraftNeeded);
} else {
balance = 0.0;
overdraftAmount -= overdraftNeeded;
}
} else {
balance = balance - amount;
}
s a
}
) h a
c o m
ฺ
ail eฺ
Task 4 – Deleting the Current TestBanking g Class
m id
@
1 nt G u
2 1class
In this task, you delete the current TestBanking
t 9 2 0
t u dinethe
com.mybank.test source package of
a inthe BankPrj
i s S project.
s h
A N ( use t
Task 5 – Copying the L TRTestBanking
e to Class
E
B en s
O
Nyou copy c TestBanking.java file from the
lithe
E
In this task, l e
M OR ferab
d:\labs\student\resources\08_except directory to the
R O rans
com.mybank.test source package of the BankPrj project.
A t
G EN non-
Task 6 – Compiling the TestBanking Class
In this task, you compile the TestBanking class.
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Lab 9
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Objectives
Upon completion of this lab, you should be able to:
● Use a generic collection to manage a one-to-many association s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 9-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Using Collections to Represent Association (Level 1)
Figure 9-1 shows the domain model of the Bank project with the class
associations: a bank serves many customers, and a customer has many accounts. s a
Figure 9-1 also shows the detailed design for Bank and Customer classes that ) h a
use a generic List to maintain these links. c o m
ฺ
ail eฺ
g m id
@ G u
com.mybank.domain
0 2 11 ent
92 Stud
has-aint0..*
sa thisAccount
serves 0..*
Bank Customer
(
R AN use
E LT se to
O B en
E N le lic SavingsAccount CheckingAccount
O R rab
O M sfe
A n
R -traBank
N on Customer
GE-customers
n : List<Customer>
-accounts : List<Account>
-firstName : String
«constructors»
-lastName : String
-Bank()
«methods» «constructors»
+addCustomer(f:String, l:String) +Customer(f:String, l:String)
+getNumOfCustomers():int «methods»
+getCustomer(index:int):Customer +addAccount(acct:Account)
+getNumOfAccounts():int
+getAccount(index:int):Account
Figure 9-1 Domain Model of the Bank Project with Details on the Bank and
Customer Classes
Preparation
There is no preparation for this exercise.
CUSTOMERS REPORT
================
0 2 11 ent
Tool Reference – Tool references used in this exercise:
9 2
Java Development: Java Classes: tModifying
n S t ud Classes: Compiling Java
Java
sai this
●
Classes (
Java Development:R u seModifying Java Classes: Executing Java
N Classes:
AJava ●
Programs LT
E e to
B en s
ForE
O
Nexercise, ic work in the BankPrj project in the
lyou
this
R rab l e
M Od:\labs\student\projects
f e directory.
A RO -trans
GEN noTask
n 1 – Modifying the Bank Class
In this task, you modify the Bank class source file in the com.mybank.domain
source package of the BankPrj project.
In this task, you modify the Customer class source file in the
com.mybank.domain source package of the BankPrj project.
M O fera
A ROTask
t r a n4s– Running the TestReport Program
G EN non-
In this task, you run the TestReport program. The output should be similar to
the following:
CUSTOMERS REPORT
================
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
G EN non
1. Add the two import statements to include the collections classes you will
use in the Bank class.
import java.util.List;
import java.util.ArrayList;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
CUSTOMERS REPORT
================
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N e lic
_____________________________________________________________
l
M OR fe_____________________________________________________________
rab
A RO -trans
G EN non
Lab 10
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
I/O Fundamentals
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 10-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Lab 11
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Objectives
Upon completion of this lab, you should be able to:
● Read a data file using the Scanner API s a
Use a generic collection to manage a one-to-many association ) h a
●
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 11-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Reading a Data File (Level 1)
Figure 11-1 shows the UML diagram for the DataSource class that you create
for the TestReport program.
TestReport
DataSource
s a
{from com.mybank.data}
CustomerReport
) h a
-dataFile : File
c o m
a il ฺ
«constructors»
g m i d eฺ
@ t Gu
+DataSource(dataFilePath:String)
«exception»
1 1
en
«methods»
02 {fromujava.io}
IOException
«send»
+loadData():void
9 2 d
a i n t
i s St
«read»
N (s e th
T R A
t o us
B EL nse
N O lice
O RE ble
test.dat ra
O M sfe
A t r an 11-1 The DataSource Class Loads Customer Data From a Flat File
R -Figure
G EN non
Code 11-1 shows an example of the format of the customer data file. The first
line contains an integer, which determines the number of customers in the data
file. A customer record contains the first name, last name, and the number of
accounts, separated by tab characters. Each account record contains a single-
character code that determines the type of account and also the data in that
record.
Code 11-2 shows an example of the format of the customer data file. This data
file contains four customer records. The first is for Jane Simms; Jane has two
bank accounts. The first account is a savings account, with an initial balance of
500.00 and an interest rate of 5 percent (0.05). The second account is a checking
account with an initial balance of 200.00 and overdraft protection of 400.00.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Jane Simms 2
S 500.00 0.05
C 200.00 400.00
Owen Bryant 1
s a
C 200.00 0.00
) h a
c o m
Tim Soley 2 ฺ
ail eฺ
S 1500.00 0.05
g m id
C 200.00 0.00 @ G u
0 2 11 ent
Maria Soley 1
n t 9 2
S t ud
S 150.00 0.05
( sai this
This exercise containsR Afollowing e
N ussections:
LT se to
the
E
“Task 1B– Creating n a data Directory”
●
O l i c e
N 2l–eCopying the Resource File”
R E“Task
rab3 – Creating the DataSource Class”
●
M O f“Taske
RO -trans “Task 4 – Deleting Unnecessary Classes”
●
A
EN non
●
Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
The class must satisfy the UML diagram in Figure 11-1 on page L11-2. The
loadData method must use Bank utility methods (addCustomer and
getCustomer) to populate the customers recorded in the data file. Furthermore,
s a
the Customer class has the addAccount method to add the accounts from the
data file. ) h a
c o m
ฺ
ail eฺ
g m id
Task 4 – Deleting Unnecessary Classes @ G u
0 2 11 ent
t 9
In this task, you delete the following Java
n S t udare no longer used:
2classes that
( sai this
TestReport
TestAccount RA
N use
E
TestAccount2 LT se to
O B en
TestBatch
E N le lic
TestBanking
M OR ferab
A ROTask
t r a n5s– Copying the TestReport Class
GEN non-
In this task, you copy the TestReport class from the
d:\labs\student\resources\11_fileio directory to the
com.mybank.test source package of the BankPrj project.
Tool Reference – Java Development: Java Application Projects: Setting the Main
Class
2. Set the main class of the BankPrj project to
com.mybank.test.TestReport. s a
) h a
o m
Tool Reference – Java Development: Java Application Projects: Running
c
Projects
ฺ
ail eฺ
m id following:
gsimilar touthe
@
11 ent
3. Run the BankPrj project. The output should be G
0 2
Reading data file: ..\data\test.dat
CUSTOMERS REPORTint9
2
S tud
(
================sa this
R AN use
Customer: Simms, Jane
E LT se to
B ebalance
Savings Account: current
O n is 500.0
N le
Checking Account: l
currenti c balance is 200.0
E
Customer: M
OR feOwen
rab
ns
Bryant,
A RO -traAccount:
Checking current balance is 200.0
E N n
G no
Customer: Soley, Tim
Savings Account: current balance is 1500.0
Checking Account: current balance is 200.0
E N Development:
l e
OR fClasses
rab
Java
●
M e
A RO -trans Java Development: Java Packages: Creating Java Packages
●
In this task, you delete the following Java classes that are no longer used:
TestReport
TestAccount
TestAccount2
TestBatch
TestBanking
Tool Reference – Java Development: Java Application Projects: Setting the Main
Class
2. Set the main class of the BankPrj project to
com.mybank.test.TestReport.
E N Development:
l e
OR fClasses
rab
Java
●
M e
A RO -trans Java Development: Java Packages: Creating Java Packages
●
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
5. Add a public method, loadData, that populates the Bank customer objects
and each customer’s account objects, shown as follows:
public void loadData() throws IOException {
// Data source variables
Scanner input = new Scanner(dataFile);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
// Domain variables
Customer customer;
int numOfCustomers = input.nextInt();
for ( int idx = 0; idx < numOfCustomers; idx++ ) {
// Create customer object
String firstName = input.next();
String lastName = input.next();
Bank.addCustomer(firstName, lastName);
customer = Bank.getCustomer(idx);
// Create customer accounts s a
int numOfAccounts = input.nextInt(); ) h a
while ( numOfAccounts-- > 0 ) {
c o m
// Create a specific type of account ฺ
ail eฺ
char accountType = input.next().charAt(0); g m id
@ G u
switch ( accountType ) {
0 2 11 ent
// Savings account
n t 9 2
S t ud
sai this
case ’S’: {
(
float initBalance = input.nextFloat();
AN use
float interestRate = input.nextFloat();
R
LT se to
customer.addAccount(new SavingsAccount(initBalance,
E
O B en interestRate));
N le lic
break;
E
M
}
OR ferab
// Checking account
A RO -trans
case ’C’: {
TestAccount
TestAccount2
TestBatch
TestBanking
Tool Reference – Java Development: Java Application Projects: Setting the Main
Class
2. Set the main class of the BankPrj project to
com.mybank.test.TestReport.
CUSTOMERS REPORT
================
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Lab 12
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Objectives
Upon completion of this lab, you should be able to:
● Create a GUI for the ChatRoom project s a
(Optional) Create a GUI for the Banking project ) h a
●
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 12-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Creating the ChatClient GUI Part 1 (Level 1)
Figure 12-1 shows the GUI design that you will attempt to achieve.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
OR ferComponent
The JTextField
M ab Quit Button Component
A RO -Figure
t r ans12-1 GUI Layout for the ChatClient Application
G EN non
As shown in Figure 12-1, there are four components in this GUI. The main
component is a JTextArea. The bottom component is a JTextField. There are
two Button components on the right.
Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
) h a
c o m
ฺ
For this exercise, you first create the ChatRoomPrj project in the
ail eฺ
d:\labs\student\projects directory, and then work in this project for all
g m id
@ u
the following exercises that are part of the ChatRoomPrj project.
G
0 2 11 ent
n t 9 2
S t ud
Task 1 – Creating the ChatClient
( sai this Class
R AN u se class in the source package of the
E LT implement
In this task, you create the to the GUI design in Figure 12-1 on page 12-2.
ChatClient
e
ChatRoomPrj
B enproject s
O lic steps:
N thelfollowing
E e
M OR ferab
Complete
R O ra1.ns Create the ChatRoomPrj Java Application Project with the following
A t
EN non-
characteristics:
G Project Name: ChatRoomPrj
Project Location: d:\labs\student\projects
Project Folder: d:\labs\student\projects\ChatRoomPrj
Set as Main Project: No
Create Main Class: No
2. Create the ChatClient class in the source package of the
ChatRoomPrj project with the following characteristics:
Class Name: ChatClient
Project: ChatRoomPrj
Location: Source Packages
Package: default package
The ChatClient class must implement the GUI design in Figure 12-1 on
page 12-2.
s a
Preparation
) h a
c o m
There is no preparation for this exercise. ฺ
ail eฺ
g m id
@ G u
11 ent
Tool Reference – Tool references used in this2exercise:
0
t 9 d Projects
2Projects:tuCreating
n
Java Development: Java Application S
sai Creating
●
( t h is Java Classes
●
N use
Java Development: Java Classes:
AJava
Java Development:
●
L R
T e tClasses:o Modifying Java Classes: Compiling Java
ClassesBE n s
O e
lic Java Classes: Modifying Java Classes: Executing Java
N Development:
E Java
●
l e
M OR fPrograms
e rab
A RO -trans Java Development: Java Classes: Terminating a Running Process
●
GEN non For this exercise, you first create the ChatRoomPrj project in the
d:\labs\student\projects directory, and then work in this project for all
the following exercises that are part of the ChatRoomPrj project.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
s a
Preparation
) h a
c o m
There is no preparation for this exercise. ฺ
ail eฺ
g m id
@ G u
Tool Reference – Tool references used in this exercise:
0 2 11 ent
Java Development: Java Application n t 9 2 Creating
Projects: S t ud Projects
●
i
saCreating s Classes
iJava
(
N use
Java Development: Java Classes:
● t h
R AClasses:
Java Development:
●
L T e to Modifying Java Classes: Compiling Java
Java
Classes BE n s
O e
lic Java Classes: Modifying Java Classes: Executing Java
NDevelopment:
E
Java
●
l e
M ORPrograms
e r a b
R sf Development: Java Classes: Terminating a Running Process
O ranJava●
A t
G EN non- For this exercise, you first create the ChatRoomPrj project in the
d:\labs\student\projects directory, and then work in this project for all
the following exercises that are part of the ChatRoomPrj project.
M O5.R fAdd
e raabpublic constructor that initializes each of the four GUI component
A RO -trans instance variables: The text area should be 10 rows tall and 50 columns
GEN non wide, the text field should be 50 columns wide, the send button should have
the word Send in the display, and the quit button should display a similar
label.
public ChatClient() {
output = new JTextArea(10,50);
input = new JTextField(50);
sendButton = new JButton("Send");
quitButton = new JButton("Quit");
}
6. Create a launchFrame method, which constructs the layout of the
components. Feel free to use nested panels and any layout managers that
will help you construct the layout in the GUI design shown above.
public void launchFrame() {
JFrame frame = new JFrame("Chat Room");
frame.add(output, BorderLayout.WEST);
frame.add(input, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
s a
}
) h a
7. o m
Create the main method. This method instantiates a new ChatClient
c
ฺ
ail eฺ
object and then calls the launchFrame method.
g m id
public static void main(String[] args) { @ G u
ChatClient c = new ChatClient();
0 2 11 ent
c.launchFrame();
n t 9 2
S t ud
}
( sai this
R AN use
Task 2 – Compiling E e to
LTthesChatClient Class
B
O lice n
N
E youbcompile
le the ChatClient class.
O Rtask,
In this
a
O M sfer
A RTask-t3ra–nRunning the ChatClient Program
N on
GE n
In this task, you run the ChatClient program. You should see the GUI shown in
Figure 12-1 on page 12-2. If your GUI does not look exactly like the figure, then
edit the code to tweak the design to match this figure.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
project. You use a complex layout to properly position several GUI components
in a frame.
Figure 12-2 shows the GUI design that you will attempt to achieve.
Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
) h a
c o m
For this exercise, you work in the BankPrj project in the
d:\labs\student\projects directory.
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
Task 1 – Copying the ATMClient
n t 9 2 Class
S t ud
( s ai this
AN use
Complete the following steps:
R
LT se to source package in the BankPrj project.
1. Create the com.mybank.gui
E
O B en
2. Copy
E N e l ic
the ATMClient.java template file from the
O r a bl
R d:\labs\student\resources\12_gui directory into the
A R -tran code provides the main method, which initializes a set of bank customers
GEN non and then launches the ATM GUI.
following characteristics:
● The Message text field must have a width of 75 characters (called columns
in the API documentation) and it must be read-only, meaning the user
cannot type into the field.
● The Data Entry text field must have a width of 10 characters and it must be
read-only. The user will use the key pad buttons to enter data which will be
displayed in the Data Entry field. This action will be coded in the next
module.
● The Output text area must have a width of 75 characters and a height (called
s a
rows in the API) of 10 characters and it must be read-only.
) h a
c o m
ฺ
ail screen.
Note – In this exercise, you will only be creating the layoutgofmthe ATM i d eฺ
1 @ totuser
You will not be creating the code to make the buttons respond G uactions; you
will do that in the next module.
1
02 uden
9 2
a i nt is St
N (s e th
Task 3 – Compiling Tthe R t o us
AATMClient Class
L
E nse
B
N
In this task, O l i
you compile cethe ATMClient class.
O RE rable
O M sfe
A R -t4ra–nRunning the ATMClient Program
Task
G EN non
Complete the following steps:
1. Set the main class of the BankPrj project to
com.mybank.gui.ATMClient.
2. Run the BankPrj project. You should see the GUI shown in Figure 12-2
on page 12-12.
Hints
These hints might help you to solve this exercise.
● Use the setEnabled(false) method to make a component read-only.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications
●
R AN use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR_____________________________________________________________
e r a b
R O ransf
A t
G EN non-
Lab 13
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Objectives
Upon completion of this lab, you should be able to:
● Create the GUI event handlers for the ChatRoom project s a
(Optional) Create the GUI event handlers for the Banking project ) h a
●
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 13-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Creating the ChatClient GUI Part 2 (Level 1)
A RO -trans
G EN non Tool Reference – Tool references used in this exercise:
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs
to create the event listeners listed in ‘‘Exercise 1: Creating the ChatClient GUI
Part 2 (Level 1)’’ on page L13-2.
s a
Preparation ) h a
c o m
ฺ
ail eฺ
There is no preparation for this exercise.
g m id
@ G u
0
Tool Reference – Tool references used in this exercise: 2 11 ent
n t 9 2
S t ud
●
s i
Java Development: Java Classes:aModifying i sJava Classes: Compiling Java
( t h
AN use
Classes
R to Modifying Java Classes: Executing Java
LTJavasClasses:
Java Development:
●
Programs BE n e
O
N le l i c e
R Eexercise,
M O ferab you work in the ChatRoomPrj
For this project in the
RO -trans
d:\labs\student\projects directory.
A
G EN non
Task 1 – Modifying the ChatClient Class
In this task, you modify the ChatClient class in the source package of the
ChatRoomPrj project. This class must implement event listeners listed in the
introduction to ‘‘Exercise 1: Creating the ChatClient GUI Part 2 (Level 1)’’ on
page L13-2.
s a
Task 2 – Compiling the ChatClient Class ) h a
c o m
ฺ
ail eฺ
In this task, you compile the ChatClient class.
g m id
@ G u
0 2 11 ent
Task 3 – Running the ChatClient
n t 9 S t ud
2 Program
( sai this
In this task, you run the A N useprogram. Test the behavior of the event
ChatClient
R
LT se to
listeners you added.
E
B en
O
N le lic
E
M OR ferab
A RO -trans
GEN non
Preparation s a
) h a
c o m
There is no preparation for this exercise. ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
Tool Reference – Tool references used in this exercise:
Java Development: Java Classes:t9
n
2
S
Modifying t ud Classes: Compiling Java
Java
sai this
●
Classes (
R
Java Development:
●
N Classes:
AJava u seModifying Java Classes: Executing Java
Programs LT
E e to
B en s
O
N exercise,
ForEthis
c work in the ChatRoomPrj project in the
liyou
R rab l e
M Od:\labs\student\projects
f e directory.
A RO -trans
G EN noTask
n 1 – Modifying the ChatClient Class
In this task, you modify the ChatClient class in the source package of the
ChatRoomPrj project. This class must implement event listeners listed in the
introduction to ‘‘Exercise 1: Creating the ChatClient GUI Part 2 (Level 1)’’ on
page L13-2.
1. Import the java.awt.event package.
import java.awt.event.*;
public class ChatClient {
// your code here
}
2. Add the ActionListener for the Send button. This listener must extract
the text from the text field and display that text in the text area. Use an inner
class for this listener.
private void launchFrame() {
O R
frame.addWindowListener(new
a b CloseHandler());
Mcodesfer
// more
O
}
A R -tran
GENprivate
nonclass CloseHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
5. Add the ActionListener for the Quit button. This listener must exit the
ChatClient program. Use an anonymous inner class for this listener.
private void launchFrame() {
// GUI component initalization code here
quitButton.addActionListener(new ActionListener() {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
M O3.R fThe
e
b selects one of the Action buttons.
rauser
A RO -trans Ifthetheamount.
action is either deposit or withdraw, then the user is prompted to enter
EN non
The user can then enter the amount by clicking the key pad
G buttons which (again) places digits in the Data Entry text field. When the
ENTER button is selected, the program executes the action with the amount
entered in the Data Entry text field. Finally, the result of the operation must
be displayed in the Output text area. At the end of the operation, the GUI
should begin again at the top of the ATM operation cycle.
Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
Task 1 – Modifying the ATMClient Class ) h a
c o m
ฺ
ail of theeฺ
In this task, you modify the ATMClient class in the source package
g m toid
@
BankPrj project. This class must rely on necessary event listeners
G u
implemented the required behavior.
0 2 11 ent
n t 9 2
S t ud
Task 2 – Compiling the ATMClient ( sai thiClasss
R AN use
T e to class.
In this task, you B EL thensATMClient
compile
N O lice
R E ble
O
TaskM3 – Running
f e ra the BankPrj Project
O
R -tran s
A
G EN non In this task, you run the BankPrj project.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications
●
R AN use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR_____________________________________________________________
e r a b
R O ransf
A t
G EN non-
Lab 14
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
GUI-Based Applications
Objectives
Upon completion of this lab, you should be able to add menus to the GUI for the
ChatRoom project.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 14-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise: Creating the ChatClient GUI, Part 3 (Level 1)
Figure 14-1 shows the GUI design that you will attempt to achieve.
s a
) h a
c o m
ฺ
ail eฺ
g m id
Figure 14-1 GUI Layout for the ChatClient Application @ G u
0 2 11 ent
n t 9 2
S t ud
( s ai this
You need to add four features to the existing GUI:
Add the user name JComboBox
●
A s e under the Send and Quit
N ucomponent
R enables
Tyou
buttons. This component
L t o you to select a name that is posted with
B that e
E ns You must alter the Send button and
every chat line enter.
O listeners
JTextField
N l i ce to write the username to the output JTextArea
E blAdd
Rcomponent. e several user name options including your full name and a
O
M few f r a
enicknames, such as 1337dud3 or Java Geek.
O s
R -tranPut the JTextArea component into a JScrollPane component. Add a
A ●
G EN non vertical scroll bar but no horizontal scroll bar. Auto scroll the text to the
bottom of the JTextArea as the user adds text to the text chat window.
● Add the File menu. This menu must include a Quit menu item that
terminates the program when selected.
● Add the Help menu. This menu must include an About menu item that pops
up a simple dialog box, which displays a comment about the program and
about you, the developer.
Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
M OR ferab
A ROTask
t r a n3s– Running the ChatClient Program
GEN non-
In this task, you run the ChatClient program. You should see the GUI shown in
Figure 14-1 on page L14-2. If your GUI does not look exactly like the figure,
then edit the code to tweak the design to match this figure.
menus.
Preparation s a
) h a
c o m
There is no preparation for this exercise. ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
Tool Reference – Tool references used in this exercise:
9
Java Development: Java Classes: Modifying
●
t d Compiling Java
2 JavatuClasses:
n S
Classes
( sai this
Java Development: Java
●
R se
N uModifying
AClasses: Java Classes: Executing Java
Programs
E LT se to
O B en
N lyou
For this exercise, c in the ChatRoomPrj project in the
liwork
E e
M OR ferab
d:\labs\student\projects directory.
A RO -trans
G EN Task
non 1 – Modifying the ChatClient Class
In this task, you modify the ChatClient class in the source package of the
ChatRoomPrj project. This class must implement the GUI design in
Figure 14-1 on page L14-2.
menus.
Preparation s a
) h a
c o m
There is no preparation for this exercise. ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
Tool Reference – Tool references used in this exercise:
9
Java Development: Java Classes: Modifying
●
t d Compiling Java
2 JavatuClasses:
n S
Classes
( sai this
Java Development: Java
●
R se
N uModifying
AClasses: Java Classes: Executing Java
Programs
E LT se to
O B en
N lyou
For this exercise, c in the ChatRoomPrj project in the
liwork
E e
M OR ferab
d:\labs\student\projects directory.
A RO -trans
G EN Task
non 1 – Modifying the ChatClient Class
In this task, you modify the ChatClient class in the source package of the
ChatRoomPrj project. This class must implement the GUI design in
Figure 14-1 on page L14-2.
usernames.addItem("1337dud3");
usernames.addItem("Java Geek");
}
// existing code here
}
2. Add the aboutDialog instance variable of type
javax.swing.JDialog to the ChatClient class.
3. Add the frame instance variable of type javax.swing.JFrame to the
ChatClient class.
s a
)
4. Modify the declaration and initialization of the frame variable in the h a
launchFrame method to the following: o m
a ilฺc ฺ
frame = new JFrame("Chat Room");
g m ide
@
5. Enhance the listeners for the Send button and1JTextFieldG uto write the
1 t
9 2 02 uden
user name to the output JTextArea component.
i nt is St {
private class SendHandler implements ActionListener
a
public void actionPerformed(ActionEvent
N (s e te)h {
String text = input.getText();
T R A
t o us
L se
output.append(usernames.getSelectedItem()
E + ": " + text + "\n");
input.setText("");
O B en
}
E N le lic
}
M OR ferab
A RO -tra6.ns Add a JScrollPane component to the project and add the JTextArea
7. Auto scroll the text to the bottom of the JTextArea as the user adds text to
the text chat window.
// Add to SendHandler to enable AutoScroll
output.setCaretPosition(output.getDocument().getLength()-1);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
8. Add the File menu. This menu must include a Quit menu item that
terminates the program when selected.
public void launchFrame() {
// existing code here
// Create menu bar and File menu
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem quitMenuItem = new JMenuItem("Quit");
quitMenuItem.addActionListener(new ActionListener() {
s a
public void actionPerformed(ActionEvent e) {
) h a
System.exit(0);
c o m
} ฺ
ail eฺ
}); g m id
@ G u
file.add(quitMenuItem);
mb.add(file); 0 2 11 ent
frame.setJMenuBar(mb);
n t 9 2
S t ud
// existing code here
( sai this
}
R AN use
9. Add the Help menu.
E LT Thissemenuto must include an About menu item that pops
up a simpleBdialog e n that displays a comment about the program and
box,
O l i c
R ENyou,bthe
about
l e developer.
O fera {
public void launchFrame()
M
A R//O Add
// existing
t r a ns bar
menu code here
aboutDialog.setVisible(true);
}
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications
●
R AN use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR_____________________________________________________________
e r a b
R O ransf
A t
G EN non-
Lab 15
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Threads
Objectives
Upon completion of this lab, you should be able to create a simple multithreaded
application.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 15-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise: Using Multithreaded Programming (Level 1)
The purpose of this lab is to create three threads and run them at the same time.
While they are running, they print out their names to the standard output stream.
By observing what is printed, you can observe how the threads run and in what
order.
G EN non Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs
d:\labs\student\exercises\15_threads directory.
2. Create a PrintMe class in the source package of the ThreadProject
with the following characteristics:
Class Name: PrintMe
Project: ThreadProject
Location: Source Packages
Package: default package
s a
Add code so that PrintMe implements Runnable.
) h a
c o m
a ฺ
The class implements the Runnable interface. The run methodil of the class
ฺ and
performs the following actions 10 times: Print the name g ofm i d
the current ethread
then sleep for 2 seconds.
1 1 @ t Gu
9 2 02 uden
Task 2 – Creating the TestThreeThreads a i nt is St Class
( s t h
R AN use
In this task, you create
E to
LT a TestThreeThreads
e class in the source package of the
B n s
O lice
ThreadProject
N
with the following characteristics:
O REClass a b le TestThreeThreads
Name:
O er ThreadProject
M sfProject:
A R -tran Location: Source Packages
GEN non
Package: default package
The main method of the class creates three threads using the PrintMe runnable
class. Give each thread a unique name using the setName method. Start each
thread.
T3 - Moe
T2 - Curly
T1 - Larry
T1 - Larry
T3 - Moe
T2 - Curly
T1 - Larry
T3 - Moe
T2 - Curly
T1 - Larry
s a
T3 - Moe
) h a
T2 - Curly
c o m
T1 - Larry ฺ
ail eฺ
T3 - Moe g m id
@ G u
T2
T1
-
-
Curly
Larry 0 2 11 ent
T3 - Moe n t 9 2
S t ud
T2 - (
Curly sai this
T1 - AN use
Larry
R
T3
E
-
LT se to
Moe
T2
O B en
- Curly
E N le lic
T1 - Larry
OR ferab
T3 - Moe
M T2 - Curly
A RO -trans T1 - Larry
G EN non T3
T2
-
-
Moe
Curly
T1 - Larry
T3 - Moe
T2 - Curly
Run this program several times. You might see different results for each
execution.
s a
Preparation
) h a
c o m
There is no preparation required for this exercise. ฺ
ail eฺ
g m id
@ G u
11 ent
Tool Reference – Tool references used in this2exercise:
0
t 9 d Projects
2Projects:tuOpening
n
Java Development: Java Application S
sai Creating
●
( t h is Java Classes
●
N use
Java Development: Java Classes:
AJava
Java Development:
●
L R o
T e tClasses: Modifying Java Classes: Compiling Java
ClassesBE n s
O e
lic Java Classes: Modifying Java Classes: Executing Java
N Development:
EJava
●
l e
M OR fPrograms
e rab
A nsthis exercise, you work in the ThreadProject project in the
RO -traFor
GEN non d:\labs\student\exercises\15_threads directory.
d:\labs\student\exercises\15_threads directory.
2. Create the PrintMe class with the following characteristics:
Class Name: PrintMe
Project: ThreadProject
Location: Source Packages
Package: default package
Add code so that PrintMe implements Runnable. a
3. Create the run method to loop the following 10 times: Print the name of)the has
current thread and then sleep for 2 seconds.
c o m
ฺ
ail eฺ
g m id
@ G u
Task 2 – Creating the TestThreeThreads
0 2 11 Class
e n t
n t 9 2
S t ud
ai thclass
In this task, you create a TestThreeThreads
( s is in the source package of the
ThreadProject project. N
R A u se
E
Complete the following LTsteps:se to
O B en
E
1. Create
l e lic
N the TestThreeThreads class with the following characteristics:
R
O Class b
ra TestThreeThreads
M f eName:
s ThreadProject
A RO -tranProject:
N on
GE n Location: Source Packages
Package: default package
2. Create the main method.
a. Create three Thread objects and pass an instance of the PrintMe
class to each constructor.
b. Give each thread a unique name using the setName method.
c. Start each thread.
on page L15-4.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
s a
Preparation
) h a
c o m
There is no preparation required for this exercise. ฺ
ail eฺ
g m id
@ G u
Tool Reference – Tool references used in this exercise:
0 2 11 ent
Java Development: Java Application n t 9 2 Opening
Projects: S t ud Projects
●
i
saCreating s Classes
iJava
(
N use
Java Development: Java Classes:
● t h
R AClasses:
Java Development:
●
L T e to Modifying Java Classes: Compiling Java
Java
Classes BE n s
O e
lic Java Classes: Modifying Java Classes: Executing Java
NDevelopment:
E
Java
●
l e
M ORPrograms
e r a b
R O ransf
A t this exercise, you work in the ThreadProject project in the
EN non-d:\labs\student\exercises\15_threads directory.
For
G
Task 1 – Creating the PrintMe Class
Complete the following steps:
1. Open the ThreadProject project in the
d:\labs\student\exercises\15_threads directory.
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Lab 16
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Networking
Objectives
Upon completion of this lab, you should be able to build a GUI client to connect
to a remote server by using Transmission Control Protocol/Internet Protocol
s a
(TCP/IP).
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 16-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise: Creating a Socket Client (Level 1)
The chat server is responsible for sending messages received from one client to
all connected clients (including the original sender). Figure 16-1 shows an
architecture diagram of several clients attached to the single chat server. In this
scenario, Simon types This is cool! into the message JTextField
component. Simon’s client then prepends his name Simon: onto the message and
sends it to the server over the output stream (Step 1). The server receives the
message and then forwards the message to each attached client (Steps 2–4); the
order of the forwarded messages is unimportant.
s a
) h a
client: PC/Win95
c o m
1 “Simon: This is cool!”
ฺ
ail eฺ
g m id
@ G u
11 ent
ChatClient
3 “Simon: This is cool!”
0 2
2 ud
Simon
n t 9
server
S t
( sai this
R AN use
client: SparcSol9
E LT se to ChatServer
B e n
E
ChatClientNO le2 l“Simon:
ic This is cool!”
Debbie
M OR ferab
A RO -trans
N on
GE n
client: PC/WinXP
Figure 16-1 The Chat Server Sends Any Message to All Attached Clients
The chat client (your application) must be modified to perform two behaviors: It
must send the user’s messages to the server, and it must display the messages it
receives from the server to the output JTextArea component. Figure 16-2 shows
a detailed design for the elements of the ChatClient application. You will add
the doConnect method to the ChatClient class to initiate the socket
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
«interface»
Runnable
The RemoteReader is a nested class
that reads messages from the serverIn
instance variable in the ChatClient. +run():void
RemoteReader server
ChatClient
s a
-serverIn : BufferedReader
) h a
-serverOut : PrintWriter
c o m ChatServer
«methods» ฺ
ail eฺ
-doConnect():void
g m id
@ G u
11 ent
SendHandler
0 2
n 9 2
«methods»
t S t ud
sai this
+actionPerformed(e:ActionEvent):void
(
R AN use
E LT se to
The SendHandler is a nested class
that sends messages to the serverOut
O BDetailed
cenDesign of the ChatClient Application
instance variable in the ChatClient.
FigureN16-2 l i
O RE rable
O e contains the following sections:
M Thissfexercise
n
AR n-tra “Task 1 – Modifying the ChatClient Class”
E N
no
●
G ● “Task 2 – Compiling the ChatClient Class”
● “Task 3 – Running the ChatRoomPrj Project”
Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
For this exercise, you work in the ChatRoomPrj project in the projects
s a
directory.
) h a
c o m
il ฺ
Task 1 – Modifying the ChatClient Class gma ideฺ
1 1 @ t Gu
In this task, you modify the ChatClient class2 u enpackage of the
0in2the source
d
9 t
nt is Scommunication
ChatRoomPrj project. Implement the iclient-server based on the
s a h
N ( uL16-3.
detailed design in Figure 16-2 on page
A s et
L TR e to
Task 2 – CompilingO BE the e n sChatClient Class
E N le lic
InO
R ryou a bcompile the ChatClient class.
M e
this task,
O ransf
R
A n-t
G EN Task
no 3 – Running the ChatRoomPrj Project
Complete the following steps:
1. Set the main class of the ChatRoomPrj project to ChatClient.
will display a message from the server with a secret passphrase. When you
send that passphrase to the server, you then trigger an event on the server
that plays a gong. This event will indicate that your application is working
correctly.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Preparation
s a
) h a
There is no preparation for this exercise.
c o m
ฺ
ail eฺ
Tool Reference – Tool references used in this exercise g m id
@ G u
Java Development: Java Classes: Modifying2Java
●
0 11Classes:
e n tCompiling Java
Classes
n t 9 2
S t ud
( saithe Main
Java Application Projects: Setting
●
t h isClass
N useProjects: Setting VM Options
AApplication
● R
Java Development: Java
to
LTJavasApplication
E
B en
Java Development:
● e Projects: Running Projects
O
N le lic
For thisE
R rab you work in the ChatRoomPrj project in the projects
exercise,
O fe
Mdirectory.
O n s
N AR n-tra
G E no Task 1 – Modifying the ChatClient Class
In this task, you modify the ChatClient class in the source package of the
ChatRoomPrj project. Implement the client-server communication based on the
detailed design in Figure 16-2 on page L16-3.
3. Add the doConnect method to initiate the TCP/IP socket connection to the
server. Ask your instructor for the hostname (or IP address) and port
number of the server application.
a. Initialize server IP and port information.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
will display a message from the server with a secret passphrase. When you
send that passphrase to the server, you then trigger an event on the server
that plays a gong. This event will indicate that your application is working
correctly.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
Preparation
s a
) h a
There is no preparation for this exercise.
c o m
ฺ
ail eฺ
Tool Reference – Tool references used in this exercise: gm id
@ G u
●Java Development: Java Classes: Modifying
0 2 11Java eClasses:
n t Compiling Java
Classes
n t 9 2
S t ud
●Java Application Projects:(s ai the
Setting t h is Class
Main
R
Java Development: u se Projects: Setting VM Options
N Application
AJava
LT sJava to
●
● E e
B en Application Projects: Running Projects
Java Development:
O
N le lic
For E
R rexercise,
this b you work in the ChatRoomPrj project in the projects
O fe
M directory. a
O n s
N AR n-tra
GE no Task 1 – Modifying the ChatClient Class
In this task, you modify the ChatClient class in the source package of the
ChatRoomPrj project. Implement the client-server communication based on the
detailed design in Figure 16-2 on page L16-3.
2. Add instance variables to hold the input and output streams for the socket
connection. You might need additional instance variables, depending on
your implementation.
public class ChatClient {
// existing code here
private Socket connection = null;
private BufferedReader serverIn = null;
private PrintStream serverOut = null;
s a
}
// existing code here
) h a
c o m
3. ฺ
ail eฺ
Add the doConnect method to initiate the TCP/IP socket connection to the
g m id
server. Ask your instructor for the hostname (or IP address) and port
@ G u
number of the server application.
0 2 11 ent
private void doConnect() {
n t 9 2
S t ud
a.
( s i this
Initialize server IP and portainformation.
// Initialize server IP and port
R u se
ANinformation
L T e to
String serverIP = System.getProperty("serverIP", "127.0.0.1");
O BE ens
String serverPort = System.getProperty("serverPort", "2000");
E N le lic
M OR– You
Note e r a b have hard coded the server IP address and port number in the
R O Socket
a n sfconstructor call below. The code for this step demonstrates how to make
could
java -DserverIP=myhost.example.com
-DserverPort=47 ChatClient
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
n t 9 2
S t ud
3. Run the ChatRoomPrj project.
( sai this
ANfrom
If your program connects e successfully, then the output text area
to thesserver
u
will display a T
L R
message t o server with a secret passphrase. When you
the
BE
send that
n
pass phrase e
s to the server, you then trigger an event on the server
N
thatOplays a l ic e
gong. This event will indicate that your application is working
E
R correctly.bl e
O
M sfe r a
O n luck and have fun!
R -traGood
A
GEN non
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications
●
R AN use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR_____________________________________________________________
e r a b
R O ransf
A t
G EN non-