Beruflich Dokumente
Kultur Dokumente
Table of Contents
About This Workbook .......................................................Preface-xvii
Lab Goals ............................................................................... Preface-xvii
Performing the Exercises ....................................................... Preface-xviii
Conventions ............................................................................. Preface-xix
Typographical Conventions ............................................ Preface-xix
Additional Conventions ................................................... Preface-xx
Getting Started..................................................................................1-1
Objectives ............................................................................................ 1-1
Exercise 1: Exploring Java Program Errors...................................... 1-2
Preparation ................................................................................... 1-2
Task Correcting Compilation and Runtime Errors ................... 1-2
Exercise 2: Creating a Test Program (Level 1)..................................... 1-4
Preparation ................................................................................... 1-4
Task 1 Copying the Account Class ......................................... 1-5
Task 2 Creating the TestAccount Class ................................ 1-5
Task 3 Compiling the TestAccount Class............................. 1-6
Task 4 Running the TestAccount Program ........................... 1-6
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
vi
vii
viii
xi
xii
xiii
xiv
xv
xvi
Lab Preface
Write a rich Java technology program using the graphical user interface
(GUI) application programming interfaces (APIs), input/output (I/O) APIs,
and networking APIs
This workbook presents the lab exercises for each module of the Student Guide.
Lab Preface-xvii
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.
Also, several modules have advanced labs. These labs are optional. These labs are
intended for more advanced students who complete the primary labs easily.
Lab Preface-xviii
Conventions
Conventions
The following conventions are used in this course to represent various training
elements and alternative learning resources.
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.
Courier is also used to indicate programming constructs, such as class names,
methods, and keywords; for example:
The getServletInfo method is used to get author information.
The java.awt.Dialog class contains Dialog constructor.
Courier bold is used for characters and numbers that you type; for example:
To list the files in this directory, type:
# dir
Courier bold is also used for each line of programming code that is referenced
in a textual description; for example:
1 import java.io.*;
2 import javax.servlet.*;
3 import javax.servlet.http.*;
Notice the javax.servlet interface is imported to allow access to its life cycle
methods (Line 2).
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.
Courier italic bold is used to represent variables whose values are to be
entered by the student as part of an activity; for example:
Type chmod a+rwx filename to grant read, write, and execute rights for
filename to world, group, and users.
Lab Preface-xix
Conventions
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 Users Guide.
These are called class options.
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
arguments.
Line breaks occur only where there are separations (commas), conjunctions
(operators), or white space in the code. Broken code is indented four spaces
under the starting code.
Lab Preface-xx
Lab 1
Getting Started
Objectives
Upon completion of this lab, you should be able to:
Lab 1-1
Preparation
No preparation is needed for this exercise.
Tool Reference Tool references used in this exercise:
Lab 1-2
3.
If a compilation error occurs, identify the source of the error and fix it.
4.
6.
If a runtime error occurs, identify the source of the error and fix it.
7.
Getting Started
Lab 1-3
Figure 1-1
Preparation
No preparation is needed for this exercise.
Tool Reference Tool references used in this exercise:
Lab 1-4
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.
Getting Started
Lab 1-5
Lab 1-6
Preparation
No preparation is needed for this exercise.
Tool Reference Tool references used in this exercise:
Getting Started
Lab 1-7
Lab 1-8
2.
3.
5.
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.
Getting Started
Lab 1-9
Preparation
No preparation is needed for this exercise.
Tool Reference Tool references used in this exercise:
Lab 1-10
2.
Lab 1-11
acct.deposit(50.0);
5.
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.
Lab 1-12
Exercise Summary
Exercise Summary
!
?
Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Interpretations
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Conclusions
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Applications
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Getting Started
Lab 1-13
Lab 2
Object-Oriented Programming
Objectives
Upon completion of this lab, you should be able to:
Lab 2-1
Preparation
You must have a web browser window open.
Open the Java Platform, Standard Edition 6 API Specification Web page
in the browser.
Lab 2-2
2.
Select the java.text package in the package list in the upper-left corner
panel of the API frameset.
3.
Select the NumberFormat class in the class list in the lower-left panel.
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.
Figure 2-1
There is only one business rule that applies to the Account class: The balance of
the bank account must never go below zero. In this exercise, you will discover
that the Account class cannot ensure this business rule.
This exercise contains the following sections:
Object-Oriented Programming
Lab 2-3
Preparation
No preparation is needed for this exercise.
Tool Reference Tool references used in this exercise:
Lab 2-4
Object-Oriented Programming
Lab 2-5
Preparation
No preparation is needed for this exercise.
Tool Reference Tool references used in this exercise:
Lab 2-6
2.
3.
Add a constructor that sets the balance instance variable to the initial
balance argument passed to the constructor.
2.
b.
c.
Use the subtraction operator to subtract 150 from the account objects
balance.
Object-Oriented Programming
Lab 2-7
Lab 2-8
Preparation
No preparation is needed for this exercise.
Tool Reference Tool references used in this exercise:
Object-Oriented Programming
Lab 2-9
2.
Add a constructor that sets the balance to the initial balance argument
passed to the constructor.
Lab 2-10
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.
Use the subtraction operator to subtract 150 from the account objects
balance.
Object-Oriented Programming
Lab 2-11
Figure 2-2
Remember, there is still one business rule that must be maintained: The balance
of the bank account must never go below zero. This business rule should be
enforced in the withdraw method.
This exercise contains the following sections:
Preparation
There is no preparation for this exercise.
Lab 2-12
Object-Oriented Programming
Lab 2-13
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
Lab 2-14
1.
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.
2.
Object-Oriented Programming
Lab 2-15
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
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.
Lab 2-16
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.
acct.deposit(47.0);
2.
acct.withdraw(150.0);
Object-Oriented Programming
Lab 2-17
com.mybank
test
domain
TestAccount
Account
-balance : double
+main(args:String[])
constructors
+Account(initBalance:double)
methods
+getBalance():double
+deposit(amt:double):void
+withdraw(amt:double):void
Figure 2-3
Lab 2-18
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
2.
Add the following package statement at the top of the Account class:
package com.mybank.domain;
Object-Oriented Programming
Lab 2-19
2.
3.
Add the following import statement under the package statement in the
TestAccount class if has not already been added by your editor:
import com.mybank.domain.Account;
Lab 2-20
Exercise Summary
Exercise Summary
!
?
Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Interpretations
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Conclusions
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Applications
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Object-Oriented Programming
Lab 2-21
Lab 3
Lab 3-1
Figure 3-1
Preparation
No preparation is needed for this exercise.
Tool Reference Tool references used in this exercise:
Lab 3-2
2.
3.
Create a main method, and complete the following steps in the main
method:
a.
Declare two variables of type MyPoint and called start and end.
Assign both of these variables a new MyPoint object.
b.
Set the x and y values of start to 10. Set the x value of end to 20
and the y value to 30.
c.
d.
To make sure that you are using the MyPoint class correctly, you
might want to compile and run TestMyPoint now (see Task 2
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.
f.
g.
Assign new values to the x (such as 47) and y (such as 50) members
of the variable stray.
h.
Lab 3-3
Lab 3-4
com.mybank.domain
has-a
Customer
-firstName : String
-lastName : String
-account : Account
Account
-balance : double
constructors
+Account(initBalance:double)
constructors
+Customer(f:String, l:String)
methods
+getFirstName():String
+getLastName():String
+getAccount():Account
+setAccount(acct:Account):void
Figure 3-2
methods
+getBalance():double
+deposit(amt:double):void
+withdraw(amt:double):void
Lab 3-5
Preparation
No preparation is needed for this exercise.
Tool Reference Tool references used in this exercise:
Lab 3-6
Lab 3-7
Preparation
No preparation is needed for this exercise.
Tool Reference Tool references used in this exercise:
Lab 3-8
2.
3.
4.
Declare two public accessors for the object instance variables; the methods
getFirstName and getLastName return the appropriate instance
variable.
5.
6.
Lab 3-9
Lab 3-10
Preparation
No preparation is needed for this exercise.
Tool Reference Tool references used in this exercise:
Lab 3-11
2.
Declare two public accessors for the object instance variables; the methods
getFirstName and getLastName return the appropriate instance
variable.
Lab 3-12
Lab 3-13
Exercise Summary
Exercise Summary
!
?
Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Interpretations
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Conclusions
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Applications
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Lab 3-14
Lab 4
Lab 4-1
1
2
3 foo
4
5 bar
6 foo
7 baz
8
9 foo
10 bar
11
12 foo
13
14 baz
15 foo bar
16
and so on.
This exercise contains the following sections:
Lab 4-2
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
2.
3.
4.
b.
Lab 4-3
Hints
These hints might help you to solve this exercise:
Lab 4-4
com.mybank.domain
has-a
Customer
-firstName : String
-lastName : String
-account : Account
Account
-balance : double
constructors
+Account(initBalance:double)
constructors
+Customer(f:String, l:String)
methods
+getFirstName():String
+getLastName():String
+getAccount():Account
+setAccount(acct:Account):void
Figure 4-1
methods
+getBalance():double
+deposit(amt:double):boolean
+withdraw(amt:double):boolean
Preparation
There is no preparation required for this exercise.
Lab 4-5
Lab 4-6
Lab 4-7
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
Lab 4-8
Modify the deposit method. Because an account has no upper limit, this
method must always return true to indicate it always succeeds.
2.
Lab 4-9
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
Lab 4-10
Modify the deposit method. Because an account has no upper limit, this
method must always return true to indicate it always succeeds.
Lab 4-11
Lab 4-12
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.
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
Lab 4-13
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.
Lab 4-14
Hints
These hints might help you to solve this exercise.
The length method returns the number of characters in the string; for
example, "cat".length() is 3.
Lab 4-15
Exercise Summary
Exercise Summary
!
?
Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Interpretations
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Conclusions
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Applications
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Lab 4-16
Lab 5
Arrays
Objectives
Upon completion of this lab, you should be able to:
Lab 5-1
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
Lab 5-2
3.
Add a main method. In the main method, declare two variables called
array1 and array2. They should be of type int[] (array of int).
4.
Using the curly-brace notation, {}, initialize array1 to the first eight prime
numbers.
5.
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.
!
?
Arrays
Lab 5-3
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
Lab 5-4
3.
Add a main method. In the main method, declare two variables called
array1 and array2. They should be of type int[] (array of int).
4.
Using the curly-brace notation, {}, initialize array1 to the first eight prime
numbers: 2, 3, 5, 7, 11, 13, 17, and 19.
5.
Display the contents of array1. You might want to use the printArray
method (see Hint on page L5-6) to display these integer arrays.
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.
!
?
Arrays
Lab 5-5
Hint
The printArray support method might help you to solve this exercise, as
follows:
public static void printArray(int[] array) {
System.out.print(<);
for ( int i = 0; i < array.length; i++ ) {
// print an element
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(>);
}
Note You can also use the java.util.Arrays.toString method to
generate a string representation of an array. For example:
System.out.println(Arrays.toString(array1));
Lab 5-6
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
Arrays
Lab 5-7
3.
Add a main method. In the main() method, declare two variables called
array1 and array2. They should be of type int[] (array of int).
Using the curly-brace notation, {}, initialize array1 to the first eight prime
numbers: 2, 3, 5, 7, 11, 13, 17, and 19.
Display the contents of array1. You might want to use the printArray
method (see Hint on page L5-6) to display these integer arrays.
System.out.print("array1 is ");
printArray(array1);
System.out.println();
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).
array2 = 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();
Lab 5-8
Arrays
Lab 5-9
com.mybank.domain
Bank
-customers : Customer[]
-numberOfCustomers : int
constructors
+Bank()
methods
+addCustomer(f:String, l:String)
+getNumOfCustomers():int
+getCustomer(index:int):Customer
serves
0..*
Figure 5-1
Customer
has-a
Account
Lab 5-10
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
For this exercise, you work in the BankPrj project in the projects directory.
Arrays
Lab 5-11
Lab 5-12
[1]
[2]
[3]
[4]
is
is
is
is
Simms, Jane
Bryant, Owen
Soley, Tim
Soley, Maria
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
Arrays
Lab 5-13
2.
Add two instance variables to the Bank class: customers (an array of
Customer objects) and numberOfCustomers (an integer that keeps track
of the next customers array index).
3.
Add a public constructor that initializes the customers array with some
appropriate maximum size (at least bigger than five).
4.
5.
6.
Lab 5-14
Arrays
[1]
[2]
[3]
[4]
is
is
is
is
Simms, Jane
Bryant, Owen
Soley, Tim
Soley, Maria
Lab 5-15
Preparation
There is no preparation for this exercise.
Tool Reference Tool References used in this exercise:
Lab 5-16
package com.mybank.domain;
public class Bank {
// insert code here
}
2.
Add two instance variables to the Bank class: customers (an array of
Customer objects) and numberOfCustomers (an integer that keeps track
of the next customers array index).
Add a public constructor that initializes the customers array with some
appropriate maximum size (at least bigger than five).
public Bank() {
customers = new Customer[10];
numberOfCustomers = 0;
}
4.
Arrays
Lab 5-17
6.
[1]
[2]
[3]
[4]
is
is
is
is
Simms, Jane
Bryant, Owen
Soley, Tim
Soley, Maria
Exercise Summary
Exercise Summary
!
?
Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Interpretations
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Conclusions
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Applications
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Arrays
Lab 5-19
Exercise Summary
Lab 5-20
Lab 6
Class Design
Objectives
Upon completion of this lab, you should be able to:
Lab 6-1
Figure 6-1 shows the UML class diagram for a design that satisfies the business
rules described above.
com.mybank.domain
Account
#balance : double
constructors
#Account(initBalance:double)
methods
+getBalance():double
+deposit(amt:double):boolean
+withdraw(amt:double):boolean
SavingsAccount
CheckingAccount
-interestRate : double
-overdraftAmount : double
constructors
+SavingsAccount(initBalance:double,
interestRate:double)
constructors
+CheckingAccount(initBalance:double,
overdraft:double)
+CheckingAccount(initBalance:double)
methods
+withdraw(amt:double):boolean
Figure 6-1
Lab 6-2
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
Class Design
Lab 6-3
Lab 6-4
Class Design
Lab 6-5
Lab 6-6
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
Class Design
Lab 6-7
2.
Lab 6-8
2.
3.
2.
3.
4.
5.
Class Design
Lab 6-9
Lab 6-10
Class Design
Lab 6-11
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
Lab 6-12
package com.mybank.domain;
public class SavingsAccount extends Account {
// insert code here
}
2.
Class Design
Lab 6-13
package com.mybank.domain;
public class CheckingAccount extends Account {
// insert code here
}
2.
Lab 6-14
Class Design
Lab 6-15
Lab 6-16
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
Class Design
Lab 6-17
com.mybank.domain
serves
Bank
0..*
Customer
has-a
0..*
Account
SavingsAccount
Figure 6-2
CheckingAccount
Lab 6-18
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
2.
3.
Class Design
Lab 6-19
Lab 6-20
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
Class Design
Lab 6-21
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.
2.
3.
4.
5.
Add the getAccount method. This method returns the account associated
with the given index parameter. This method replaces the previous
getAccount method, which should be removed.
Lab 6-22
1.
2.
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.
b.
Class Design
Lab 6-23
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
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.
Add the getAccount method. This method returns the account associated
with the given index parameter. This method replaces the previous
getAccount method, which should be removed.
Class Design
Lab 6-25
3.
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.
System.out.println("
" + account_type + ": current balance is "
+ account.getBalance());
Lab 6-26
AccumulateSavingsBatch
CustomerReport
-bank : Bank
-bank : Bank
methods
+doBatch():void
+setBank(bank:Bank):void
methods
+generateReport():void
+setBank(bank:Bank):void
SavingsAccount
-interestRate : double
constructors
+SavingsAccount(initBalance:double,
interestRate:double)
methods
+accumulateInterest():void
Figure 6-3
Class Design
Lab 6-27
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
Lab 6-28
3.
Add a setBank method to set the method parameter to the bank instance
variable.
4.
Lab 6-29
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Lab 6-30
Exercise Summary
Exercise Summary
!
?
Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Interpretations
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Conclusions
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Applications
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Class Design
Lab 6-31
Exercise Summary
Lab 6-32
Lab 7
Lab 7-1
com.mybank.domain
Bank
-customers : Customer[]
-numberOfCustomers : int
constructors
-Bank()
methods
+addCustomer(f:String, l:String)
+getNumOfCustomers():int
+getCustomer(index:int):Customer
serves
0..*
Figure 7-1
Customer
has-a
Account
Lab 7-2
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
Lab 7-3
Lab 7-4
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
Lab 7-5
2.
3.
4.
Move the original variable initialization code from the constructor to either
a static block or on the static variable declarations.
5.
6.
Remove the bank instance variable and the getBank and setBank
methods.
2.
Modify the generateReport method to use the static methods from the
new Bank utility class design.
Lab 7-6
Lab 7-7
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
Lab 7-8
2.
3.
Move the original variable initialization code from the constructor to either
a static block or on the static variable declarations.
static {
customers = new Customer[10];
numberOfCustomers = 0;
}
5.
private Bank() {
// this constructor should never be called
}
6.
Lab 7-9
Remove the bank instance variable and the getBank and setBank
methods.
2.
Modify the generateReport method to use the static methods from the
new Bank utility class design.
Lab 7-10
Lab 7-11
{abstract}
Pet
#legs : int
constructors
#Animal(legs:int)
methods
+walk():void
+eat():void
Spider
constructors
+Spider()
methods
+eat():void
+getName():String
+setName(n:String):void
+play()
Cat
Fish
-name : String
-name : String
constructors
+Cat(n:String)
+Cat()
constructors
+Fish()
methods
+getName():String
+setName(n:String):void
+play():void
+eat():void
Figure 7-2
methods
+getName():String
+setName(n:String):void
+play():void
+walk():void
+eat():void
Lab 7-12
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
2.
The Pet interface must satisfy the UML diagram in Figure 7-1 on page L7-2.
Lab 7-13
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
say something similar to This animal walks on 4 legs, where 4 is the
value of the legs instance variable.
2.
Create the Spider, Cat, and Fish classes in the Source Packages of the
InterfaceProject project to satisfy the UML diagram in Figure 7-1 on
page L7-2.
In this task, you create the TestAnimals class with the following
characteristics:
Class Name: TestAnimals
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();
Lab 7-14
Casting objects
Using polymorphism
Lab 7-15
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise
Lab 7-16
2.
The Pet interface must satisfy the UML diagram in Figure 7-1 on page L7-2.
b.
c.
d.
e.
Declare a concrete method walk that prints out something about how
the animals walks (include the number of legs).
Lab 7-17
3.
b.
c.
4.
b.
This class must include a String instance variable to store the name
of the pet.
c.
d.
e.
f.
Lab 7-18
This class must include a String instance variable to store the name
of the pet.
c.
d.
e.
Override the walk method. This method should call the super method
and they print a message that fish do not walk
f.
In this task, you create the TestAnimals class with the following
characteristics:
Class Name: TestAnimals
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:
Casting objects
Using polymorphism
Lab 7-19
Lab 7-20
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
Lab 7-21
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();
}
a.
Declare a concrete method walk that prints out something about how
the animals walks (include the number of legs).
Lab 7-22
a.
public Spider() {
super(8);
}
c.
b.
This class must include a String instance variable to store the name
of the pet.
public Cat(String n) {
Lab 7-23
e.
public Cat() {
this("");
}
public String getName() {
return name;
}
public void setName(String n) {
name = n;
}
public void play() {
System.out.println(name + " likes to play with string.");
}
f.
b.
This class must include a String instance variable to store the name
of the pet.
public Fish() {
super(0);
// this line must be here
}
Lab 7-24
Override the walk method. This method should call the super method
and they print a message that fish do not walk
In this task, you create the TestAnimals class with the following
characteristics:
Class Name: TestAnimals
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:
Lab 7-25
Lab 7-26
Exercise Summary
Exercise Summary
!
?
Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Interpretations
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Conclusions
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Applications
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Lab 7-27
Lab 8
Lab 8-1
com.mybank.domain
Account
exception
Exception
#balance : double
{from java.lang}
constructors
#Account(initBalance:double)
methods
+getBalance():double
+deposit(amt:double):void
+withdraw(amt:double):void
constructors
+Exception(msg:String)
methods
+getMessage():String
send
exception
CheckingAccount
OverdraftException
-overdraftAmount : double
-deficit : double
constructors
+CheckingAccount(initBalance:double,
overdraft:double)
+CheckingAccount(initBalance:double)
methods
+withdraw(amt:double):boid
Figure 8-1
constructors
+OverdraftException(msg:String,
deficit:double)
send
methods
+getDeficit():double
Lab 8-2
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
Lab 8-3
Lab 8-4
Lab 8-5
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
Lab 8-6
2.
3.
Add a public constructor that takes two arguments: message and deficit. The
message parameter should be passed to the superclass constructor. The
deficit parameter initializes the deficit instance variable.
4.
Modify the deposit method so that it does not return a value (that is,
void). This operation should never fail, so it does not need to throw any
exceptions.
2.
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 a new exception that specifies Insufficient
funds and the deficit (the amount requested subtracted by the current
balance).
Lab 8-7
Lab 8-8
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
Lab 8-9
package com.mybank.domain;
public class OverdraftException extends Exception {
// insert code here
}
2.
Add a public constructor that takes two arguments: message and deficit. The
message parameter should be passed to the superclass constructor. The
deficit parameter initializes the deficit instance variable.
Lab 8-10
Modify the deposit method so that it does not return a value (that is,
void). This operation should never fail, so it does not need to throw any
exceptions.
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 a new exception that specifies Insufficient
funds and the deficit (the amount requested subtracted by the current
balance).
Lab 8-11
Lab 8-12
Exercise Summary
Exercise Summary
!
?
Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Interpretations
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Conclusions
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Applications
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Lab 8-13
Lab 9
Lab 9-1
com.mybank.domain
serves
Bank
0..*
Customer
has-a
0..*
Account
SavingsAccount
Bank
Customer
-customers : List<Customer>
constructors
-Bank()
methods
+addCustomer(f:String, l:String)
+getNumOfCustomers():int
+getCustomer(index:int):Customer
Figure 9-1
Lab 9-2
CheckingAccount
-accounts : List<Account>
-firstName : String
-lastName : String
constructors
+Customer(f:String, l:String)
methods
+addAccount(acct:Account)
+getNumOfAccounts():int
+getAccount(index:int):Account
Domain Model of the Bank Project with Details on the Bank and
Customer Classes
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
Lab 9-3
Lab 9-4
Preparation
There is no preparation for this exercise.
2.
3.
4.
Lab 9-5
2.
3.
4.
5.
Lab 9-6
Lab 9-7
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
Lab 9-8
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;
2.
static {
customers = new ArrayList<Customer>(10);
}
4.
Lab 9-9
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;
2.
Lab 9-10
Lab 9-11
Exercise Summary
Exercise Summary
!
?
Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Interpretations
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Conclusions
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Applications
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Lab 9-12
Lab 10
I/O Fundamentals
There are no exercises for this module.
Lab 10-1
Lab 11
Lab 11-1
DataSource
CustomerReport
{from com.mybank.data}
-dataFile : File
constructors
+DataSource(dataFilePath:String)
methods
+loadData():void
exception
send
IOException
{from java.io}
read
test.dat
Figure 11-1
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 singlecharacter code that determines the type of account and also the data in that
record.
Code 11-1 Data File Format
<number-of-customers>
<first-name> <last-name> <number-of-accounts>
<account-type-code> <datum1> <datum2>
Lab 11-2
Simms
500.00
200.00
2
0.05
400.00
Owen
C
Bryant
200.00
1
0.00
Tim
S
C
Soley
2
1500.00 0.05
200.00 0.00
Maria
S
Soley
150.00
1
0.05
Lab 11-3
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise
Lab 11-4
Lab 11-5
Tool Reference Java Development: Java Application Projects: Setting the Main
Class
2.
Run the BankPrj project. The output should be similar to the following:
Lab 11-6
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
Lab 11-7
2.
3.
4.
Add a public method, loadData, that populates the Bank customer objects
and each customers account objects. Here is the pseudo-code for this
method:
read <number-of-customers>
for each customer record
read <first-name> and <last-name>
add customer to Bank
read <number-of-accounts>
for each account
read <account-type-code>
switch on <account-type-code>
Savings:
read <initial-balance> and <interest-rate)
create account and add account to customer
Checking:
read <initial-balance> and <overdraft-amount)
Lab 11-8
Tool Reference Java Development: Java Application Projects: Setting the Main
Class
2.
Lab 11-9
Run the BankPrj project. The output should be similar to the following:
Lab 11-10
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
Lab 11-11
2.
3.
4.
5.
6.
Click Next.
7.
8.
Click Finish.
package com.mybank.data;
// insert import statements here
public class DataSource {
// insert code here
}
2.
import
import
import
import
Lab 11-12
com.mybank.domain.*;
java.io.File;
java.io.IOException;
java.util.Scanner;
Lab 11-13
Add a public method, loadData, that populates the Bank customer objects
and each customers account objects, shown as follows:
Lab 11-14
Tool Reference Java Development: Java Application Projects: Setting the Main
Class
2.
Run the BankPrj project. The output should be similar to the following:
Lab 11-15
Lab 11-16
Exercise Summary
Exercise Summary
!
?
Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Interpretations
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Conclusions
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Applications
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Lab 11-17
Lab 12
Lab 12-1
Lab 12-2
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
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.
2.
Lab 12-3
Lab 12-4
1.
2.
Press the stop button in the output ChatClient window to stop the process
running.
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
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.
Lab 12-5
3.
Add four instance variables to the ChatClient class to hold the GUI
components.
4.
Add a public constructor that initializes each of the four GUI component
instance variables: The text area should be 10 rows tall and 50 columns
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.
5.
6.
Lab 12-6
2.
Press the stop button in the output ChatClient window to stop the process
running.
Lab 12-7
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
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.
Lab 12-8
3.
import java.awt.*;
import javax.swing.*;
public class ChatClient {
// insert code here
}
4.
private
private
private
private
Add four instance variables to the ChatClient class to hold the GUI
components.
JTextArea output;
JTextField input;
JButton sendButton;
JButton quitButton;
5.
Add a public constructor that initializes each of the four GUI component
instance variables: The text area should be 10 rows tall and 50 columns
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.
Lab 12-9
frame.add(output, BorderLayout.WEST);
frame.add(input, BorderLayout.SOUTH);
// Create the button panel
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(2,1));
p1.add(sendButton);
p1.add(quitButton);
// Add the button panel to the center
frame.add(p1, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
7.
Lab 12-10
2.
Press the stop button in the output ChatClient window to stop the process
running.
Lab 12-11
Lab 12-12
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
2.
Lab 12-13
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
rows in the API) of 10 characters and it must be read-only.
Note In this exercise, you will only be creating the layout of the ATM screen.
You will not be creating the code to make the buttons respond to user actions; you
will do that in the next module.
Lab 12-14
1.
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.
Lab 12-15
Exercise Summary
Exercise Summary
!
?
Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Interpretations
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Conclusions
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Applications
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Lab 12-16
Lab 13
(Optional) Create the GUI event handlers for the Banking project
Lab 13-1
Create an ActionListener that copies the text from the input text field
into the output text area when the send button is pressed.
Create an ActionListener that copies the text from the input text field
into the output text area when the Enter key is pressed in the input text
field.
Create an ActionListener that will quit the program when the Quit
button is pressed. (Hint Use System.exit(0).)
Create a WindowListener that will quit the program when the close
widget is pressed on the frame.
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
Lab 13-2
Hints
Use the following hints during this exercise:
Have the listeners (inner classes) access the instance variables of their
containing class to refer to the components like the output text area and the
input text field. Remember that you made the components instance
variables in the previous lab.
To get the text from a JTextArea or JTextField, you can use the
getText method; to set the text, use either the setText or append
method.
Lab 13-3
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
Lab 13-4
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.
3.
Add the ActionListener for the text field. Can you use the same listener
in Step 2?
4.
Add the WindowListener to the GUI frame. This listener must exit the
ChatClient program. Use an inner class for this listener.
5.
Add the ActionListener for the Quit button. This listener must exit the
ChatClient program. Use an anonymous inner class for this listener.
Lab 13-5
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
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.
Add the ActionListener for the text field. Can you use the same listener
in Step 2?
Add the WindowListener to the GUI frame. This listener must exit the
ChatClient program. Use an inner class for this listener.
Lab 13-7
Add the ActionListener for the Quit button. This listener must exit the
ChatClient program. Use an anonymous inner class for this listener.
Lab 13-8
2.
The user enters the ID using the key pad buttons. Each number is displayed
in the Data Entry text field.
When the ENTER button is selected, the application retrieves the specified
customer object and displays the following text in the Output text area:
Welcome FIRST-NAME LAST-NAME if the customer was found;
otherwise, the following text is displayed: Customer ID was not
found. Finally, if the customer was found, then the Action buttons are
enabled.
3.
Lab 13-9
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise
Lab 13-10
Lab 13-11
Exercise Summary
Exercise Summary
!
?
Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Interpretations
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Conclusions
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Applications
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Lab 13-12
Lab 14
GUI-Based Applications
Objectives
Upon completion of this lab, you should be able to add menus to the GUI for the
ChatRoom project.
Lab 14-1
Figure 14-1
Add the user name JComboBox component under the Send and Quit
buttons. This component enables you to select a name that is posted with
every chat line that you enter. You must alter the Send button and
JTextField listeners to write the username to the output JTextArea
component. Add several user name options including your full name and a
few nicknames, such as 1337dud3 or Java Geek.
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.
Lab 14-2
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
GUI-Based Applications
Lab 14-3
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
Lab 14-4
1.
Add the user name JComboBox component under the Send and Quit
buttons. This component enables you to select a name that is posted with
every chat line that you enter. Add several user name options including your
full name and a few nicknames, such as 1337dud3 or Java Geek.
2.
Enhance the listeners for the Send button and JTextField to write the
user name to the output JTextArea component.
4.
Add the File menu. This menu must include a Quit menu item that
terminates the program when selected.
5.
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.
GUI-Based Applications
Lab 14-5
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
Add the user name JComboBox component under the Send and Quit
buttons. This component enables you to select a name that is posted with
every chat line that you enter. Add several user name options including your
full name and a few nicknames, such as 1337dud3 or Java Geek.
Lab 14-6
3.
4.
Enhance the listeners for the Send button and JTextField to write the
user name to the output JTextArea component.
// Add declaration
private JScrollPane textPane;
// existing code here
// Put JTextArea into JScrollPane and define scroll bars
textPane = new JScrollPane(output,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
// existing code here
// Add JScrollPane to Layout
frame.add(textPane, BorderLayout.WEST);
GUI-Based Applications
Lab 14-7
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, that displays a comment about the program and
about you, the developer.
Lab 14-8
GUI-Based Applications
Lab 14-9
Exercise Summary
Exercise Summary
!
?
Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Interpretations
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Conclusions
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Applications
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Lab 14-10
Lab 15
Threads
Objectives
Upon completion of this lab, you should be able to create a simple multithreaded
application.
Lab 15-1
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
Lab 15-2
2.
The class implements the Runnable interface. The run method of the class
performs the following actions 10 times: Print the name of the current thread and
then sleep for 2 seconds.
Threads
Lab 15-3
Moe
Curly
Larry
Larry
Moe
Curly
Larry
Moe
Curly
Larry
Moe
Curly
Larry
Moe
Curly
Larry
Moe
Curly
Larry
Moe
Curly
Larry
Moe
Curly
Larry
Moe
Curly
Larry
Moe
Curly
Run this program several times. You might see different results for each
execution.
Discussion Can you explain the behavior of your program?
!
?
Lab 15-4
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
Threads
Lab 15-5
2.
3.
Create the run method to loop the following 10 times: Print the name of the
current thread and then sleep for 2 seconds.
2.
b.
c.
Lab 15-6
Threads
Lab 15-7
Preparation
There is no preparation required for this exercise.
Tool Reference Tool references used in this exercise:
Lab 15-8
Create the run method to loop the following 10 times: Print the name of the
current thread and then sleep for 2 seconds.
Threads
Lab 15-9
t1.setName("T1 - Larry");
t2.setName("T2 - Curly");
t3.setName("T3 - Moe");
c.
t1.start();
t2.start();
t3.start();
Lab 15-10
Exercise Summary
Exercise Summary
!
?
Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Interpretations
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Conclusions
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Applications
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Threads
Lab 15-11
Lab 16
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
(TCP/IP).
Lab 16-1
client: PC/Win95
1 Simon: This is cool!
ChatClient
Simon
client: SparcSol9
ChatServer
ChatClient
Debbie
client: PC/WinXP
ChatClient
Asok
Figure 16-1
Lab 16-2
Runnable
The RemoteReader is a nested class
that reads messages from the serverIn
instance variable in the ChatClient.
+run():void
RemoteReader
server
ChatClient
-serverIn : BufferedReader
-serverOut : PrintWriter
ChatServer
methods
-doConnect():void
SendHandler
methods
+actionPerformed(e:ActionEvent):void
Figure 16-2
Networking
Lab 16-3
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
For this exercise, you work in the ChatRoomPrj project in the projects
directory.
Lab 16-4
Networking
Lab 16-5
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise
For this exercise, you work in the ChatRoomPrj project in the projects
directory.
Lab 16-6
1.
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.
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.
b.
c.
d.
e.
f.
4.
5.
Modify the SendHandler nested class to send the message text (and the
user name) to the socket output stream. Delete the code that displayed the
message to the output text area.
6.
Networking
Lab 16-7
Lab 16-8
Preparation
There is no preparation for this exercise.
Tool Reference Tool references used in this exercise:
For this exercise, you work in the ChatRoomPrj project in the projects
directory.
Networking
Lab 16-9
import java.net.*;
import java.io.*;
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.
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.
try {
connection = new Socket(serverIP, Integer.parseInt(serverPort));
c.
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
serverIn = new BufferedReader(isr);
d.
Lab 16-10
} catch (Exception e) {
System.err.println("Unable to connect to server!");
e.printStackTrace();
} // END of try-catch block
} // END of doConnect method
4.
Modify the SendHandler nested class to send the message text (and the
user name) to the socket output stream. Delete the code that displayed the
message to the output text area.
Networking
Lab 16-11
Lab 16-12
Networking
Lab 16-13
Exercise Summary
Exercise Summary
!
?
Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Interpretations
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Conclusions
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Applications
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
Lab 16-14