Professional Documents
Culture Documents
Ilide - Info Starting Out With Java 5 Lab Manual PR
Ilide - Info Starting Out With Java 5 Lab Manual PR
Ilide - Info Starting Out With Java 5 Lab Manual PR
to Accompany
Diane Christie
University of Wisconsin – Stout
Publisher Greg Tobin
Senior Acquisitions Editor Michael Hirsch
Editorial Assistant Lindsey Triebel
Cover Designer Nicole Clayton
Marketing Manager Michelle Brown
Marketing Assistant Dana Lopreato
Prepress and Manufacturing Caroline Fell
Supplement Coordination Marianne Groth
Proofreader Melanie Aswell
Many of the designations used by manufacturers and sellers to distinguish their prod-
ucts are claimed as trademarks. Where those designations appear in this book, and
Addison-Wesley
Addison-W esley was aware
aware of a trademark claim, the designations have been printed in
initial caps or all caps.
Copyrigh
Copyrightt © 2007 Pear
Pearson
son Educati
Education,
on, Inc.
ISBN 0-321-43424-2
1 2 3 4 5 6 7 8 9 10—BB—09 08 07 06
Preface
Supplementary Materials
• Students
Students can find
find source
source code
code files
files for the
the labs at www
www.aw
.aw.com/
.com/cssu
cssuppor
pport,
t, under
authorr “Christi
autho “Christie”e” and title
title “ Lab Manual to Accompany Starting Out with Java 5:
From Control Structures to Objects ” or “Ga “Gadd
ddis
is”,
”, “Starting Out with Java 5:
From Control Structures to Objects .”
• Soluti
Solution
on files
files and source
source code are avail
available
able to qualifi
qualified
ed instructors
instructors at
at Addison
Addison--
Wesley’s Instructor Resource Center. Register at www.aw.com/irc and search for
author “Gaddis.
“Gaddis.””
Acknowledgements
I would like to thank everyone at Addison-Wesley for making this lab manual a reality,
Tony Gaddis for having the confidence in me to write labs to accompany his books and
my colleagues who have contributed ideas to help develop these labs.
I also thank my students at the University of Wisconsin-Stout for giving me feed-
back on these labs to continue to improve them.
Mostt of all,
Mos all, I want
want to thank
thank my fami
family:
ly: Mic
Michael
hael,, And
Andre
rew
w, and Pame
Pamela
la for
for all of
of
their
their encoura
encourageme
gement,nt, pati
patience
ence,, lo
love,
ve, and support
support..
Contents
Chap
Chapte
terr 1 La
Lab
b Algo
Algorrit
ithm
hms,
s, Er
Errror
ors,
s, an
and
d Test
stiing 1
Chapt
pteer 2 Lab Java Fu
Fund
nda
ament
nta
als 9
Chap
Chapte
terr 3 La
Lab
b Sele
Select
ctio
ion
n Co
Cont
ntrrol St
Stru
ruct
ctur
ures
es 21
Chapter 4 Lab Loops and Files 31
Chapter 5 Lab Methods 41
Chapt
pteer 6 Lab Classe
sess an
and Obj
Objeects 51
Chapt
pteer 7 Lab GUI App
ppllications 61
Chapter 8 Lab Arrays 67
Chap
Chapte
terr 9 La
Lab
b Morre Cl
Mo Clas
asse
sess and
and Ob
Obje
ject
ctss 75
Chapte
Chapterr 10
10 Lab
Lab Text Pr
Proce
ocessi
ssing
ng and
and Wra
Wrappe
pperr Clas
Classes
ses 87
Chap
Chapte
terr 11 La
Lab
b Inhe
Inherrit
itan
ance
ce 97
Chapt
Chapter
er 12 La
Lab
b Exce
Except
ptio
ions
ns an
and
d I/O
I/O St
Stre
ream
amss 109
Chapt
Chapter
er 13 La
Lab
b Advan
Advance
ced
d GUI
GUI Ap
Appl
plic
icat
atio
ions
ns 113
Chap
Chapte
terr 14 La
Lab
b App
pple
lets
ts an
and
d Mo
Morre 121
Chapt
pteer 15
15 La
Lab Recur
ursi
sio
on 127
Chapter 1 Lab
Algori
Algorithm
thms,
s, Erro
Errors,
rs, and Test
esting
ing
Objectives
• Be ab
able
le to wr
writ
itee an
an alg
algor
orit
ithm
hm
• Be abl
ablee to co
comp
mpil ilee a Jav
Javaa progr
program
am
• Be able to execute
execute a Jav Javaa program
program using
using the Sun JDK
JDK or a Jav
Javaa IDE
• Be ab
able
le to te
test
st a pro
progrgram
am
• Be able
able to debu
debug g a progra
program m with
with syntax
syntax and
and logic
logic erro
errors
rs
Introduction
Your teacher will introduce your computer lab and the environment you will be using
for programming in Java.
In chapter 1 of the textbook, we discuss writing your first
first program. The example
calculates the user’s gross pay. It calculates the gross pay by multiplying the number of
hours worked by hourly pay rate. However,
However, it is not always calculated this way.
way. What
if you work 45 hours in a week? The hours that you worked over 40 hours are consid-
ered overtime. You will need to be paid time and a half for the overtime hours you
worked.
In this lab, you are given a program which calculates user’
user’ss gross pay with or with-
with-
out overtime. You are to work backwards this time, and use pseudocode to write an
algorithm from the Java code. This will give you practice with algorithms while allow-
ing you to explore and understand a little Java code before we begin learning the Java
programming language.
You will also need to test out this program to ensure the correctness of the algo-
rithm and code. You will need to develop test data that will represent all possible kinds
of data that the user may enter.
You will also be debugging a program. There are several types of errors. In this lab,
you will encounter syntax and logic errors. We will explore runtime errors in lab 2.
1. Syntax Erro
Syntax Errors—
rs—err
errors
ors in the
the “gram
“grammar
mar”” of the
the progr
programm
amming
ing langu
language.
age. Thes
Thesee
are caught by the compiler and listed out with line number and error found. You
will learn how to understand what they tell you with experience. All syntax
errors must be corrected before the program will run. If the program runs, this
2 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
does not mean that it is correct, only that there are no syntax errors. Examples
of syntax errors are spelling mistakes in variable names, missing semicolon,
unpaired
unpaired curly
curly braces,
braces, etc.
2. Logic Errors—
Logic Errors—err
errors
ors in
in the logic
logic of the
the algorit
algorithm.
hm. Thes
Thesee errors
errors emphas
emphasize
ize the
the
need for a correct algorithm. If the
the statements are out of order,
order, if there are
errorss in a formula, or if there are missing
error missing steps,
steps, the program
program can still run
run and
give you output, but it may be the wrong output. Since there there is no list of errors
errors
for logic errors,
errors, you may not realize you have errors unless you check your out-
put. It is very important to know what output you expect. You should test your
programs with different
different inputs, and know what output to expect in each case.
For example,
example, if your program
program calculates
calculates your pay,
pay, you should check
check three dif-
ferent cases: less than 40 hours, 40 hours,
hours, and more
more than 4040 hours.
hours. Calculate
Calculate
each case by hand before running your program so that you know what to
expect. You may get a correct answer for one case, but not for another case.
This will help you figure out where your logic errors are.
3. Run time
time err
errors
ors—er
—error
rorss that
that do not occur
occur unt
until
il the
the progr
program
am is
is run,
run, and then
then
may only occur with some data. These errors emphasize the need for complete-
ly testing your program.
Chap
Chapte
terr 1 Lab
Lab Algo
Algori
rith
thms
ms,, Er
Erro
rors
rs,, an
and
d Tes
Testi
ting
ng 3
Task #1
#1 Wri
Writin
ting
g an Alg
Algori
orithm
thm
1. Copy the file Pay.java (see code listing 1.1) from www.aw.com/cssupport or as
directed by your instructor.
2. Open the
the file
file in
in your Jav
Javaa Integrat
Integrated
ed Develop
Development
ment Env
Environme
ironmentnt (IDE)
(IDE) or
or a text
text
editor as directed by your instructor.
instructor. Examine the file, and compare it with the
detailed version of the pseudocode in step number 3, section 1.6 of the the text-
book. Notice that the pseudocode does not include every line of code. The pro-
gram code includes identifier declarations and a statement that is needed to
enable Java to read from the keyboard. These are not part of actually complet-
ing the task of calculating pay,
pay, so they are not included in the pseudocode. The
only important difference between the example pseudocode and the Java code
is in the calculation. Below is the detailed pseudocode from the example, but
without the calculation part. You need to fill in lines that tell in English what
the calculation part of Pay.java is doing.
Task #2 Com
Compil
pilee and Execut
Executee a Program
Program
1. Compile the Pay.java using the Sun JDK or a Java IDE as directed by your
instructor.
2. You sho
shoul
uld
d not
not rece
receiv
ivee any
any erro
errorr mess
messag
ages
es..
3. When this
When this progra
programm is execut
executed,
ed, it will
will ask
ask the user
user for
for input.
input. You shoul
should
d calcu-
calcu-
late several different cases by hand. Since there is a critical point at which the
calculation
calcula tion changes,
changes, you should
should test three
three diffe
different
rent cases:
cases: the critical
critical point,
point, a
number above the critical point, and a number below the critical point. You
want to calculate by hand so that you can check the logic of the program. Fill
in the chart below with your test cases and the result you get when calculating
by hand.
4. Execute the progra
Execute programm using
using your fir
first
st set
set of data. Record your resul
result.
t. You will
will
need to execute the
the program three times to test all your data. Note: you do not
need to compile again. Once the program compiles correctly
correctly once, it can be
executed many times. You only need to compile again if you make changes to
the code.
Task #3
#3 Debu
Debugging
gging a Jav
Java
a Program
Program
1. Copy the file SalesTax.java (see code listing 1.2) from www
www.aw
.aw.com/cssupport
.com/cssupport
or as directed by your instructor.
2. Open the
the file
file in
in your IDE oror text
text editor
editor as directe
directedd by your
your instru
instructor
ctor.. This
This file
file
contains a simple Java program that contains errors. Compile the program. You
should get a listing
listing of syntax errors.
errors. Correct all the syntax errors, you may
want to recompile after you fix some of the errors.
3. When all syn
When syntax
tax err
errors
ors are cor
correc
rected,
ted, the prog
program
ram sho
should
uld comp
compile
ile.. As in
in the
previous exercise,
exercise, you need to develop some test data. Use the chart below to
record your test data and results when calculated by hand.
4. Executee the progr
Execut program
am using
using your
your test
test data
data and
and recordi
recording
ng the
the result
results.
s. If the
the output
output
of the program is different from
from what you calculated, this usually indicates a
logic error. Examine the program and correct logic error. Compile the program
and execute using the test data again. Repeat until all output matches what is
expected.
//identifier declarations
double hours; //number of hours worked
double rate; //hourly pay rate
double pay; //gross pay
//calculations
if(hours <= 40)
pay = hours * rate;
else
pay = (hours - 40) * (1.5 * rate) + 40 * rate;
//display results
System.out.println("You earned $" + pay);
}
}
Chap
Chapte
terr 1 Lab
Lab Algo
Algori
rith
thms
ms,, Er
Erro
rors
rs,, an
and
d Tes
Testi
ting
ng 7
import java.util.Scanner;
//calculations
tax = price + TAX_RATE;
total = price * tax;
//display results
System.out.print(item + " $");
System.out.println(price);
System.out.print("Tax $");
System.out.println(tax);
System.out.print("Total $");
System.out.println(total);
}
}
Chapter 2 Lab
Java Fundamentals
Objectives
• Write arith
Write arithmet
metic
ic expre
expressi
ssions
ons to
to accompl
accomplishish a task
task
• Use cast
casting
ing to
to conver
convertt between
between prim
primiti
itive
ve types
types
• Use a value-r
value-returni
eturning
ng librar
library
y method
method and and a librar
library
y constant
constant
• Use str
string
ing met
methods
hods to mani
manipula
pulate
te stri
string
ng data
data
• Communicate
Communi cate with
with the
the user
user by using the Scanner
Scanner class or dialog
dialog boxes
boxes
• Create a program
program from
from scratch
scratch by transla
translating
ting a pseudocode
pseudocode algori
algorithm
thm
• Be ab
able
le to do
docum
cumen entt a pr
progr
ogram
am
Introduction
This lab is designed to give you practice with some of the basics in Java. We will con-
tinue ideas from lab 1 by correcting logic errors while looking at mathematical formu-
las in Java. We will explore the difference between integer division and division on
your calculator as well as reviewing the order of operations.
We will also learn how to use mathematical formulas that are preprogrammed in
Java. On your calculator there are buttons to be able toto do certain operations, such as
raise a number to a power or use the number pi. Similarly,
Similarly, in Java,
Java, we will have
have pro-
grams that are available for our use that will also do these operations. Mathematical
operations that can be performed with the touch of a button on a calculator are also
available in the Math class. We will learn how to use a Math class method to cube the
radius in the formula for finding the volume of a sphere.
This lab also introduces communicating with the user. We have already seen how
console input and output work in lab 1. We will now need to learn how to program
user input, by investigating
investigating the lines of code that we need to add in order to use the
Scanner class. We will also learn the method call needed for output.
Alternately,, you may use dialog boxes for communicating with the user. An intro-
Alternately
duction to graphical user interface (GUI) programming is explored using the
JOptionPane class.
The String class is introduced and we will use some of the available methods to
prepare you for string processing.
10 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #1 Corr
Correcting
ecting Logic Errors
Errors in Formula
Formulass
1. Download th
the fi
file NumericTypes.java (see code listing 2.1) from
www.aw
www.aw.com/cssupport
.com/cssupport or as directed by your instructor
instructor..
2. Compilee the
Compil the sour
source
ce file
file,, run the pro
progra
gram,
m, and obs
observ
ervee the
the outpu
output.
t. Som
Somee of the
output is incorrect . You need to correct logic errors in the average formula
and the temperature conversion formula. The logic errors could be due to con-
version
version between
between data types, order of operations
operations,, or formula
formula problems.
problems. The nec-
essary formulas are
score1 + score2 5
average = C = 9 (F - 32)
numberOfScores
3. Each tim
timee you mak
makee change
changess to
to the
the progr
program
am code,
code, you mus
mustt compi
compile
le agai
again
n for
for
the changes to take effect before running the program again.
4. Make sure
Make sure that the
the output
output make
makess sense
sense befor
beforee you conti
continue.
nue. The aver
average
age of 95
95
and 100 should be 97.5 and the temperature that water boils is 100 degrees
Celsius.
12 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
1. Add an impor
importt statem
statement
ent abov
abovee the class
class decl
declara
aratio
tion
n to make
make the Scanne
Scannerr class
class
available to your program.
2. In the
the main
main met
method,
hod, cre
create
ate a Scanne
Scannerr object
object and conne
connect
ct it
it to
to the
the Syste
System.i
m.in
n
object.
3. Prom
Prompt
pt the
the use
userr to
to ente
enterr his/
his/he
herr fir
first
st nam
name.
e.
4. Read the name
name from
from the keyb
keyboar
oard
d using
using the
the nextL
nextLine
ine meth
method,
od, and stor
storee it int
into
o
a variable called firstName (you will need to declare any variables you use).
5. Prom
Prompt
pt th
thee user
user to ent
enter
er hi
his/
s/he
herr las
lastt nam
name.
e.
6. Read the name
name from
from the keyb
keyboar
oard
d and sto
store
re it
it in a vari
variabl called lastName .
ablee called
7. Concatenate ththe firstName and lastName with a space between them and
store the result in a variable called fullName .
8. Print out the fullName .
9. Comp
Compil
ile,
e, de
debu
bug,
g, an
and
d run
run,, us
usin
ing
g you
yourr nam
namee as
as tes
testt dat
data.
a.
10. Since we
Since we are
are addin
adding
g on to the
the same
same pro
progra
gram,
m, eac
each
h time
time we
we run
run the
the progr
program
am we
we
will get the output from the previous tasks before the output of the current task.
Chap
Chapte
terr 2 Lab
Lab Java
Java Fu
Fund
ndam
amen
enta
tals
ls 13
Task #2 (Alter
(Alternate)
nate) Using
Using Dialog
Dialog Boxes
Boxes for
for User Input
Input
1. Add an impor
importt statem
statement
ent abov
abovee the class
class decl
declara
aratio
tion
n to make
make the JOpti
JOptionP
onPane
ane
class available to your program.
2. In the
the main
main meth
method,
od, pro
prompt
mpt the user
user to enter
enter his
his/he
/herr firs
firstt name
name by disp
display
laying
ing
an input dialog box and storing the user input in a variable called firstName
(you will need to declare any variables you use).
3. Prompt the
Prompt the user
user to ente
enterr his/he
his/herr last
last name
name by displ
displayi
aying
ng an input
input dia
dialog
log box
box
and storing the user input in a variable called lastName .
4. Concatenate ththe firstName and lastName with a space between them and
store the result in a variable called fullName .
5. Display the fullName using a message dialog box.
6. Comp
Compil
ile,
e, de
debu
bug,
g, an
and
d run
run,, us
usin
ing
g you
yourr nam
namee as
as tes
testt dat
data.
a.
7. Since we
Since we are
are addin
adding
g on to the
the same
same pro
progra
gram,
m, eac
each
h time
time we
we run
run the
the progr
program
am we
we
will get the output from the previous tasks before the output of the current task.
14 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #3 Work
orking
ing with
with String
Stringss
1. Use the charAt method to get the first character in firstName and store it in
a variable called firstInitial (you will need to declare any variables that
you use).
2. Prin
Printt out
out th
thee use
user’
r’ss fir
first
st in
init
itia
ial.
l.
3. Use the toUpperCase method to change the fullName to all capitals and
store it back into the fullName variable
4. Add a li
Add line
ne th
that
at pr
prin
ints
ts ou
outt the
the va
valu of fullName and how many characters
luee of
(including the space) are in the string stored in fullName (use the method
length to obtain that information).
5. Compile
Compi le,, de
debu
bug,
g, an
and
d run.
run. The
The new
new output
output adde
added
d on afte
afterr the
the outpu
outputt from
from the
the
previous tasks should have your initials and your full name in all capital letters.
Chap
Chapte
terr 2 Lab
Lab Java
Java Fu
Fund
ndam
amen
enta
tals
ls 15
Task #4
#4 Using Pred
Predefin
efined
ed Math
Math Functions
Functions
1. Add a lin
linee that
that promp
prompts
ts the
the user
user to
to enter
enter the
the diamet
diameter
er of a spher
sphere.
e.
2. Read in
in and store
store the
the number
number into
into a vari
variabl
ablee called
called diamet
diameter
er (you
(you will
will need
need to
declare any variables that you use).
3. The diam
diamete
eterr is twi
twice
ce as lon
long
g as the radiu
radius,
s, so calc
calcula
ulate
te and
and store
store the radi
radius
us in
in
an appropriately named variable.
4. The fo
form
rmul
ulaa for
for th
thee vol
volum
umee of
of a sp
spher
heree is
is
4 3
V = pr
3
Convert the formula to Java and add a line which calculates and stores the
value of volume in an appropriately named variable. Use Math.PI for p and
Math.pow to cube the radius.
5. Print
Print your
your resu
results
lts to the
the scree
screen
n with
with an appr
appropr
opriat
iatee messag
message.
e.
6. Compil
Compile,
e, deb
debug,
ug, and run usi
using
ng the
the foll
follow
owing
ing tes
testt data
data and rec
record
ord the res
result
ults.
s.
Task #5 Cr
Create
eate a progr
program
am from
from scratch
scratch
In this task the student will create a new program that calculates gas mileage in miles
per gallon. The student
student will use string expressio
expressions,
ns, assig
assignment
nment statements
statements,, input and
output statements to communicate with the user.
1. Crea
Create
te a ne
new
w fil
filee in yo
your
ur IDE
IDE or
or text
text edi
edito
torr.
2. Create
Create the she
shell
ll for your fi
first
rst pro
progra
gram
m by
by enter
entering
ing::
public class Mileage
{
public static void main(String[] args)
{
// add your declaration and code here
}
}
3. Save th
the fi
file aass Mileage.java .
4. Translatee the algori
Translat algorithm
thm belo
below
w into
into Jav
Java.
a. Don’t
Don’t forg
forget
et to
to declare
declare variab
variables
les
before they are used. Each variable must be one word only (no spaces).
Print a line indicating this program will calculate mileage
Print prompt to user asking for miles driven
Read in miles driven
Print prompt to user asking for gallons used
Read in gallons used
Calculate miles per gallon by dividing miles driven by gallons used
Print miles per gallon along with appropriate labels
5. Compil
Compilee the
the progra
program
m and deb
debug,
ug, rep
repeati
eating
ng until
until it comp
compile
iless succes
successfu
sfully
lly..
6. Run the
the progr
program
am and
and test
test it usin
using
g the foll
follow
owing
ing sets
sets of
of data
data and recor
record
d the
results:
Miles driven Gallons used Miles per gallon Miles per gallon
(hand ca
calculated) (resulting ou
output)
2000 100
500 25. 5
241. 5 10
100 0
7. The last
last set of data
data caus
caused
ed the
the comput
computer
er to
to divid
dividee 100 by 0, whi
which
ch resul
resulted
ted in
in
what is called a runtime error. Notice that runtime can occur on programs
which compile and run on many other sets of data. This emphasizes the need to
thoroughly test you program with all possible kinds of data.
Chap
Chapte
terr 2 Lab
Lab Java
Java Fu
Fund
ndam
amen
enta
tals
ls 17
Task #6 Docume
Documenting
nting a Jav
Java
a Program
Program
1. Compar
Comp aree th
thee co
code
de li
list
stin
ings
gs of NumericTypes.java with Mileage.java . You will
see that NumericTypes.java has lines which have information about what the
program is doing. These lines are called comments and are designated by the
// at the beginning of the line. Any comment that starts with /** and ends
with */ is considered a documentation comment. These are typically written
just before a class header,
header, giving a brief description
description of the class. They are also
used for documenting methods in the same way.
2. Write a docume
Write documentantatio
tion
n comment
comment at the
the top of
of the progr
program
am which
which indica
indicates
tes the
the
purposee of the program,
purpos program, your name,
name, and today’
today’s date.
3. Add comm
comment
ent lines
lines aft
after
er each
each vari
variabl
ablee declar
declarati
ation,
on, ind
indicat
icating
ing what
what each
each vari
vari--
able represents.
4. Add comm
comment
ent lines
lines for each sec
sectio
tion
n of the prog
program
ram,, ind
indicat
icating
ing what
what is done
done in
in
that section.
5. Finall
Finally
y add a comm
comment
ent line
line indi
indicat
cating
ing the
the purpo
purpose
se of the
the calcul
calculati
ation.
on.
18 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
//identifier declarations
final int NUMBER = 2 ; // number of scores
final int SCORE1 = 100;
100; // first test score
final int SCORE2 = 95; // second test score
final int BOILING_IN_F = 212; // freezing temperature
int fToC; // temperature in Celsius
double average; // arithmetic average
String output; // line of output to print out
//TASK #2 declare variables used here
//TASK #3 declare variables used here
//TASK #4 declare variables used here
System.out.println(output);
System.out.println(); // to leave a blank line
Objectives
• Be able to construct
construct boolean expreexpression
ssionss to evalua
evaluate
te a given
given conditio
conditionn
• Be abl
ablee to
to comp
compararee Stri
String
ngss
• Be ab
able
le to us
use a fla
lagg
• Be able to construct
construct if and if-el
if-else-i
se-iff statements
statements to perform
perform a specif
specific
ic task
task
• Be able
able to cons
constru
truct
ct a swi
switch
tch sta
statem
tementent
• Be ab
able
le to fo
form
rmat
at nu
numbmber
erss
Introduction
Up to this point, all the programs you have had a sequential control structure. This
means that all statements are executed in order,
order, one after another.
another. Sometimes we need
to let the computer make decisions, based on the data. A selection control structure
allows the computer to select which statement to execute.
In order to have the computer make a decision, it needs to do a comparison. So we
will work with writing boolean expressions. Boolean expressions use relational opera-
tors and logical operators to create a condition that can be evaluated as true or false.
Once we have a condition, we can conditionally execute
execute statements. This means
that there are statements in the program that may or may not be executed,
executed, depending
on the condition.
We can also chain conditional statements together to allow the computer to choose
from several courses of action. We will explore this using nested if-else statements as
well as a switch statement.
In this lab, we will be editing a pizza ordering program. It creates a Pizza object to
the specifications that the
the user desires. It walks
walks the user through ordering, giving the
user choices, which the program then uses to decide how how to make the
the pizza and how
much the cost of the pizza will be. The user will also receive a $2.00 discount if
his/her name is Mike or Diane.
22 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Tas
ask
k #1 Th
Thee if State
Statemen
ment,
t, Co
Comp
mpar
arin
ing
g Strin
Strings
gs,, an
and
d Flags
Flags
1. Copy the file PizzaOrder.java (see code listing 3.1) from www
www.aw
.aw.com/cssup-
.com/cssup-
port or as directed by your instructor.
2. Compile and run PizzaOrder.java . You will be able to make selections, but at
this point, you will always
always get a Hand-tossed pizza at a base cost of $12.99 no
matter what
what you select,
select, but you will
will be able to
to choose toppings,
toppings, and they
should add into the price correctly. You will also notice that the output does not
look like money. So we need to edit PizzaOrder.java to complete the program
so that it works correctly.
3. Construct
Constru ct a simple
simple if stat
statemen
ement.
t. The
The conditi
condition
on will
will compare
compare the
the String
String input
input by
the user as his/her first
first name with the first
first names of the owners,
owners, Mike and
Diane. Be sure that the comparison is not case sensitive.
4. If the
the user
user has
has eith
either
er firs
firstt name,
name, set the dis
discoun
countt flag
flag to
to true.
true. Thi
Thiss will
will not
not
affect the price at this point yet.
Chapte
Chapterr 3 Lab
Lab Select
Selection
ion Con
Contro
troll Struc
Structur
tures
es 23
Task #2
#2 The if-el
if-else-i
se-iff Stateme
Statement
nt
1. Write an if-el
Write if-else-
se-if
if state
statement
ment that
that lets
lets the
the compute
computerr choose
choose which
which statem
statement
entss to
execut
executee by the user
user input
input size
size (10,
(10, 12, 14, or 16).
16). For each
each optio
option,
n, the cost
cost
needs to be set to the appropriate amount.
2. The defaul
defaultt else of the
the above
above if-el
if-else-
se-if
if state
statement
ment shoul
should
d print
print a statemen
statementt that
the user input was not one of the
the choices, so a 12 inch pizza will be made. It
should also set the size to 12 and the cost to 12.99.
3. Compile,
Compil e, deb
debug,
ug, and runrun.. You shoul
should d now
now be abl
ablee to get cor
correc
rectt outpu
outputt for
for size
size
and price (it will still
still have Hand-tossed crust,
crust, the output won’t look likelike money,
money,
and no discount will be applied yet). Run your program multiple times ordering
a 10,
10, 12
12,, 14
14,, 16
16,, an
andd 17
17 inc
inchh piz
pizza
za..
24 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #3 Swi
Switch
tch Sta
Stateme
tement
nt
1. Write a switch
Write switch state
statement
ment that
that compar
compareses the user’
user’ss choice
choice with
with the approp
appropria
riate
te
characters (make sure that both capital letters and small letters will work).
2. Each case
case will
will assi
assign
gn the appr
appropr
opriat
iatee string
string indi
indicati
cating
ng crust
crust type
type to the
the crust
crust
variable.
3. The defau
defaultlt case
case will
will print
print a stat
statemen
ementt that
that the user
user input
input was
was not
not one of the
the
choices,, so a Hand-tossed
choices Hand-tossed crust will
will be made.
4. Compile,
Compil e, deb
debug,
ug, and run
run.. You shoul
should
d now
now be abl
ablee to get cru
crust
st typ
types
es othe
otherr than
than
Hand-tossed. Run your program multiple times to make sure all cases of the
switch statement operate correctly.
Chapte
Chapterr 3 Lab
Lab Select
Selection
ion Con
Contro
troll Struc
Structur
tures
es 25
Task #4
#4 Usi
Using
ng a Flag
Flag as a Con
Condit
dition
ion
1. Write an if sta
Write statem
tement
ent that
that uses
uses the
the flag
flag as the
the conditi
condition.
on. Remem
Rememberber that
that the
the
flag is a Boolean variable, therefore is true or false.
false. It does not have
have to be com-
pared to anything.
2. The body of the
the if
if stat
statemen
ementt shoul
should
d conta
contain
in two
two stat
stateme
ements
nts::
a) A statement
statement that prints
prints a message
message indicating
indicating that
that the user
user is eligible
eligible for a
$2.00 discount.
b) A statement
statement that reduces the variabl
variablee cost
cost by 2.
3. Compile
Compi le,, de
debu
bug,
g, an
and
d run.
run. Tes
Testt your
your prog
progra
ram
m usin
using
g the
the owne
owners
rs’’ nam
names
es (bot
(both
h
capitalized and not) as well as a different name. The discount should be cor-
rectly at this time.
26 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #5 Fo
Forma
rmattin
tting
g Numbe
Numbers
rs
1. Add an impor
importt statem
statement
ent to
to use the
the Decimal
DecimalFor
Format
mat class
class as
as indica
indicated
ted abov
abovee the
class declaration.
2. Create
Create a Deci
Decimal
malFor
Format
mat obje
object
ct that
that alway
alwayss shows
shows 2 deci
decimal
mal plac
places.
es.
3. Edit the appro
Edit appropri
priate
ate lines
lines in
in the main
main method
method so that
that any
any monetar
monetary
y output
output has 2
decimal places.
4. Compile,
Compile, deb
debug,
ug, and run.
run. Your out
output
put sho
should
uld be
be comple
completel
tely
y correc
correctt at this
this tim
time,
e,
and numeric output should look like money.
Chapte
Chapterr 3 Lab
Lab Select
Selection
ion Con
Contro
troll Struc
Structur
tures
es 27
import java.util.Scanner;
import java.text.DecimalFormat;
System.out.println(
"Your order will be ready for pickup in 30 minutes.");
}
}
Chapter 4 Lab
Loops and Files
Objectives
• Be able to convert
convert an algorithm
algorithm using contro
controll structure
structuress into
into Java
Java
• Be ab
able
le to wr
writ
itee a wh
whililee loop
loop
• Be abl
ablee to
to writ
writee an do do-w
-whihile
le lo
loop
op
• Be ab
able
le to wr
writ
itee a for
for lo
loop
op
• Be able
able to use
use the
the Random
Random clas classs to gener
generate
ate rando
random m number
numberss
• Be abl
ablee to us
usee fil
filee stre
streams
ams fo forr I/O
I/O
• Be able
able to writ
writee a loop
loop that
that reads
reads until
until end of fi
file
le
• Be able
able to
to imple
implement
ment an accumu
accumulat lator
or and
and a count
counter er
Introduction
This is a simulation of rolling dice. Actual results approach theory only when the sam-
ple size is large. So we will need to repeat rolling the dice a large number of times (we
will use 10,000). The theoretical probability of rolling doubles of a specific number is
1 out of 36 or approximately 278 out of 10,000 times that you roll the pair of dice.
Since this is a simulation,
simulation, the numbers will vary a little each time you run it.
Check out how to use the random number generator (introduced in section 4.11 of
the text) to get a number between 1 and 6 to create the simulation.
We will continue to use control structures
structures that we have already
already learned, while
exploring control structures used for repetition. We shall also continue our work with
algorithms, translating a given algorithm to java java in order to complete our program. We We
will start
start with a while
while loop, then use the samesame program,
program, changin
changing g the while loop to a
do-while
do-whi le loop, and then a for loop.
loop.
We will be introduced to file input and output. We will read a file, line by line, con-
verting each line into a number. We will then use the numbers to calculate the mean
and standard deviation.
First we will learn how to use file output to get results printed to a file. Next we
will use file
file input to read the numbers from a file and calculate the mean. Finally,
Finally, we
will see
see that when the file
file is closed,
closed, and then reopened,
reopened, we will start
start reading
reading from the
top of the file again so that we can calculate the standard deviation.
32 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Tas
ask
k #1
#1 Wh
Whil
ilee loo
loop
p
Repeat while the number of dice rolls are less than the number of times the dice should
be rolled.
Get the value of the first
first die by “rolling”
“rolling” the first die
Get the value of the second
second die by “rolling”
“rolling” the second die
If the value of the first die is the same as the value of the second die
If value of first die is 1
Increment the number of times snake eyes were rolled
Else if value of the first die is 2
Increment the number of times twos were rolled
Else if value of the first die is 3
Increment the number of times threes were rolled
Else if value of the first die is 4
Increment the number of times fours were rolled
Else if value of the first die is 5
Increment the number of times fives were rolled
Else if value of the first die is 6
Increment the number of times sixes were rolled
Increment the number of times the dice were rolled
4. Compilee and run.
Compil run. You should
should get
get numbers
numbers that
that are
are somewhat
somewhat clos
closee to 278 for
each of the different pairs of doubles. Run it several times. You should get dif-
ferent results than the first
first time, but again it should be somewhat
somewhat close to 278.
Chap
Chapte
terr 4 La
Lab
b Loop
Loopss and
and Fi
File
less 33
Task #2
#2 Using Other Types of Loops
Loops
1. Change
Change th
thee whi
while
le lo
loop
op to a do-while loop. Compile and run. You should get the
same results.
2. Chan
angge th
the do loop to
to a for loop. Compile and run. You should get the same
results.
34 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #3
#3 Wri
Writin
ting
g Output
Output to
to a File
File
1. Copy the files StatsDemo.java (see code listing 4.2) and Numbers.txt from
www.aw
www .aw.com/cssupport
.com/cssupport or as directed by your instructor
instructor..
2. Firstt we
Firs we wil
willl wr
writ
itee out
outpu
putt to
to a fi
file
le::
a) Create a FileWriter
FileWriter object passi
passingng it the filenam
filenamee “Results.t
“Results.txt”
xt” (Don’
(Don’tt for-
for-
get the needed import statement).
b) Create a PrintWrit
PrintWriterer object
object passing
passing it the
the FileWriter
FileWriter object
object..
c) Since you are are using
using a FileWr
FileWriter
iter object, add a thro
throws
ws clause
clause to
to the main
method header.
d) Print the
the mean and standard
standard deviati
deviation
on to the output
output file
file using a three
three deci-
mal format,
format, labeli
labeling
ng each.
e) Cl
Clos
osee the
the outp
outputut fi
file
le..
3. Compile
Compi le,, de
debu
bug,
g, an
andd run.
run. You wil
willl need
need to
to type
type in
in the
the fil
filena
ename
me Numbers.txt.
You should get no output to the console, but running the program will create a
file called Results.txt with your output. The output you should get at this point
is: mean = 0.000, standa
standard
rd deviation
deviation = 0.000.
0.000. This
This is not the correct
correct mean
mean or
standard deviation for the data, but we will fix fix this in the next tasks.
tasks.
Chap
Chapte
terr 4 La
Lab
b Loop
Loopss and
and Fi
File
less 35
Task #4 Cal
Calcul
culati
ating
ng the
the Mean
Mean
1. Now we need
Now need to add
add lines
lines to
to allow
allow us
us to read
read from
from the
the input
input file
file and
and calcul
calculate
ate
the mean.
a) Create a FileReader
FileReader object passi
passing
ng it the filenam
filename.e.
b) Create a BufferedRea
BufferedReader
der object
object passing
passing it the
the FileReader
FileReader object.
object.
2. Write
Write a pri
primin
ming
g read
read to
to read
read the
the firs
firstt line
line of the
the file
file..
3. Write
Write a loop
loop that
that cont
continu
inues
es unti
untill you
you are at the
the end
end of the file
file..
4. The bo
The body
dy of the loloop
op wi
will
ll
a) con
convert
vert the
the line into
into a double
double value
value and add the
the value
value to the accumula
accumulator
tor
b) in
incr
crem
emen
entt the
the coun
counte
terr
c) re
read
ad a new
new liline
ne fro
fromm the
the file
file
5. When
When the
the progr
program
am exit
exitss the
the loop
loop clo
close
se the inp
input
ut fi
file.
le.
6. Calculate
Calcul ate and
and store
store the
the mean.
mean. The mean
mean is calc
calculat
ulated
ed by divid
dividing
ing the
the accumu
accumula-
la-
tor by the counter.
7. Compile
Compi le,, de
debu
bug,
g, an
and
d run.
run. You sho
shoul
uld
d now
now get
get a mean
mean of
of 77.4
77.444,
44, bu
butt the
the stan
stan--
dard deviation will still be 0.000.
36 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #5
#5 Calcul
Calculating
ating the Standar
Standard
d Deviatio
Deviation
n
1. We need to
to reconnec
reconnectt to the
the file
file so that
that we
we can start
start readi
reading
ng from
from the top
top again.
again.
a) Create a FileReader
FileReader object passi
passing
ng it the filenam
filename. e.
b) Create a BufferedRea
BufferedReader
der object
object passing
passing it the
the FileReader
FileReader object.
object.
2. Rein
Reinit
itia
iali
lize
ze su
sum
m and
and co
coun
untt to
to 0.
0.
3. Write
Write a pri
primin
ming
g read
read to
to read
read the
the firs
firstt line
line of the
the file
file..
4. Write
Write a loop
loop that
that cont
continu
inues
es unti
untill you
you are at the
the end
end of the file
file..
5. The bo
The body
dy of the loloop
op wi
will
ll
a) con
convert
vert the line
line into
into a double
double value
value and subtr
subtract
act the
the mean, store the result
result
in difference
b) add the
the square
square of the diffe
difference
rence to the
the accumulator
accumulator
c) in
incr
crem
emenentt th
thee coun
counte
terr
d) rea
read
d a new
new lin
linee from
from the
the file
file
6. When
When the
the progr
program
am exit
exitss the
the loop
loop clo
close
se the inp
input
ut fi
file.
le.
7. The vari
varianc
ancee is calcul
calculate
ated
d by divid
dividing
ing the
the accumu
accumulat
lator
or (sum
(sum of the
the square
squaress of
the difference) by the counter. Calculate the standard deviation by taking the
square root of the variance (Use Math.sqrt ( ) to take the square root).
8. Compile,
Compil e, deb
debug,
ug, and run
run.. You shoul
should
d get
get a mean
mean of 77.44
77.444
4 and
and standa
standard
rd devi
devia-
a-
tion of 10.021.
Chap
Chapte
terr 4 La
Lab
b Loop
Loopss and
and Fi
File
less 37
Objectives
Be able to write methods
Be able to call methods
Be able to write javadoc comments
Be able to create HTML documentation for our Java class using javadoc
Introduction
Methods are commonly used to break a problem down into small manageable pieces.
A large task can be broken down into smaller tasks (methods) that contain the details
of how to complete that small task. The larger problem is then solved by implementing
the smaller tasks (calling the methods) in the correct order.
This also allows for efficiencies,
efficiencies, since the method can be called as many times as
needed without rewriting the code each time.
Finally
Finally, we will use documentat
documentation
ion comments
comments for each method,
method, and generate
generate
HTML documents similar to the Java APIs that we have seen.
42 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #2 Value-R
alue-Return
eturning
ing Method
Methodss
1. Writee a st
Writ stat
atic
ic me
meth
thod
od ca
call
lled
ed circleArea that takes in the radius of the circle and
returns the area using the formula A = pr 2.
2. Writee a st
Writ stat
atic
ic me
meth
thod
od ca
call
lled
ed rectangleArea that takes in the length and width
of the rectangle and returns the area using the formula A = lw.
3. Writee a st
Writ stat
atic
ic me
meth
thod
od ca
call
lled
ed triangleArea that takes in the base and height of
the triangle and returns the area using the formula A = 12bh.
4. Writee a st
Writ stat
atic
ic me
meth
thod
od ca
call
lled
ed circleCircumference that takes in the radius of the
circle and returns the circumference using the formula C = 2pr .
5. Writee a st
Writ stat
atic
ic me
meth
thod
od ca
call
lled
ed rectanglePerimeter that takes in the length and
the width of the rectangle and returns the perimeter of the rectangle using the
formula P = 2l + 2w.
6. Writee a st
Writ stat
atic
ic me
meth
thod
od ca
call
lled
ed trianglePerimeter that takes in the lengths of the
three sides of the triangle and returns the perimeter of the triangle which is cal-
culated by adding up the three sides.
44 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Tas
ask
k #3 Ca
Call
llin
ing
g Metho
Methods
ds
1. Add lines
lines in
in the main
main method
method in the
the Geomet
GeometryD
ryDemo
emo class
class whic
which
h will
will call
call these
these
methods. The comments indicate where to place the method calls.
2. Below, writ
Below writee some
some sampl
samplee data
data and
and hand calc
calculat
ulated
ed resul
results
ts for
for you
you to
to test
test
all 6 menu items.
3. Compi
Compile
le,, de
debu
bug,
g, an
and
d run.
run. Tes
Testt out the
the prog
progra
ram
m usin
using
g your
your samp
sample
le data
data..
Chap
Chapte
terr 5 Lab
Lab Me
Meth
tho
ods 45
Task #4
#4 Ja
Java
va Docu
Document
mentati
ation
on
1. Write javad
Write javadoc
oc comment
commentss for each
each of the
the 7 stati
staticc methods
methods that
that you
you just
just wrote.
wrote.
They should include
a) A one line
line summ
summary
ary of
of what
what the met
method
hod does
does..
a) A descriptio
description n of what the program
program requires
requires toto operate
operate and what the result
result of
that operation is.
a) @param listlisting
ing and describi
describing
ng each of the
the parameters
parameters in in the parameter
parameter list
list
(if any).
a) @retu
@returnrn describing
describing the
the information
information that
that is returned
returned to the
the calling
calling statement
statement
(if any).
2. Generatee the docum
Generat documenta
entatio
tion.
n. Check
Check the meth
method
od summa
summary
ry and the metho
method d details
details
to ensure your comments were put into the Java Documentation correctly.
46 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
/**
This program demonstrates static methods
*/
switch (choice)
{
Code Listing 5.1 continued on next page.
Chap
Chapte
terr 5 Lab
Lab Me
Meth
tho
ods 47
case 1:
System.out.print(
"Enter the radius of the circle: ");
radius = keyboard.nextDouble();
//call the circleArea method and
//store the result
//in the value
System.out.println(
"The area
area of
of the
the circle
circle is
is " + value)
value);
;
break;
case 2:
System.out.print(
"Enter the length of the rectangle: ");
length = keyboard.nextDouble();
System.out.print(
"Enter the width of the rectangle: ");
width = keyboard.nextDouble();
//call the rectangleArea method and store
//the result in the value
System.out.println(
"The area of the rectangle is " + value);
break;
case 3:
System.out.print(
"Enter the height of the triangle: ");
height = keyboard.nextDouble();
System.out.print(
"Enter the base of the triangle: ");
base = keyboard.nextDouble();
//call the triangleArea method and store
//the result in the value
System.out.println(
"The area of the triangle is " + value);
break;
Code Listing 5.1 continued on next page.
48 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
case 4:
System.out.print(
"Enter the radius of the circle: ");
radius = keyboard.nextDouble();
//call the circumference method and
//store the result in the value
System.out.println(
"The circumference of the circle is " + value);
break;
case 5:
System.out.print(
"Enter the length of the rectangle: ");
length = keyboard.nextDouble();
System.out.print(
"Enter the width of the rectangle: ");
width = keyboard.nextDouble();
//call the perimeter method and store the result
//in the value
System.out.println(
"The perimeter of the rectangle is " + value);
break;
case 6:
System.out.print("Enter the length of side 1 " +
"of the triangle: ");
side1 = keyboard.nextDouble();
System.out.print("Enter the length of side 2 " +
"of the triangle: ");
side2 = keyboard.nextDouble();
System.out.print("Enter the length of side 3 " +
"of the triangle: ");
side3 = keyboard.nextDouble();
//call the perimeter method and store the result
//in the value
System.out.println("The perimeter of the " +
"triangle is " + value);
break;
default:
Code Listing 5.1 continued on next page.
Chap
Chapte
terr 5 Lab
Lab Me
Meth
tho
ods 49
System.out.println(
"You did not enter a valid choice.");
}
Objectives
• Be ab
able
le to de
decl
clararee a ne
new
w cla
class
ss
• Be ab
able
le to wr
writ
itee a co
cons
nstr
truc
ucto
torr
• Be able
able to writ
writee instan
instance
ce methods
methods thathatt return
return a valu
valuee
• Be able
able to write
write inst
instance
ance meth
methodsods that
that take
take argum
argument
entss
• Be abl
ablee to
to ins
insta
tantntia
iate
te an obj
object
ect
• Be able to use
use calls to instance
instance methods
methods to access
access and change the
the state
state of an
object
Introduction
Everyone is familiar with a television. It is the object we are going to create in this lab.
First we need a blueprint. All manufacturers have the same basic elements in the televi-
sions they produce as well as many options. We are going to work with a few basic
elements that are common to all televisions. Think about a television in general. It has
a brand name (i.e. it is made by a specific manufacturer). The television screen has a
specific size. It has some basic controls. There is a control to turn the power on and
off. There is a control to change the channel. There is also a control for the volume. At
any point in time, the television’s
television’s state can be described by how these controls are set.
We will write the television class. Each object that is created from the television
class must be able to hold information about that instance of a television in fields. So a
television object will have the following attributes:
• manufacturer . The manufacturer attribute will hold the brand name. This
cannot change once the television
television is created, so will be a named constant.
• screenSize. The screenSize attribute will hold the size of the television
screen. This cannot change once the television has been created so will be a
named constant.
• powerOn. The powerOn attribute will hold the value true if the power is on,
and false if the power is off.
• channel. The channel attribute will hold the value of the station that the tele-
vision is showing.
• volume. The volume attribute will hold a number value representing the loud-
ness (0 being no sound).
52 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
We will also need a constructor method that will be used to create an instance of a
Television.
These ideas can be brought together to form a UML (Unified Modeling Language)
diagram for this class as shown below.
Task #1 Cr
Creati
eating
ng a New Cla
Class
ss
1. In a new
new file
file,, cre
create
ate a class
class def
defini
initio
tion
n calle
called
d Tele
Televis
vision
ion..
2. Put a prog
program
ram heade
headerr (comm
(comments
ents/do
/docume
cumenta
ntatio
tion)
n) at the
the top
top of the
the file
file
// The purpose of this class is to model a television
// Your name and today’s date
3. Declare
Declare the 2 const
constant
ant fi
fields
elds lis
listed
ted in the
the UML
UML diag
diagram
ram..
4. Declare
Declare the 3 remai
remainin
ning
g fiel
fields
ds list
listed
ed in
in the
the UML
UML diagr
diagram.
am.
5. Write
Write a comm
comment
ent for each fi
field
eld ind
indicat
icating
ing what
what it repr
represe
esents
nts..
6. Save this file as Television.java.
7. Comp
Compil
ilee an
and
d deb
debug
ug.. Do
Do no
nott ru
run.
n.
54 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #2 Wri
Writin
ting
g a Const
Construct
ructor
or
1. Create a const
Create construc
ructor
tor def
defini
initio
tion
n that has
has two
two paramet
parameters
ers,, a manufac
manufactur
turer’
er’ss brand
brand
and a screen size. These parameters will bring in information
2. Inside the
Inside the constr
construct
uctor
or,, ass
assign
ign the
the valu
values
es taken
taken in
in from
from the
the paramet
parameters
ers to
to the
corresponding fields.
3. Initialize the powerOn field to off), the volume to 20,
to false (power is off), 20, and th
thee
channel to 2.
4. Write comment
Write commentss descri
describin
bing
g the purpo
purpose
se of the
the constr
construct
uctor
or above
above the
the method
method
header.
5. Comp
Compil
ilee an
and
d deb
debug
ug.. Do
Do no
nott ru
run.
n.
Chap
Chapte
terr 6 Lab
Lab Clas
Classe
sess and
and Obje
Object
ctss 55
Tas
ask
k #3
#3 Me
Meth
thod
odss
1. Deffin
De inee acc
acces
esso
sorr met
metho
hods
ds ca
called getVolume , getChannel ,
lled
getManufacturer , and getScreenSize that return the value of the cor-
responding field.
2. Defin
Def inee a mu
muta
tato
torr met
metho
hod
d cal
called setChannel accepts a value to be stored in
led
the channel field.
3. Define a mutat
Define mutator
or metho
methodd called
called power
power that
that chang
changes
es the
the state
state from
from true
true to fals
falsee
or from false to true. This can be accomplished by using the NOT operator (!).
If the boolean variable powerOn is tru true,
e, the n !powerOn is false and vice
then
versa. Use the assignment statement
powerOn = !powerOn;
to change the state of powerOn and then store it back into powerOn (remem-
ber assignment statements evaluate
evaluate the right hand side first,
first, then assign the
result to the left hand side variable.
4. Define two
Define two mutat
mutator
or metho
methods
ds to
to change
change the
the volum
volume.
e. One
One method
method shoul
should
d be
called increaseVolume and will increase the volume by 1. The other
method should be called decreaseVolume and will decrease the volume by
1.
5. Write
Write ja
javad
vadoc
oc com
comment
mentss abov
abovee each
each met
method
hod head
header
er..
6. Comp
Compil
ilee an
and
d deb
debug
ug.. Do
Do no
nott ru
run.
n.
56 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #4
#4 Run
Runnin
ning
g the appli
applicati
cation
on
1. You can
can only
only execut
executee (run)
(run) a progra
program
m that
that has
has a main
main meth
method,
od, so ther
theree is a dri-
dri-
ver program that is already written to test out your Television class. Copy
the file TelevisionDemo.java (see code listing 3.1) from www
www.aw
.aw.com/cssupport
.com/cssupport
or as directed by your instructor. Make sure it is in the same directory as
Television.java.
2. Compil
Compilee and run Tele
elevis
vision
ionDem
Demo
o and fol
follo
low
w the
the promp
prompts.
ts.
3. If you
yourr out
output
put ma
matc
tche
hess the
the out
outpu
putt bel
below
ow,, Television.java is complete and cor-
rect. You will not need to modify it further for this lab.
Task #5 Crea
Creating
ting another
another instance
instance of a Telev
Television
ision
import java.util.Scanner;
//declare variables
int station; //the user’s channel choice
System.out.println(
"Too loud!! I am lowering the volume.");
//decrease the volume of the television
bigScreen.decreaseVolume();
bigScreen.decreaseVolume();
bigScreen.decreaseVolume();
bigScreen.decreaseVolume();
bigScreen.decreaseVolume();
bigScreen.decreaseVolume();
//display the current channel and volume of the
//television
System.out.println("Channel: " +
bigScreen.getChannel() +
" Volume: " + bigScreen.getVolume());
System.out.println(); //for a blank line
Objectives
• Be abl
ablee to cre
creat
atee a clos
closea
eabl
blee windo
window w
• Be able
able to crea
create
te pane
panels
ls cont
contain
aining
ing but
button
tonss
• Be abl
ablee to us
usee dif
diffe
fere
rent
nt lay
layout
outss
• Be abl
ablee to
to handl
handlee but
butto
ton
n eve
event
ntss
Introduction
In this lab, we will be creating a graphical user interface
interface (GUI) to allow
allow the user to
select a button that will change the color of the center panel and radio buttons that will
change the color of the text in the center panel. We will need to use a variety of Swing
components to accomplish this task.
We will build two
two panels, a top panel containing three buttons and a bottom panel
containing three radio buttons. Layouts will be used to add these panels to the window
in the desired positions. A label with instructions will also be added to the window.
Listeners will be employed to handle the events desired by the user.
Our final GUI should look like the following
62 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Tas
ask
k #1 Cr
Crea
eatin
ting
g a GUI
GUI
1. Impo
Import
rt th
thee requ
requir
ired
ed Ja
Java
va li
libr
brar
arie
ies.
s.
2. Create
Create a cla
class
ss call
called
ed Color
ColorFac
Factor
tory
y that
that inher
inherits
its fro
from
m JFram
JFrame.
e.
3. Create
Create name
named
d constan
constants
ts for
for a width
width of
of 500 and
and height
height of
of 300 for
for the
the frame.
frame.
4. Write a defau
Write defaultlt cons
constru
tructo
ctorr that
that doe
doess the
the foll
follow
owing
ing
a) Set the
the title
title of
of the windo
window w to Color Facto
Factoryry..
b) Set the
the size
size of the window
window using the constant
constants. s.
c) Specif
Specifyy what happens when the the close
close button
button is clicked.
clicked.
d) Get the content
content pane
pane of the
the JFrame
JFrame and set the layout
layout manager
manager to border
border
layout.
e) Call the
the method to build
build the top
top panel (to
(to be written
written asas directed
directed below).
below).
f) Add the
the panel
panel to the
the north
north part
part of
of the cont
content
ent pane.
pane.
g) Call the method
method to build
build the bottom
bottom panel
panel (to be written
written as directed
directed below)
below)..
h) Add this
this panel to the south part of of the content pane.
i) Create a label that contains
contains the message
message “Top
“Top buttons
buttons change
change the
the panel
color and bottom radio buttons change the text color.”
j) Add this
this labe
labell to the
the center
center part
part of
of the cont
content
ent pane.
pane.
Chap
Chapte
terr 7 Lab
Lab GUII App
GU Appli
licat
catio
ions
ns 63
Task #2
#2 Wri
Writin
ting
g Privat
Privatee Methods
Methods
1. Write a pri
Write priva
vate
te meth
methodod that
that buil
builds
ds the
the top
top panel
panel as fol
follo
lows
ws
a) Cre
Create
ate a panel
panel tha
thatt conta
contains
ins thr
three
ee butt
buttons
ons,, red
red,, ora
orange,
nge, and yelyello
low
w.
b) Use flow
flow layout
layout for the panel
panel and set the background
background to to be white.
white.
c) The buttons
buttons should
should be labeled
labeled with
with the color
color name
name and also
also appear inin that
color.
d) Set the action
action command
command of each button button to bebe the first
first letter of the color
color
name.
e) Add button
button listener
listener that
that implement
implementss action
action listener
listener for
for each button.
button.
2. Create a botto
Create bottom
m panel
panel in the
the same
same way as the
the top
top panel
panel abo
above,
ve, bu
butt use
use radio
radio
buttons
buttons with
with the
the colors
colors green, blue, and cyan.
cyan.
64 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #3 Wri
Writin
ting
g Inner
Inner Clas
Classes
ses
1. Write a priv
Write private
ate inner
inner clas
classs called
called Butto
ButtonLi
nListe
stener
ner that
that impl
impleme
ements
nts
ActionListener. It should contain an actionPerformed method to handle the but-
ton events. This event handler will
will handle all button events,
events, so you must get the
action command of the event and write a decision structure to determine which
color to set the background of the content pane.
2. Write anothe
Write anotherr priva
private
te inner
inner class
class call
called
ed RadioB
RadioButt
uttonL
onList
istener
ener,, sim
simila
ilarr to Butto
Button
n
listener.. It will handle all radio
listener radio button events, so you will need to check the
source of the event and write a decision structure to determine which color
should be used for the text of the message.
Chap
Chapte
terr 7 Lab
Lab GUII App
GU Appli
licat
catio
ions
ns 65
Task #4
#4 Run
Runnin
ning
g the GUI
GUI Progr
Program
am
1. Write a main
Write main method
method that
that declare
declaress and creat
creates
es one inst
instanc
ancee of a ColorF
ColorFacto
actory
ry,,
then use the setVisible method to show it on the screen.
Chapter 8 Lab
Arrays
Objectives
• Be aable
ble to decl
declare
are and ins
instan
tantia
tiate
te arr
arrays
ays
• Be able to fill
able fill an arra
arrayy using
using a for
for loop
loop
• Be able to acces
able accesss and
and proces
processs data
data inin an arr
array
ay
• Be ablee to
abl to writ
writee a sor
sorti
ting
ng met
metho
hodd
• Be ablee to
abl to use
use an ararra
ray
y of obj
object
ectss
Introduction
Everyone is familiar
familiar with a list. We make shopping lists,
lists, to-do lists, assignment lists,
birthday
birth day lists,
lists, etc. Notice
Notice that though there
there may be many itemsitems on the list, we call the
list by one name. That is the idea of the array,
array, one name for a list of related
related items. In
this lab, we will work with lists
lists in the form of an array.
array.
It will start out simple with a list of numbers. We will learn how to process the
contents of an array. We will also explore sorting algorithms, using the selection sort.
We will then move onto more more complicated arrays, arrays that contain objects.
68 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #1 Aver
verage
age Clas
Classs
Create a class called Average according to the UML diagram.
Average
-data [ ] :in
-da intt
-mea
-m ean:
n: double
+Average( ):
+calcula
late
teMe
Mean(
an( ): voi
void
d
+toStrin g( ): St
Strrin g
+select
+selectionSo
ionSort(rt( ): void
This class will allow a user to enter 5 scores into an array. It will then rearrange the
data in descending order and calculate the mean for the data set.
Attributes:
• data[] —the array which will contain the scores
• mean—the arithmetic average of the scores
Methods:
• Average —the constructor. It will allocate memory for the array. Use a for
loop to repeatedly display a prompt for the user which should indicate that user
should enter score
score number
number 1, score number 2, etc. Note:
Note: The computer
computer starts
starts
counting
counti ng with 0, but people
people start
start counting
counting with 1, and your prompt
prompt should
should
account for
for this. For example
example,, when the user enters
enters score
score number 1, it will be
stored in indexed variable 0. The constructor will then call the
selectionSort and the calculateMean methods.
• calculateMean —this is a method that uses a for loop to access each score
in the array and add it to a running total. The total divided by the number of
scores (use the length of the array),
array), and the result is stored into mean.
• toString —returns a String containing data in descending order and the
mean.
• selectionSort —this method uses the selection sort algorithm to rearrange
the data set from highest to lowest.
Chap
Chapte
terr 8 La
Lab
b Arr
rray
ayss 69
Task #2
#2 Aver
verage
age Driv
Driver
er
1. Create an AverageDriver class. This class only contains the main method.
The main method should declare and instantiate an Average object. The
Average object information should then be printed to the console.
2. Compile,
Compil e, deb
debug,
ug, and run the pro
progra
gram.
m. It sho
should
uld out
output
put the dat
dataa set
set fro
from
m high
highest
est
to lowest and the mean. Compare the computer’s output to your hand calcula-
tion using a calculator.
calculator. If they are not the same,
same, do not continue until you cor-
rect your code.
70 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #3 Arra
Arrays
ys of Obj
Objects
ects
1. Copy the files Song.java (code listing 8.1), CompactDisc.java (code listing 8.2)
and Classics.txt (code listing 8.3) from www.aw.com/cssupport or as directed
by your instructor
instructor.. Song.java is complete and will not be edited. Classics.txt is
the data file that will be used by CompactDisc.java , the file
file you will
will be editin
editing.
g.
2. In CompactDisc.java , there are comments
comments indicating
indicating where the missing
missing code is
to be placed.
placed. Declare
Declare an array
array of Songs,
Songs, called cd,
cd, to be of size
size 6.
3. Fill the arra
Fill array
y by creati
creating
ng a new
new song with
with the
the title
title and arti
artist
st and
and storin
storing
g it in
the appropriate position in the array.
4. Prin
Printt the
the cont
conten
ents
ts of the
the arr
array
ay to
to the
the cons
consol
ole.
e.
5. Compi
Compile
le,, de
debu
bug,
g, an
and
d run.
run. Your ou
outp
tput
ut sho
shoul
uld
d be as
as foll
follow
ows:
s:
Contents of Classics
Ode to Joy by Bach
The Sleeping Beauty by Tchaikovsky
Lullaby by Brahms
Canon by Bach
Symphony No. 5 by Beethoven
The Blue Danube Waltz by Strauss
Chap
Chapte
terr 8 La
Lab
b Arr
rray
ayss 71
/**constructor
@param title The title of the song
@param artist The artost who sings the song*/
public Song(String title, String artist)
{
this.title = title;
this.artist = artist;
}
System.out.println("Contents of Classics:");
for (int i = 0; i < cd.length; i++)
{
//print the contents of the array to the console
}
}
}
Chap
Chapte
terr 8 La
Lab
b Arr
rray
ayss 73
Objectives
• Be abl
ablee to wr
writ
itee a copy
copy cons
constr
truct
uctor
or
• Be ab
able to write equals and toString methods
to wr
• Be able
able to use
use objects
objects made
made up of of other
other objects
objects (Ag
(Aggre
gregat
gation
ion))
• Be able
able to writ
writee methods
methods tha
thatt pass
pass and retu
return
rn object
objectss
Introduction
We discussed objects in Chapter 6 and we modeled a television in the Chapter 6 lab.
We want build
build on that lab, and work more with
with objects.
objects. This time,
time, the object that
that we
are choosing is more complicated. It is made up of other objects. This is called aggre-
gation. A credit card is an object that is very common, but not as simple as a television.
Attributes of the credit card include information about the owner,
owner, as well as a balance
and credit limit. These things would be our instance fields. A credit card allows you to
make payments and charges. These wouldwould be methods. As we have seen before, there
would also be other methods associated with this object in order to construct the object
and access its fields.
Examine the UML diagram that follows. Notice that the instance fields in the
CreditCard class are other types of objects, a Person object or a Money object. We can
say that
that the Credi
CreditCard
tCard “has a” Perso
Person,
n, which means
means aggreg
aggregation,
ation, and the Perso
Personn
object “has a” Address object as one of its instance fields. This aggregation structure
can create a very complicated object. We will try to keep this lab reasonably simple.
To start with, we will be editing a partially written
written class, Money
Money.. The constructor
that you will be writing is a copy constructor. This means it should create a new object,
but with the same values in the instance variables as the object that is being copied.
will write equals and toString methods. These are very common
Next, we will
methods that are needed when you write a class to model an object. You will also see a
compareTo method that is also a common method for objects.
76 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Credit Card
-balance:Money
-creditLimit:Money
-owner:Person
+CreditCard(newCardHolder:Person,, limit:Money):
+CreditCard(newCardHolder:Person
+getBalance():Money
+getCreditLimit():Money
+getPersonals():String
+charge(amount:Money):void
+payment(amount:Money):void
Money Person
-dollars:long -lastName:String
-cents:long -firstName:String
-home:Address
+Money(anount:double):
+Money(otherObject:Money): +toString():String
+add(otherAmount:Money):Money
+subtract(otherAmount:Money):Money
+compareTo(otherObject:Money):int
+equals(otherObject:Money):boolean
+toString():String
Address
-street:String
-city:String
-state:String
-zip:String
+toString():String
Chapte
Chapterr 9 Lab Mor
Moree Clas
Classes
ses and Obj
Object
ectss 77
Task #1
#1 Wri
Writin
ting
g a Copy Cons
Construc
tructor
tor
1. Copy the files Address.java (code listing 9.1), Person.java (code listing 9.2),
Money.java (code listing 9.3), MoneyDriver.java (code list listing
ing 9.4),
9.4), and
CreditCardDemo.java (code listing 9.5) from www www.aw
.aw.com/cssupport
.com/cssupport or as
directed by your instructor. Address.java , Person.java, MoneyDemo.java , and
CreditCardDemo.java are complete and will not need to be modified. We will
start by modifying Money.java.
2. Overload
Overlo ad the const
construc
ructor
tor.. The constr
construct
uctor
or that
that you will
will write
write will
will be a copy
constructor. It should use the parameter money object to make a duplicate
money object, by copying the valuevalue of each instance variable
variable from the parame-
ter object to the instance variable of the new object.
78 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Tas
ask
k #2
#2 Wr
Writ
itin
ing
g equals and toString methods
1. Write and
and doc ument an equals method. The method compares the instance
ocu
variables of the calling object with instance variables of the parameter object
for equality and returns true if the dollars and the cents of the calling object are
the same as the dollars and the cents of the parameter object. Otherwise, it
returns false.
2. Write and doc ument a toString method. This method will return a String
ocu
that looks like money,
money, including the dollar sign. Remember that if you have less
than 10 cents, you will need to put a 0 before printing the cents so that it
appears correctly with 2 decimal places.
3. Compiile
Comp le,, de
deb
bug
ug,, an
and
d tes
testt by
by run
runni
ning
ng the MoneyDriver.java driver program. You
should get the output:
The current amount is $500.00
Adding $10.02 gives $510.02
Subtracting $10.88 gives $499.14
$10.02 equals $10.02
$10.88 does not equal $10.02
Chapte
Chapterr 9 Lab Mor
Moree Clas
Classes
ses and Obj
Object
ectss 79
Task #3 Pass
Passing
ing and Retur
Returning
ning Object
Objectss
1. Create a Cred
Create CreditC
itCard
ard clas
classs accord
according
ing to
to the UML
UML Diagr
Diagram
am on the
the back.
back. It
It
should have data fields
fields that include an owner of type Person, a balance of type
Money,, and a creditLimit of type Money.
Money Money.
2. It shoul
should
d have
have a constr
constructo
uctorr that
that has
has two
two paramet
parameters
ers,, a Person
Person to
to initia
initializ
lizee the
owner and a Money value to initialize the creditLimit. The balance can be ini-
tialized to a Money value of zero. Remember you are passing in objects (pass
by reference), so you have passed in the address to an object. If you want your
CreditCard to have
have its own
own creditLimit and balance, you should create a new
object of each using the copy constructor in the Money class.
3. It shoul
should
d have
have access
accessor
or methods
methods to
to get the
the balance
balance and
and the ava
availa
ilable
ble credi
credit.
t.
Since these are objects (pass by reference), we don’t want
want to create an insecure
insecure
credit card by passing out addresses to components in our credit card, so we
must return a new object with the same values. Again, use the copy constructor
to create a new object of type money that can be returned.
4. It shoul
should
d have
have an
an access
accessor
or meth
method
od to get the
the info
informa
rmatio
tion
n about
about the
the owner
owner,, but
in the form of a String that can be printed out. This can be done by calling the
toString method for the owner (who is a Person).
5. It shoul
should d have
have a method
method that
that will
will char
charge
ge to the
the credi
creditt card
card by addin
adding
g the
amount of Money in the parameter to the balance if it will not exceed the credit
limit.. If the credit limit
limit limit will
will be exceeded, the amount should
should not be added, and
an error message can be printed to the console.
6. It shoul
should
d have
have a method
method that
that will
will mak
makee a paymen
paymentt on the
the credit
credit car
card
d by sub-
sub-
tracting the amount of Money in the parameter from the balance.
7. Compile
Compi le,, de
debu
bug,
g, an
and
d te
test
st it ou
outt com
compl
plet
etel
ely
y by ru
runni
nning
ng CreditCardDemo.java .
You should get the output:
Diane Christie, 237J Harvey Hall, Menomonie, WI 54751
Balance: $0.00
Credit Limit: $1000.00
Attempt to charge $200.00
Charge: $200.00
Balance: $200.00
Attempt to charge $10.02
Charge: $10.02
Balance: $210.02
Attempt to pay $25.00
Payment: $25.00
Balance: $185.02
Attempt to charge $990.00
Exceeds credit limit
Balance: $185.02
80 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
}
82 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
object are less than the dollars and the cents of the
parameter object, 0 if the dollars and the cents of the
calling object are equal to the dollars and cents of the
parameter object, and 1 if the dollars and the cents of the
calling object are more than the dollars and the cents of
the parameter object.*/
public int compareTo(Money amount)
{
int value;
if(this.dollars < amount.dollars)
{
value = -1;
}
else if (this.dollars > amount.dollars)
{
value = 1;
}
else if (this.cents < amount.dollars)
{
value = -1;
}
else if (this.cents > amount.cents)
{
value = 1;
}
else
{
value = 0;
}
return value;
}
}
Chapte
Chapterr 9 Lab Mor
Moree Clas
Classes
ses and Obj
Object
ectss 85
equal = THIRD_AMOUNT.equals(FIRST_AMOUNT);
if(equal)
System.out.println(THIRD_AMOUNT + " equals " +
FIRST_AMOUNT);
else
System.out.println(THIRD_AMOUNT +
" does not equal " + FIRST_AMOUNT);
}
}
86 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Objectives
• Use methods
methods of the
the Character
Character class and String
String class to process
process text
• Be able
able to use the
the StringT
StringTokeniz
okenizer
er and Strin
StringBuf
gBuffer
fer classe
classess
Introduction
In this lab we ask the user to enter a time in military time (24 hours). The program will
convert and display the equivalent conventional time (12 hour with AM or PM) for each
entry if it is a valid military time. An error message will be printed to the console if the
entry is not a valid military time.
Think about how you would convert any military time 00:00 to 23:59 into conven-
tional time. Also think about what would be valid military times. To be a valid time,
the data must have a specific form. First,
First, it should have exactly
exactly 5 characters. Next,
only digits are allowed
allowed in the first two and last two positions,
positions, and that a colon is
always used in the middle position. Next, we need to ensure that we never have over
23 hours or 59 minutes. This will require us to separate the substrings containing the
hours and minutes. WhenWhen converting from military time to conventional
conventional time, we only
have to worry
worry about times that have hours greater than 12, and we do not need to do
anything
anyth ing with the minutes
minutes at all. To
To convert,
convert, we will need to subtract
subtract 12, and put it
back together with the colon and the minutes, and indicate that it is PM. Keep in mind
that 00:00 in military time is 12:00 AM (midnight) and 12:00 in military time is 12:00
PM (noon).
We will need to use a variety of Character class and String class methods to vali-
date the data and separate it in order to process it. We will also use a Character class
method to allow the user to continue the program if desired.
The String Tokenizer class will allow us to process a text file in order to decode a
secret message. We will use the first letter of every 5th token read in from a file to
reveal the secret message.
88 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #1 Charac
Character
ter and
and String
String Class Method
Methodss
1. Copy the files Time.java (code listing 10.1) and TimeDemo.java (code listing
10.2) from www.aw
www.aw.com/cssupport
.com/cssupport or as directed by your instructor.
instructor.
2. In the Time.java file, add conditions to the decision structure
structure which validates
the data. Conditions are needed that will
a) Chec
Check k the
the leng
length
th of
of the
the stri
string
ng
b) Chec
Check k the
the positi
position
on of
of the
the colon
colon
c) Chec
Check k that all
all other
other chara
character
cterss are digi
digits
ts
3. Add lines
lines that
that will
will separat
separatee the strin
string
g into two
two subst
substrin
rings
gs contai
containin
ning
g hours
hours and
minutes. Convert these substrings to integers and save them into the instance
variables.
4. In the
the Time
TimeDem
Demo o class,
class, add a condi
conditio
tion
n to the
the loop
loop that
that con
conver
verts
ts the
the user’
user’ss
answer to a capital letter prior to checking it.
5. Compile,
Compil e, deb
debug,
ug, and run
run.. Test
Test out you
yourr progr
program
am usin
using
g the
the foll
follow
owing
ing va
valid
lid
input:
input: 00:
00:00,
00, 12:
12:00,
00, 04:0
04:05,
5, 10:
10:15,
15, 23:
23:59,
59, 00:
00:35,
35, and the fol
follo
lowin
wingg in
inva
valid
lid inp
input:
ut:
7:56
7:56,, 15
15:7
:78,
8, 08
08:6
:60,
0, 24
24:0
:00,
0, 3e
3e:3
:33,
3, 1:
1:11
111.
1.
Chapte
Chapterr 10 Lab Tex
extt Process
Processing
ing and
and Wrappe
Wrapperr Classes
Classes 89
Task #2 Strin
StringT
gTokeni
okenizer
zer and StringBuffer
StringBuffer classes
classes
}
//morning times don’t need converting
else
{
System.out.println(this.toString());
}
}
}
}
}
}
Chapte
Chapterr 10 Lab Tex
extt Process
Processing
ing and
and Wrappe
Wrapperr Classes
Classes 95
Objectives
• Be able
able to deri
derive
ve a class
class from
from anan existi
existing
ng class
class
• Be able to define
define a class
class hierar
hierarchy
chy in which methods
methods are overr
overridden
idden and
and fields
fields
are hidden
• Be abl
ablee to
to use
use der
deriv
ived-
ed-clas
classs obje
objects
cts
• Im
Impl
plem
ement
ent a cop
copyy cons
constr
truct
uctor
or
Introduction
In this lab, you will be creating new classes
classes that are derived
derived from a class called
BankAccount. A checking account is a bank account and a savings account is a bank
account as well. This sets up a relationship called inheritance, where BankAccount is
the superclass and CheckingAccount and SavingsAccount are subclasses.
This relationship allows CheckingAccount to inherit attributes from BankAccount
(likee owner,
(lik owner, balance, and accountNumber
accountNumber,, but it can have
have new attribu
attributes
tes that are spe-
spe-
cific to a checking account, like a fee for clearing a check. It
It also allows
allows
CheckingAccoun
Checki ngAccountt to inherit methods
methods from BankAccount,
BankAccount, like deposit,
deposit, that are univer-
univer-
sal for all bank accounts.
You will write a withdraw method in CheckingAccount that overrides the withdraw
method in BankAccount, in order to do something slightly different than the original
withdraw method.
You will use an instance variable called accountNumber in SavingsAccount to hide
the accountNumber variable inherited from BankAccount.
98 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
BankAccount
-balance:double
-owner:String
-accountNumber:String
#numberOfAccounts:int
+BankAccount():
+BankAccount(name:String,amount:double):
+BankAccount(oldAccount:BankAcc
+BankAccount(o ldAccount:BankAccount,amount:double):
ount,amount:double):
+deposit(amount:double):void
+withdraw(amount:double):boolean
+getBalance():double
+getOwner():String
+getAccountNumber():String
+setBalance(amount:double):void
+setAccountNumber(newAccountNumber:String):void
CheckingAccount SavingsAccount
-FEE:double -rate:double
-savingsNumber:int
+CheckingAccount(name:String, -accountNumber:String
amont:double):
+withdraw (amount:double):boolean +SavingsAccount(name:String,amount:double):
+SavingsAccount(oldAccount:SavingsAccount,
amont:double):
+postInterest():void
+getAccountNumber():String
Chap
Chapte
terr 11 La
Lab
b Inhe
Inheri
rita
tanc
ncee 99
Task #1
#1 Ext
Extend
ending
ing Bank
BankAcco
Account
unt
Task #2 Cr
Creati
eating
ng a Second
Second Subcl
Subclass
ass
1. Crea
Create
te a ne
new cla
classs cal
calle
led
d SavingsAccount that extends BankAccount .
2. It shou
should
ld cont
contai
ain
n an ins
insta
tance
nce va
vari
riab
able
le cal
called rate that represents the annual
led
interest rate. Set it equal to 2.5%.
3. It shou
should
ld als
also
o have
have an
an inst
instanc
ancee vari
variabl
ablee called savingsNumber , ini
called initia
tializ
lized
ed to
0. In this bank, you have one account
account number,
number, but can have
have several
several savings
savings
accounts with that same number. Each individual savings account is identified
by the number following a dash. For For example, 100001-0 is the first savings
account you open, 100001-1 would be another savings savings account that is still part
of your same account. This is so that you can keep some funds separate from
the others,
others, like a Christmas
Christmas club account.
account.
4. An in
inst
stan
ance
ce var
aria
iabl
blee ca
called accountNumber tha
lled thatt will
will hide
hide the
accountNumber from the superclass, should also be in this class.
5. Write a constr
Write construct
uctor
or that
that takes
takes a name
name and an an initia
initiall balance
balance as para
paramet
meters
ers and
and
calls the constructor for the superclass. It should initialize accountNumber
to be the current value in the superclass accountNumber (the hidden
instance variable) concatenated with a hyphen and then the savingsNumber.
6. Write a metho
hodd ca
called postInterest that has no parameters and returns no
value. This method will calculate one month’s worth of interest on the balance
and deposit it into the account.
7. Writee a me
Writ meth
thod
od th
that
at ov
over
erri
ride
dess th
thee getAccountNumber method in the super-
class.
8. Write a copy constructor that creates another savings
savings account for the same per-
son. It should take the original savings account and an initial balance as para-
meters. It should
should call the copy constructor
constructor of the superclass,
superclass, assign the
savingsNumber to be one more than the savingsNumber of the original
savings account. It should assign the accountNumber to be the
accountNumber of the superclass concatenated with the hypen and the
savingsNumber of the new account.
9. Comp
Compil
ilee and
and de
debu
bug
g thi
thiss cla
class
ss..
10. Use the
the Accoun
AccountDr
tDriv
iver
er class
class to test
test out your
your class
classes.
es. If you
you named
named and create
created
d
your classes and methods correctly,
correctly, it should not have any difficulties.
difficulties. If you
have errors, do not edit the AccountDriver class. You must make your classes
work with this program.
11. Running
Running the pro
progra
gram
m shoul
should
d give
give the
the foll
follow
owing
ing out
output
put::
Account Number 100001-10 belonging to Benjamin Franklin
Initial balance = $1000.00
After deposit of $500.00, balance = $1500.00
After withdrawal of $1000.00, balance = $499.85
Chap
Chapte
terr 11 La
Lab
b Inhe
Inheri
rita
tanc
ncee 101
DecimalFormat myFormat;
String money;
String money_in;
String money_out;
boolean completed;
money = myFormat.format(
myCheckingAccount.getBalance());
if (completed)
{
System.out.println ("After withdrawal of $" +
money_out + ", balance = $" + money);
}
else
{
System.out.println ("Insuffient funds to " +
" withdraw $" + money_out +
", balance = $" + money);
}
System.out.println();
/**default constructor*/
public BankAccount()
{
balance = 0;
accountNumber = numberOfAccounts + "";
numberOfAccounts++;
}
/**standard constructor
@param name the owner of the account
@param amount the beginning balance*/
public BankAccount(String name, double amount)
{
owner = name;
balance = amount;
accountNumber = numberOfAccounts + "";
numberOfAccounts++;
}
Objectives
• Be able
able to
to write
write code that han
handle
dless an excep
exceptio
tion
n
• Be ab
able
le to
to write
write code that thr
throw
owss an exc
except
eption
ion
• Be able
able to writ
writee a cust
custom
om exce
excepti
ption
on clas
classs
Introduction
This program will ask the user for a person’s name and social security number. The
program will then check to see if the social security number is valid. An exception will
be thrown if an invalid SSN is entered.
You will be creating your own exception class in this program. You will also create
a driver program that will use the exception class. Within the driver
driver program, you will
include a static method that throws
throws the exception. Note: Since you are creating all the
classes for this lab, there are no files on www
www.aw
.aw.com/cssupport.
.com/cssupport.
110 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #1 Writin
Writing
g a Custom Excepti
Exception
on Class
Class
1. Create an excep
Create exceptio
tion
n class
class called
called SocSec
SocSecExce
Excepti
ption.
on. The
The UML for
for this
this class
class is
is
below.
SocSec Exception
+SocSecException(Strin g error):
The constructor will call the superclass constructor. It will set the message associated
with the exception to “Invalid
“Invalid social security number” concatenated with the error
string.
2. Create
Create a dri
drive
verr pro
progr
gram
am ca
call
lled
ed SocSecProcessor.java. This program will have a
main method and a static method called isValid that will check if the social
security number is valid.
SocSecProcessor
+main(args:Strin g[ ]):
]):voi
void
d
+isValid(ssn:String):boolean
Chapte
Chapterr 12 Lab Exc
Except
eption
ionss and
and I/O
I/O Stre
Streams
ams 111
Task #2
#2 Writin
Writing
g Code to Handle
Handle an Exceptio
Exception
n
1. In tth
he ma
main me
method:
a) The main method shouldshould read
read a name and
and social
social security
security number
number from
from the
user as Strings.
b) The main method
method should
should contain a try-catc
try-catchh statement.
statement. This
This statement
statement tries
tries
to check if the social security number is valid by using the method isValid.
If the social security number is valid, it prints the name and social security
security
number. IfIf a SocSecException is thrown, it should catch it and print out the
name, social securit
security
y number entered,
entered, and an associated
associated error message
message indi-
indi-
cating why the social security number is invalid.
c) A loop should
should be used
used to allow
allow the
the user to
to continue
continue until
until the user
user indicates
indicates
that they do not want to continue.
2. The static isValid method:
a) Thi
Thiss method
method thro
throws
ws a SocSec
SocSecExce
Excepti
ption.
on.
b) Tr
Trueue is returne
returned d if the
the social
social security
security number is valid,
valid, fals
falsee otherwise.
otherwise.
c) The method
method checks for the the following
following errors
errors and
and throws
throws a SocSecExcept
SocSecException ion
with the appropriate message.
i) NumNumber ber of char
charact
acters
ers not equa
equall to 11. (Ju
(Just
st check
check the len
length
gth of the
the
string)
ii)) Da
ii Dashshes
es in th
thee wro
wrong
ng spspot
ots.
s.
iii)
ii i) An
Any y non-
non-di
digi
gits
ts in the
the SSN
SSN..
iv)) Hin
iv Hint:t: Use a loop
loop to step
step thro
through
ugh each
each char
characte
acterr of the str
string
ing,, chec
checking
king
for a digit or hyphen in the appropriate spots.
3. Compile
Compi le,, de
debu
bug,
g, an
and
d run your
your pro
progr
gram.
am. Sam
Sampl
plee output
output is
is show
shown
n below
below wit
with
h
user input in bold.
OUTPUT (boldface is user input)
Name? Sam Sly
SSN? 333-00-999
Invalid the social security number, wrong number of charac-
ters
Continue? y
Name? George Washington
SSN? 123-45-6789
George Washington 123-45-6789 is valid
Continue? y
Name? Dudley Doright
SSN? 222-00-999o
Invalid the social security number, contains a character
that is not a digit
Continue? y
112 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Objectives
• Be abl
ablee to
to add
add a menu
menu to th
thee menu
menu bar
• Be ab
able
le to us
usee nes
neste
ted
d men
menusus
• Be able
able to add scro
scroll
ll bars,
bars, gi
giving
ving the
the user
user the
the option
option of when
when they
they will
will be seen.
seen.
• Be able
able to chang
changee the look
look and
and feel,
feel, gi
givin
ving
g the user
user the
the optio
option
n of which
which look
look
and feel to use
Introduction
In this lab we will be creating a simple note taking interface. It is currently a working
program, but we will be adding features to it. The current program displays a window
which has one item on the menu bar, Notes, which allows
allows the user
user 6 choices. These
These
choices allow the user to store and retrieve up to 2 different notes. It also allows the
user to clear the text area or exit the program.
We would like to add features to this program which allows the user to change how
the user interface appears. We will be adding another choice on the menu bar called
Views, giving the user choices about scroll bars and the look and feel of the GUI.
114 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #1 Cr
Creati
eating
ng a Menu with
with Submen
Submenus
us
Task #2 Addin
Adding
g Scroll
Scroll Bars and Editin
Editing
g the Action Listener
Listener
1. Add scro
scroll
ll bars
bars to the
the text
text area
area by comple
completin
ting
g the foll
follow
owing
ing step
stepss in the
the con-
structor
a) Cre
Create
ate a JScrol
JScrollPa
lPane
ne object
object cal
called
led scrolledText , pas passi
sing
ng in theText .
b) Chan
Changege the line
line that
that adds
adds to the
the textP
textPanel
anel,, by passin
passing
g in scrolledText
(which now has theText .)
2. Edit the actio
Edit action
n listen
listener
er by addin
adding
g 6 more
more branches
branches to
to the else-
else-if
if logic
logic.. Each
branch will compare the actionCommand to the 6 submenu items: Metal,
Motif , Window, Never, Always, and As Needed.
a) Each Look and Feel submenu item will use a try-catch statement to set the
look and feel to the appropriate one, displaying an error message
message if this was
not accomplished.
b) Each Scroll Bars submenu item will set the horizontal and vertical scroll
bar policy to the appropriate values.
c) Any components
components that have
have already
already been created
created need
need to be updated.
updated. This
This
can be accomplished by calling the
SwingUtilities.updateComponentTreeUI method, passi passing
ng a reference
reference to
the component that you want to update as an argument. Specifically you
will need to add the line
SwingUtilities.updateComponentTreeUIgetContentPane());
to each branch that you just added to the logic structure.
Figure 1
116 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Figure 2
Figure 3
Chapte
Chapterr 13 Lab
Lab Advanc
Advanced
ed GUI
GUI App
Applic
licati
ations
ons 117
//objects in GUI
private JTextArea theText; //area to take notes
private JMenuBar mBar; //horizontal menu bar
private JPanel textPanel; //panel to hold scrolling text area
private JMenu notesMenu; //vertical menu with choices for notes
//default notes
private String note1 = "No Note 1.";
private String note2 = "No Note 2.";
/**constructor*/
public NoteTaker()
{
//create a closeable JFrame with a specific size
super("Note Taker");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
Code Listing 13.1 continued on next page.
118 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Objectives
• Be ab
able
le to wr
writ
itee an
an app
apple
lett
• Be ab
able
le to dr
draw
aw rerect
ctang
angle
les,
s, ci
circ
rcle
les,
s, and ar
arcs
cs
• Be abl
ablee to ove
overr
rrid
idee the
the pain
paintt meth
methodod
• Be ab
able
le to us
use a tim
imer
er
Introduction
In this lab we will create an applet that changes the light on a traffic signal. The applet
that you create will draw the outside rectangle of a traffic signal and fill it in with yel-
low.. Then it will
low will draw
draw three circles
circles in
in one column, to resemble
resemble the red,
red, orange, and
green lights on the traffic signal. Only one circle at a time will be filled in. It will start
will green
green and cycle through
through the orange,
orange, red, and back to green to start
start the cycle
cycle again.
However,, unlike a traffic
However traffic signal, each light will remain on for the
the same amount of time.
time.
To accomplish
accomplish this cycle, we will use
a timer object.
When you have finished your
applet should appear as shown in fig-
ure 1, but with
with the filled
filled in circle
cycling up from green to orange to
red and starting over in a continuous
changing of the traffic light.
122 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #1 Cr
Create
eate an Ap
Apple
plett
Tas
ask
k #2
#2 Th
Thee Ti
Time
merr
1. An appl
applet
et does
does not hav
havee a cons
constru
tructo
ctorr or a main
main meth
method.
od. Ins
Instea
tead,
d, it has
has a
method named init that performs the same operations as a constructor. The
init method accepts no arguments and has a void return type. Write an init
method.
2. Inside the init method, create a timer object passing in the TIME_DELA
TIME_DELAY Y
constant and a new TimerListener (We will be creating the listener class next).
3. Calll the star
Cal startt method
method with
with the
the timer
timer obje
object
ct to gene
generat
ratee action
action even
events.
ts.
124 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Task #3 The Ti
TimerL
merListe
istener
ner Class
Class
1. Write a priv
Write private
ate inner
inner clas
classs called
called Time
TimerLi
rListe
stener
ner which
which impl
impleme
ements
nts
ActionListener.
2. Inside this
Inside this clas
class,
s, wri
write
te an acti
actionP
onPerf
erform
ormed
ed metho
method.
d. This
This meth
method
od will
will check
check the
the
statuss variable
statu variable to see whether
whether it is currently
currently red, orange
orange,, or green. Since
Since we
want the lights
lights to cycle
cycle as a traffic
traffic signal,
signal, we need to cycle in the order:
order: green,
orange,
orange, red
red,, gre
green,
en, ora
orange,
nge, red
red,, … Once
Once the sta
status
tus is det
determ
ermine
ined,
d, the sta
status
tus
should then be set to the next color in the cycle.
3. Redispl
Redisplay
ay the
the graphi
graphics
cs compo
component
nentss (to
(to be creat
created
ed next)
next) by
by callin
calling
g the
repaint method.
Chap
Chapte
terr 14
14 Lab
Lab Appl
Applet
etss and
and Mo
More
re 125
Task #4 Dra
Drawin
wing
g Gra
Graphi
phics
cs
}
Chapter 15 Lab
Recursion
Objectives
• Be able
able to trac
tracee recur
recursi
sive
ve fun
functi
ction
on call
callss
• Be able to
to write
write non-recursi
non-recursive
ve and recursi
recursive
ve methods
methods to find
find geometric
geometric and
and har-
monic progressions
Introduction
In this lab we will follow how the computer executes recursive
recursive methods, and will write
our own recursive
recursive method, as well as the iterative
iterative equivalent. There are two common
progressions in mathematics, the geometric progression
progression and the harmonic progression.
The geometric progression is defined as the product of the first n integers. The har-
monic progression is defined as the product of the inverses of the first n integers.
Mathematically,, the definitions
Mathematically definitions are as follows
n n-1
Geometric (n) =
q
i 1
i
=
= i *
q
i 1
=
i
n n-1
1 1 1
Harmonic (n) =
q
i 1
=
i
=
i
*
q
i 1=
i
Task #2 Writing
Writing Recursive
Recursive and Iterative
Iterative Version
ersionss of a
Method
1. Copy the file Progression.java (see code listing 15.2) from www.aw.com/cssup-
www.aw.com/cssup-
port or as directed by your instructor.
2. You need to
to wr
write class (static) methods for an iterative and a recursive version
each of the progressions. You
You will have 4 methods,
metho ds, geometricRecursive ,
geometricIterative , harmonicRecursive , and
harmonicIterative . Be sure to match them to the method calls in the
main method.
130 Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects