Lab Manual JAVA EO
Lab Manual JAVA EO
2/14/06
1:59 PM
Page i
LAB MANUAL
to Accompany
Diane Christie
University of Wisconsin Stout
Christie_435966_LM
2/14/06
1:59 PM
Page ii
Publisher
Senior Acquisitions Editor
Editorial Assistant
Cover Designer
Marketing Manager
Marketing Assistant
Prepress and Manufacturing
Supplement Coordination
Proofreader
Greg Tobin
Michael Hirsch
Lindsey Triebel
Nicole Clayton
Michelle Brown
Dana Lopreato
Caroline Fell
Marianne Groth
Melanie Aswell
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and
Addison-Wesley was aware of a trademark claim, the designations have been printed in
initial caps or all caps.
Christie_435966_LM
2/14/06
1:59 PM
Page iii
Preface
About this Lab Manual
This lab manual accompanies Starting Out with Java 5: Early Objects, by Tony
Gaddis. Each lab gives students hands on experience with the major topics in each
chapter. It is designed for closed laboratoriesregularly scheduled classes supervised
by an instructor, with a length of approximately two hours. Lab manual chapters correspond to textbook chapters. Each chapter in the lab manual contains learning objectives, an introduction, one or two projects with various tasks for the students to complete, and a listing of the code provided as the starting basis for each lab. Labs are
intended to be completed after studying the corresponding textbook chapter, but prior
to programming challenges for each chapter in the textbook.
Students should copy the partially written code (available at www.aw.com/cssupport)
and use the instructions provided in each task to complete the code so that it is operational. Instructions will guide them through each lab having them add code at specified
locations in the partially written program. Students will gain experience in writing code,
compiling and debugging, writing testing plans, and finally executing and testing their
programs.
Note: Labs 10 and 11 are written entirely by the student using the instructions in
the various tasks, so there is no code provided as a starting basis.
Christie_435966_LM
iv
2/14/06
1:59 PM
Page iv
Supplementary Materials
Students can find source code files for the labs at www.aw.com/cssupport, under
author Christie and title Lab Manual to Accompany Starting Out with Java
5: Early Objects or Gaddis, Starting Out with Java 5: Early Objects.
Solution files and source code are available to qualified instructors at AddisonWesleys Instructor Resource Center. Register at www.aw.com/irc and search for
author 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 feedback on these labs to continue to improve them.
Most of all, I want to thank my family: Michael, Andrew, and Pamela for all of
their encouragement, patience, love, and support.
Christie_435966_LM
2/14/06
1:59 PM
Page v
Contents
Chapter 1 Lab
Chapter 2 Lab
Chapter 3 Lab
Chapter 4 Lab
Chapter 5 Lab
Chapter 6 Lab
Chapter 7 Lab
Chapter 8 Lab
Chapter 9 Lab
Chapter 10 Lab
Chapter 11 Lab
Chapter 12 Lab
Chapter 13 Lab
Chapter 14 Lab
1
9
21
31
45
57
69
77
87
99
103
109
117
123
Christie_435966_LM
2/14/06
1:59 PM
Page vi
Christie_435966_LM
2/14/06
1:59 PM
Page 1
Chapter 1 Lab
Algorithms, Errors, and Testing
Objectives
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 program. The example
calculates the users gross pay. It calculates the gross pay by multiplying the number of
hours worked by hourly pay rate. However, it is not always calculated this way. What
if you work 45 hours in a week? The hours that you worked over 40 hours are considered 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 users gross pay with or without 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 allowing 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 algorithm 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.
Christie_435966_LM
2/14/06
1:59 PM
Page 2
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 curly braces, etc.
2.
Logic Errorserrors in the logic of the algorithm. These errors emphasize the
need for a correct algorithm. If the statements are out of order, if there are
errors in a formula, or if there are missing steps, the program can still run and
give you output, but it may be the wrong output. Since there is no list of errors
for logic errors, you may not realize you have errors unless you check your output. It is very important to know what output you expect. You should test your
programs with different inputs, and know what output to expect in each case.
For example, if your program calculates your pay, you should check three different cases: less than 40 hours, 40 hours, and more than 40 hours. 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 errorserrors that do not occur until the program is run, and then
may only occur with some data. These errors emphasize the need for completely testing your program.
Christie_435966_LM
2/14/06
1:59 PM
Page 3
Chapter 1 Lab
Copy the file Pay.java (see code listing 1.1) from www.aw.com/cssupport or as
directed by your instructor.
2.
Open the file in your Java Integrated Development Environment (IDE) or a text
editor as directed by your instructor. Examine the file, and compare it with the
detailed version of the pseudocode in step number 3, section 1.6 of the textbook. Notice that the pseudocode does not include every line of code. The program code includes identifier declarations and a statement that is needed to
enable Java to read from the keyboard. These are not part of actually completing the task of calculating 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.
Display
Input
Display
Input
hours
"How much do you get paid per hour?"
rate
Christie_435966_LM
2/14/06
1:59 PM
Page 4
Compile the Pay.java using the Sun JDK or a Java IDE as directed by your
instructor.
2.
3.
When this program is executed, it will ask the user for input. You should calculate several different cases by hand. Since there is a critical point at which the
calculation changes, you should test three different cases: the critical 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 program using your first set of data. Record your result. You will
need to execute the program three times to test all your data. Note: you do not
need to compile again. Once the program compiles correctly once, it can be
executed many times. You only need to compile again if you make changes to
the code.
Hours
Rate
Christie_435966_LM
2/14/06
1:59 PM
Page 5
Chapter 1 Lab
Copy the file SalesTax.java (see code listing 1.2) from www.aw.com/cssupport
or as directed by your instructor.
2.
Open the file in your IDE or text editor as directed by your instructor. This file
contains a simple Java program that contains errors. Compile the program. You
should get a listing of syntax errors. Correct all the syntax errors, you may
want to recompile after you fix some of the errors.
3.
When all syntax errors are corrected, the program should compile. As in the
previous exercise, you need to develop some test data. Use the chart below to
record your test data and results when calculated by hand.
4.
Execute the program using your test data and recording the results. If the output
of the program is different 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.
Item
Price
Tax
Total (calculated)
Total (output)
Christie_435966_LM
2/14/06
1:59 PM
Page 6
Christie_435966_LM
2/14/06
1:59 PM
Page 7
Chapter 1 Lab
");
//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);
}
}
$");
$");
$");
Christie_435966_LM
2/14/06
1:59 PM
Page 8
Christie_435966_LM
2/14/06
1:59 PM
Page 9
Chapter 2 Lab
Java Fundamentals
Objectives
Introduction
This lab is designed to give you practice with some of the basics in Java. We will continue ideas from lab 1 by correcting logic errors while looking at mathematical formulas 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 to do certain operations, such as
raise a number to a power or use the number pi. Similarly, in Java, we will have programs 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 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 introduction 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.
Christie_435966_LM
10
2/14/06
1:59 PM
Page 10
Christie_435966_LM
2/14/06
1:59 PM
Page 11
Chapter 2 Lab
Java Fundamentals
2.
Compile the source file, run the program, and observe the output. Some 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 conversion between data types, order of operations, or formula problems. The necessary formulas are
average =
score1 + score2
numberOfScores
C =
5
(F - 32)
9
3.
Each time you make changes to the program code, you must compile again for
the changes to take effect before running the program again.
4.
Make sure that the output makes sense before you continue. The average of 95
and 100 should be 97.5 and the temperature that water boils is 100 degrees
Celsius
11
Christie_435966_LM
12
2/14/06
1:59 PM
Page 12
Add an import statement above the class declaration to make the Scanner class
available to your program.
2.
In the main method, create a Scanner object and connect it to the System.in
object.
3.
4.
Read the name from the keyboard using the nextLine method, and store it into
a variable called firstName (you will need to declare any variables you use).
5.
6.
Read the name from the keyboard and store it in a variable called lastName.
7.
Concatenate the firstName and lastName with a space between them and
store the result in a variable called fullName.
8.
9.
10.
Since we are adding on to the same program, each time we run the program we
will get the output from the previous tasks before the output of the current task.
Christie_435966_LM
2/14/06
1:59 PM
Page 13
Chapter 2 Lab
Java Fundamentals
Add an import statement above the class declaration to make the JOptionPane
class available to your program.
2.
In the main method, prompt the user to enter his/her first name by displaying
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 user to enter his/her last name by displaying an input dialog box
and storing the user input in a variable called lastName.
4.
Concatenate the firstName and lastName with a space between them and
store the result in a variable called fullName.
5.
6.
7.
Since we are adding on to the same program, each time we run the program we
will get the output from the previous tasks before the output of the current task.
13
Christie_435966_LM
14
2/14/06
1:59 PM
Page 14
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.
3.
Use the toUpperCase method to change the fullName to all capitals and store
it back into the fullName variable
4.
Add a line that prints out the value of fullName and how many characters
(including the space) are in the string stored in fullName (use the method
length to obtain that information).
5.
Compile, debug, and run. The new output added on after the output from the
previous tasks should have your initials and your full name in all capital letters.
Christie_435966_LM
2/14/06
1:59 PM
Page 15
Chapter 2 Lab
Java Fundamentals
Add a line that prompts the user to enter the diameter of a sphere.
2.
Read in and store the number into a variable called diameter (you will need to
declare any variables that you use).
3.
The diameter is twice as long as the radius, so calculate and store the radius in
an appropriately named variable.
4.
4 3
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.
6.
Compile, debug, and run using the following test data and record the results.
Diameter
2
25.4
875,000
15
Christie_435966_LM
16
2/14/06
1:59 PM
Page 16
2.
3.
4.
Translate the algorithm below into Java. Dont forget to declare variables
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.
6.
Run the program and test it using the following sets of data and record the
results:
Miles driven
Gallons used
2000
100
500
25.5
241.5
10
100
7.
The last set of data caused the computer to divide 100 by 0, which resulted 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.
Christie_435966_LM
2/14/06
1:59 PM
Page 17
Chapter 2 Lab
Java Fundamentals
2.
Write a comment line at the top of the program which indicates the purpose of
the program.
3.
Write a second comment line at the top of the program with your name and
todays date.
4.
Add comment lines after each variable declaration, indicating what each variable represents.
5.
Add comment lines for each section of the program, indicating what is done in
that section.
6.
17
Christie_435966_LM
18
2/14/06
1:59 PM
Page 18
Christie_435966_LM
2/14/06
1:59 PM
Page 19
Chapter 2 Lab
System.out.println(output);
System.out.println();
//
//
//
//
//
//
//
}
}
System.out.println();
//
//
//
//
//
//
System.out.println();
//
//
//
//
//
//
Java Fundamentals
19
Christie_435966_LM
2/14/06
1:59 PM
Page 20
Christie_435966_LM
2/14/06
1:59 PM
Page 21
Chapter 3 Lab
Classes and Methods
Objectives
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 televisions 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 televisions 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 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 television is showing.
volume. The volume attribute will hold a number value representing the loudness (0 being no sound).
Christie_435966_LM
22
2/14/06
1:59 PM
Page 22
Television
-MANUFACTURER: String
! -SCREEN_SIZE: int
-powerOn: boolean
-channel: int
! -volume: int
! +Television(brand: String, size: int):
+setChannel (station: int): void
+power( ): void
!
+increaseVolume( ): void
+decreaseVolume( ): void
! +getChannel( ): int
+getVolume( ): int
! +getManufacturer( ): String
+getScreenSize( ): int
Class Name
Attributes or fields
Methods
+ public
private
Data type returned
Christie_435966_LM
2/14/06
1:59 PM
Page 23
Chapter 3 Lab
2.
3.
4.
5.
6.
7.
23
Christie_435966_LM
24
2/14/06
1:59 PM
Page 24
2.
Inside the constructor, assign the values taken in from the parameters to the
corresponding fields.
3.
Initialize the powerOn field to false (power is off), the volume to 20, and the
channel to 2.
4.
Write comments describing the purpose of the constructor above the method
header.
5.
Christie_435966_LM
2/14/06
1:59 PM
Page 25
Chapter 3 Lab
Task #3 Methods
1.
2.
3.
Define a mutator method called power that changes the state from true to
false or from false to true. This can be accomplished by using the NOT operator (!). If the boolean variable powerOn is true, then !powerOn is false
and vice versa. Use the assignment statement
powerOn = !powerOn;
to change the state of powerOn and then store it back into powerOn (remember
assignment statements evaluate the right hand side first, then assign the result to
the left hand side variable.
4.
Define two mutator methods to change the volume. One method should 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 comments above each method header describing the purpose of the
method.
6.
25
Christie_435966_LM
26
2/14/06
1:59 PM
Page 26
You can only execute (run) a program that has a main method, so there is a driver program that is already written to test out your Television class. Copy
the file TelevisionDemo.java (see code listing 3.1) from www.aw.com/cssupport
or as directed by your instructor. Make sure it is in the same directory as
Television.java.
2.
3.
If your output matches the output below, Television.java is complete and correct. You will not need to modify it further for this lab.
Christie_435966_LM
2/14/06
1:59 PM
Page 27
Chapter 3 Lab
2.
3.
4.
5.
6.
Use calls to the accessor methods to print what television was turned on.
7.
Use calls to the mutator methods to change the channel to the users preference and decrease the volume by two.
8.
Use calls to the accessor methods to print the changed state of the portable.
9.
10.
11.
The output for task #5 will appear after the output from above, since we added
onto the bottom of the program. The output for task #5 is shown below.
27
Christie_435966_LM
28
2/14/06
1:59 PM
Page 28
Christie_435966_LM
2/14/06
1:59 PM
Page 29
Chapter 3 Lab
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
//HERE IS WHERE YOU DO TASK #5
}
}
29
Christie_435966_LM
2/14/06
1:59 PM
Page 30
Christie_435966_LM
2/14/06
1:59 PM
Page 31
Chapter 4 Lab
Selection Control Structures
Objectives
Introduction
Up to this point, all the programs you have had a sequential control structure. This
means that all statements are executed in order, one after 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 operators and logical operators to create a condition that can be evaluated as true or false.
Once we have a condition, we can conditionally execute statements. This means
that there are statements in the program that may or may not be 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 user desires. It walks the user through ordering, giving the
user choices, which the program then uses to decide how to make 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.
Christie_435966_LM
32
2/14/06
1:59 PM
Page 32
Copy the files Pizza.java (see code listing 4.1) and PizzaOrder.java (see code
listing 4.2) from www.aw.com/cssupport or as directed by your instructor.
Make sure to place them both in the same directory.
2.
Pizza.java is correct, so you will not be editing this file. You only need to compile it. Compile and run PizzaOrder.java. You will be able to make selections,
but at this point, you will always get a 12 inch Hand-tossed pizza no matter
what you select, but you will be able to choose toppings. 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 a simple if statement. The condition will compare the String input by
the user as his/her first name with the first names of the owners, Mike and
Diane. Be sure that the comparison is not case sensitive.
4.
If the user has either first name, set the discount flag to true.
Christie_435966_LM
2/14/06
1:59 PM
Page 33
Chapter 4 Lab
Write an if-else-if statement that lets the computer choose which statements to
execute by the user input size (10, 12, 14, or 16). For each option, two statements need to be executed:
a) A call to the setSize method passing in the size indicated.
b) A call to the setCost method passing in the appropriate adjustment. Notice
that in the Pizza.java program, the constructor creates a 12 inch Handtossed pizza for $12.99. The setCost method adjusts the cost, so a 10 inch
pizza will need its cost decreased by 2, while the 16 inch pizza cost will
need to increase by 4.
2.
The default else of the above if-else-if statement should print a statement that
the user input was not one of the choices, so a 12 inch pizza will be made.
3.
Compile, debug, and run. You should now be able to get correct output for size
and price (it will still have Hand-tossed crust, the output wont look like money,
and no discount will be applied yet). Run your program multiple times ordering
a 10, 12, 14, 16, and 17 inch pizza.
33
Christie_435966_LM
34
2/14/06
1:59 PM
Page 34
Write a switch statement that compares the users choice with the appropriate
characters (make sure that both capital letters and small letters will work).
2.
Each case will call the setCrust method passing in the appropriate String indicating crust type.
3.
The default case will print a statement that the user input was not one of the
choices, so a Hand-tossed crust will be made.
4.
Compile, debug, and run. You should now be able to get crust types other than
Hand-tossed. Run your program multiple times to make sure all cases of the
switch statement operate correctly.
Christie_435966_LM
2/14/06
1:59 PM
Page 35
Chapter 4 Lab
Write an if statement that uses the flag as the condition. Remember that the
flag is a Boolean variable, therefore is true or false. It does not have to be compared to anything.
2.
3.
Compile, debug, and run. Test your program using the owners names (both
capitalized and not) as well as a different name. The discount should be correctly at this time.
35
Christie_435966_LM
36
2/14/06
1:59 PM
Page 36
Add an import statement to use the DecimalFormat class as indicated above the
class declaration.
2.
3.
Edit the appropriate lines in the main method so that any monetary output has 2
decimal places.
4.
Compile, debug, and run. Your output should be completely correct at this time,
and numeric output should look like money.
Christie_435966_LM
2/14/06
1:59 PM
Page 37
Chapter 4 Lab
Pizza
double cost;
String crust;
int size;
int numToppings;
String toppingList;
37
Christie_435966_LM
38
2/14/06
1:59 PM
Page 38
Christie_435966_LM
2/14/06
1:59 PM
Page 39
Chapter 4 Lab
return numToppings;
}
//returns the list of toppings
public String getToppingList()
{
return toppingList;
}
}
39
Christie_435966_LM
40
2/15/06
8:07 AM
Page 40
Christie_435966_LM
2/14/06
1:59 PM
Page 41
Chapter 4 Lab
41
Christie_435966_LM
42
2/14/06
1:59 PM
Page 42
Christie_435966_LM
2/14/06
1:59 PM
Page 43
Chapter 4 Lab
43
Christie_435966_LM
2/14/06
1:59 PM
Page 44
Christie_435966_LM
2/14/06
1:59 PM
Page 45
Chapter 5 Lab
Loops and Files
Objectives
Introduction
This is a simulation of rolling dice. Actual results approach theory only when the sample 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, the numbers will vary a little each time you run it.
Check out the Dice class to see how the random number generator (introduced in
section 4.13 of the text) works to create the simulation.
We will continue to use control structures that we have already learned, while
exploring control structures used for repetition. We shall also continue our work with
algorithms, translating a given algorithm to java in order to complete our program. We
will start with a while loop, then use the same program, changing the while loop to a
do-while loop, and then a for loop.
We will be introduced to file input and output. We will read a file, line by line, converting 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 input to read the numbers from a file and calculate the mean. Finally, we
will see that when the file is closed, and then reopened, we will start reading from the
top of the file again so that we can calculate the standard deviation.
Christie_435966_LM
46
2/14/06
1:59 PM
Page 46
Copy the files Dice.java (see code listing 5.1) and DiceSimulation.java (see
code listing 5.2) from www.aw.com/cssupport or as directed by your instructor.
Make sure to place them both in the same directory. You can compile both programs. Dice.java is complete and will not be modified in this lab, but
DiceSimulation.java is incomplete. Since there is a large part of the program
missing, the output will be incorrect if you run DiceSimulation.java.
2.
You will be modifying the DiceSimulation class only. I have declared all the
variables. You need to add what the method does. Convert the algorithm below
to Java and place it in the main method after the variable declarations, but
before the output statements. You will be using several control structures: a
while loop and an if-else-if statement nested inside another if statement. Use
the indenting of the algorithm to help you decide what is included in the loop,
what is included in the if statement, and what is included in the nested if-else-if
statement.
Repeat while the number of dice rolls are less than the number of times the dice should
be rolled.
Roll the first die
Get the value of the first die
Roll the second die
Get the value of 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
3.
Compile and run. You should get numbers that are somewhat close to 278 for
each of the different pairs of doubles. Run it several times. You should get different results than the first time, but again it should be somewhat close to 278.
Christie_435966_LM
2/14/06
1:59 PM
Page 47
Chapter 5 Lab
Change the while loop to a do-while loop. Compile and run. You should get the
same results.
2.
Change the do loop to a for loop. Compile and run. You should get the same
results.
47
Christie_435966_LM
48
2/14/06
1:59 PM
Page 48
Copy the files FileStats.java (see code listing 5.3) and Numbers.txt from
www.aw.com/cssupport or as directed by your instructor. You can compile
FileStats.java. It will compile without errors so that you can use it to test out
the StatsDemo class you will be creating.
2.
Create a class called StatsDemo which consists of a main method to do the following:
a) Create a DecimalFormat object so that we can format our numbers for output with 3 decimal places (Dont forget the needed import statement).
b) Create a Scanner object to get the file name input from the user (Dont forget the needed import statement).
c) Prompt the user and read in the file name (Remember to declare any needed
variables).
d) Create a FileStats object passing it the file name.
e) Create a FileWriter object passing it the filename Results.txt (Dont forget the needed import statement).
f) Create a PrintWriter object passing it the FileWriter object.
g) Since you are using a FileWriter object, add a throws clause to the main
method header.
h) Print the mean and standard deviation to the output file using a three decimal format, labeling each.
i) Close the output file.
3.
Compile, debug, and run. 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, standard deviation = 0.000. This
is not the correct mean or standard deviation for the data, but we will fix this in
the next tasks.
Christie_435966_LM
2/14/06
1:59 PM
Page 49
Chapter 5 Lab
Open FileStats.java for editing. You will notice that the calculateMean and
calculateStdDev methods do not do any calculations yet. They simply return a 0
to the constructor to initialize the instance variables. We need to add lines to
each of these methods to have them return the correct value. Lets work with
the calculateMean method first.
2.
Create a FileReader object passing it the filename (Dont forget the needed
import statement).
3.
4.
Since you are using a FileReader object, add a throws clause to the
calculateMean method header as well as the constructor method header (since it
calls the calculateMean method).
5.
6.
7.
Write a loop that continues until you are at the end of the file.
8.
9.
When the program exits the loop close the input file.
10.
Calculate and return the mean instead of 0. The mean is calculated by dividing
the accumulator by the counter.
11.
Compile, debug, and run. You should now get a mean of 77.444, but the standard deviation will still be 0.000.
49
Christie_435966_LM
50
2/14/06
1:59 PM
Page 50
Do steps 2-7 as above in the calculateMean method but add another local variable called difference of type double.
2.
3.
When the program exits the loop close the input file.
4.
5.
Compile, debug, and run. You should get a mean of 77.444 and standard deviation of 10.021.
Christie_435966_LM
2/14/06
1:59 PM
Page 51
Chapter 5 Lab
51
Christie_435966_LM
52
2/14/06
1:59 PM
Page 52
on the first
on the second
the dice were
snake eyes
double two is
double three
double four
double
double six is
Christie_435966_LM
2/14/06
1:59 PM
Page 53
Chapter 5 Lab
53
Christie_435966_LM
54
2/14/06
1:59 PM
Page 54
Christie_435966_LM
2/14/06
1:59 PM
Page 55
Chapter 5 Lab
//returns the calculated standard deviation
public double calculateStdDev(String filename)
{
//ADD LINES FOR TASK 5
return 0;
}
}
55
Christie_435966_LM
2/14/06
1:59 PM
Page 56
Christie_435966_LM
2/14/06
1:59 PM
Page 57
Chapter 6 Lab
More Classes and Objects
Objectives
Introduction
We discussed objects in Chapter 3 and we modeled a television in the Chapter 3 lab.
We want build on that lab, and work more with objects. This time, the object that we
are choosing is more complicated. It is made up of other objects. This is called aggregation. 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, 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 would 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 the CreditCard has a Person, which means aggregation, and the Person
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 class, Money. We will investigate overloading methods by writing another constructor method. 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.
Next, we will write equals and toString methods. These are very common
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.
After we have finished the Money class, we will write a CreditCard class. This
class contains Money objects, so you will use the methods that you have written to
complete the Money class. The CreditCard class will explore passing objects and the
possible security problems associated with it. We will use the copy constructor we
wrote for the Money class to create new objects with the same information to return to
the user through the accessor methods.
Christie_435966_LM
58
2/14/06
1:59 PM
Page 58
Credit Card
-balance:Money
-creditLimit:Money
-owner:Person
+CreditCard(newCardHolder:Person, limit:Money):
+getBalance():Money
+getCreditLimit():Money
+getPersonals():String
+charge(amount:Money):void
+payment(amount:Money):void
Money
-dollars:long
-cents:long
+Money(anount:double):
+Money(otherObject:Money):
+add(otherAmount:Money):Money
+subtract(otherAmount:Money):Money
+compareTo(otherObject:Money):int
+equals(otherObject:Money):boolean
+toString():String
Person
-lastName:String
-firstName:String
-home:Address
+toString():String
Address
-street:String
-city:String
-state:String
-zip:String
+toString():String
Christie_435966_LM
2/14/06
1:59 PM
Page 59
Chapter 6 Lab
Copy the files Address.java (code listing 6.1), Person.java (code listing 6.2),
Money.java (code listing 6.3), MoneyDriver.java (code listing 6.4), and
CreditCardDemo.java (code listing 6.5) from www.aw.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 the constructor. The constructor that you will write will be a copy
constructor. It should use the parameter money object to make a duplicate
money object, by copying the value of each instance variable from the parameter object to the instance variable of the new object.
59
Christie_435966_LM
60
2/14/06
1:59 PM
Page 60
Write and document an equals method. The method compares the instance
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 document a toString method. This method will return a String
that looks like 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.
Compile, debug, and test by running 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
Christie_435966_LM
2/14/06
1:59 PM
Page 61
Chapter 6 Lab
2.
It should have a constructor that has two parameters, a Person to initialize the
owner and a Money value to initialize the creditLimit. The balance can be initialized 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 its own creditLimit and balance, you should create a new
object of each using the copy constructor in the Money class.
3.
It should have accessor methods to get the balance and the available credit.
Since these are objects (pass by reference), we dont want to create an 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 should have an accessor method to get the information about the 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 should have a method that will charge to the credit card by adding the
amount of Money in the parameter to the balance if it will not exceed the credit
limit. If the credit limit will be exceeded, the amount should not be added, and
an error message can be printed to the console.
6.
It should have a method that will make a payment on the credit card by subtracting the amount of Money in the parameter from the balance.
7.
61
Christie_435966_LM
62
2/14/06
1:59 PM
Page 62
Christie_435966_LM
2/14/06
1:59 PM
Page 63
Chapter 6 Lab
63
Christie_435966_LM
64
2/14/06
1:59 PM
Page 64
Christie_435966_LM
2/14/06
1:59 PM
Page 65
Chapter 6 Lab
return sum;
}
//Subtracts the parameter Money object from the calling
//Money
//object and returns the difference.
public Money subtract (Money amount)
{
Money difference = new Money(0);
if (this.cents < amount.cents)
{
this.dollars = this.dollars - 1;
this.cents = this.cents + 100;
}
difference.dollars = this.dollars - amount.dollars;
difference.cents = this.cents - amount.cents;
return difference;
}
//Compares instance variable of the calling object
//with the parameter object. It returns -1 if the
//dollars and the cents of the calling 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;
}
Code Listing 6.3 continued on next page.
65
Christie_435966_LM
66
2/14/06
1:59 PM
Page 66
Christie_435966_LM
2/14/06
1:59 PM
Page 67
Chapter 6 Lab
67
Christie_435966_LM
68
2/14/06
1:59 PM
Page 68
Christie_435966_LM
2/14/06
1:59 PM
Page 69
Chapter 7 Lab
Arrays
Objectives
Introduction
Everyone is familiar with a list. We make shopping lists, to-do lists, assignment lists,
birthday lists, etc. Notice that though there may be many items on the list, we call the
list by one name. That is the idea of the array, one name for a list of related items. In
this lab, we will work with lists in the form of an 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 complicated arrays, arrays that contain objects.
Christie_435966_LM
70
2/14/06
1:59 PM
Page 70
Christie_435966_LM
2/14/06
1:59 PM
Page 71
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, debug, and run the program. It should output the data set from highest
to lowest and the mean. Compare the computers output to your hand calculation using a calculator. If they are not the same, do not continue until you correct your code.
71
Christie_435966_LM
72
2/14/06
1:59 PM
Page 72
Copy the files Song.java (code listing 7.1), CompactDisc.java (code listing 7.2)
and Classics.txt (code listing 7.3) from www.aw.com/cssupport or as directed
by your 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 you will be editing.
2.
3.
Fill the array by creating a new song with the title and artist and storing it in
the appropriate position in the array.
4.
5.
Christie_435966_LM
2/14/06
1:59 PM
Page 73
73
Christie_435966_LM
74
2/14/06
1:59 PM
Page 74
Christie_435966_LM
2/14/06
1:59 PM
Page 75
Chapter 7 Lab
Arrays
75
Christie_435966_LM
2/14/06
1:59 PM
Page 76
Christie_435966_LM
2/14/06
1:59 PM
Page 77
Chapter 8 Lab
Text Processing and Wrapper Classes
Objectives
Use methods of the Character class and String class to process text
Be able to use the StringTokenizer and StringBuffer classes
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 conventional time. Also think about what would be valid military times. To be a valid time,
the data must have a specific form. First, it should have exactly 5 characters. Next,
only digits are allowed in the first two and last two 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. When converting from military time to conventional time, we only
have to worry about times that have hours greater than 12, and we do not need to do
anything with the minutes at all. To convert, we will need to 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 validate 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.
Christie_435966_LM
78
2/14/06
1:59 PM
Page 78
Copy the files Time.java (code listing 8.1) and TimeDemo.java (code listing
8.2) from www.aw.com/cssupport or as directed by your instructor.
2.
In the Time.java file, add conditions to the decision structure which validates
the data. Conditions are needed that will
a) Check the length of the string
b) Check the position of the colon
c) Check that all other characters are digits
3.
Add lines that will separate the string into two substrings containing hours and
minutes. Convert these substrings to integers and save them into the instance
variables.
4.
In the TimeDemo class, add a condition to the loop that converts the users
answer to a capital letter prior to checking it.
5.
Compile, debug, and run. Test out your program using the following valid
input: 00:00, 12:00, 04:05, 10:15, 23:59, 00:35, and the following invalid input:
7:56, 15:78, 08:60, 24:00, 3e:33, 1:111.
Christie_435966_LM
2/14/06
1:59 PM
Page 79
Chapter 8 Lab
2.
Write a main method that will read the file secret.txt, separate it into word
tokens.
3.
You should process the tokens by taking the first letter of every fifth word,
starting with the first word in the file. These letters should converted to capitals,
then be appended to a StringBuffer object to form a word which will be printed
to the console to display the secret message.
79
Christie_435966_LM
80
2/14/06
1:59 PM
Page 80
Christie_435966_LM
2/14/06
1:59 PM
Page 81
Chapter 8 Lab
81
Christie_435966_LM
82
2/14/06
1:59 PM
Page 82
Christie_435966_LM
2/14/06
1:59 PM
Page 83
Chapter 8 Lab
String am_pm;
String zero = "";
if (afternoon)
am_pm = "PM";
else
am_pm = "AM";
if (minutes < 10)
zero = "0";
return hours + ":" + zero + minutes + " " + am_pm;
}
}
83
Christie_435966_LM
84
2/14/06
1:59 PM
Page 84
Christie_435966_LM
2/14/06
1:59 PM
Page 85
Chapter 8 Lab
Violet is a
85
Christie_435966_LM
2/14/06
1:59 PM
Page 86
Christie_435966_LM
2/14/06
1:59 PM
Page 87
Chapter 9 Lab
Inheritance, Polymorphism, and Scope
Objectives
Be able to derive a class from an existing class
Be able to define a class hierarchy in which methods are overridden and fields
are hidden
Be able to use derived-class objects
Implement a copy constructor
Introduction
In this lab, you will be creating new classes that are 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
(like owner, balance, and accountNumber, but it can have new attributes that are specific to a checking account, like a fee for clearing a check. It also allows
CheckingAccount to inherit methods from BankAccount, like deposit, that are universal 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.
Christie_435966_LM
88
2/14/06
1:59 PM
Page 88
BankAccount
-balance:double
-owner:String
-accountNumber:String
#numberOfAccounts:int
+BankAccount():
+BankAccount(name:String,amount:double):
+BankAccount(oldAccount:BankAccount,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
-FEE:double
+CheckingAccount(name:String,
amont:double):
+withdraw (amount:double):boolean
SavingsAccount
-rate:double
-savingsNumber:int
-accountNumber:String
+SavingsAccount(name:String,amount:double):
+SavingsAccount(oldAccount:SavingsAccount,
amont:double):
+postInterest():void
+getAccountNumber():String
Christie_435966_LM
2/14/06
1:59 PM
Page 89
Chapter 9 Lab
2.
3.
It should contain a static constant FEE that represents the cost of clearing one
check. Set it equal to 15 cents.
4.
5.
Write a new instance method, withdraw, that overrides the withdraw method in
the superclass. This method should take the amount to withdraw, add to it the
fee for check clearing, and call the withdraw method from the superclass.
Remember that to override the method, it must have the same method heading.
Notice that the withdraw method from the superclass returns true or false
depending if it was able to complete the withdrawal or not. The method that
overrides it must also return the same true or false that was returned from the
call to the withdraw method from the superclass.
6.
89
Christie_435966_LM
90
2/14/06
1:59 PM
Page 90
2.
It should contain an instance variable called rate that represents the annual
interest rate. Set it equal to 2.5%.
3.
4.
5.
Write a constructor that takes a name and an initial balance as parameters 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.
7.
8.
Write a copy constructor that creates another savings account for the same person. It should take the original savings account and an initial balance as parameters. It should call the copy constructor of the 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.
10.
Use the AccountDriver class to test out your classes. If you named and created
your classes and methods correctly, it should not have any difficulties. If you
have errors, do not edit the AccountDriver class. You must make your classes
work with this program.
11.
Christie_435966_LM
2/14/06
1:59 PM
Page 91
Chapter 9 Lab
91
Christie_435966_LM
92
2/14/06
1:59 PM
Page 92
Christie_435966_LM
2/14/06
1:59 PM
Page 93
Chapter 9 Lab
money_out = myFormat.format(take_out);
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();
//to test the savings account class
SavingsAccount yourAccount =
new SavingsAccount ("William Shakespeare", 400);
System.out.println ("Account Number "
+ yourAccount.getAccountNumber() +
" belonging to " + yourAccount.getOwner());
money = myFormat.format(yourAccount.getBalance());
System.out.println ("Initial balance = $" + money);
yourAccount.deposit (put_in);
money_in = myFormat.format(put_in);
money = myFormat.format(yourAccount.getBalance());
System.out.println ("After deposit of $" + money_in
+ ", balance = $" + money);
completed = yourAccount.withdraw(take_out);
money_out = myFormat.format(take_out);
money = myFormat.format(yourAccount.getBalance());
if (completed)
{
System.out.println (
"After withdrawal of $" +
money_out
+ ", balance = $" + money);
}
else
Code Listing 9.1 continued on next page.
93
Christie_435966_LM
94
2/14/06
1:59 PM
Page 94
Christie_435966_LM
2/14/06
1:59 PM
Page 95
Chapter 9 Lab
{
System.out.println (
"Insuffient funds to withdraw $"
+ money_out + ", balance = $" + money);
}
System.out.println();
//to test to make sure new accounts are numbered
//correctly
CheckingAccount yourCheckingAccount =
new CheckingAccount ("Isaac Newton", 5000);
System.out.println ("Account Number "
+ yourCheckingAccount.getAccountNumber()
+ " belonging to "
+ yourCheckingAccount.getOwner());
}
}
95
Christie_435966_LM
96
2/14/06
1:59 PM
Page 96
Christie_435966_LM
2/14/06
1:59 PM
Page 97
Chapter 9 Lab
accountNumber = oldAccount.accountNumber;
}
//allows you to add money to the account
public void deposit(double amount)
{
balance = balance + amount;
}
//allows you to remove money from the account if
//enough money is available
//returns true if the transaction was completed
//returns false if the there was not enough money
public boolean withdraw(double amount)
{
boolean completed = true;
if (amount <= balance)
{
balance = balance - amount;
}
else
{
completed = false;
}
return completed;
}
//accessor method to balance
public double getBalance()
{
return balance;
}
//accessor method to owner
public String getOwner()
{
Code Listing 9.2 continued on next page.
97
Christie_435966_LM
98
2/14/06
1:59 PM
Page 98
Christie_435966_LM
2/14/06
1:59 PM
Page 99
Chapter 10 Lab
Exceptions and I/O Streams
Objectives
Be able to write code that handles an exception
Be able to write code that throws an exception
Be able to write a custom exception class
Introduction
This program will ask the user for a persons 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 program, you will
include a static method that throws the exception. Note: Since you are creating all the
classes for this lab, there are no files on www.aw.com/cssupport associated with this lab.
Christie_435966_LM
100
2/14/06
1:59 PM
Page 100
Create an exception class called SocSecException. The UML for this class is
below.
SocSecException
+SocSecException(String error):
The constructor will call the superclass constructor. It will set the message associated
with the exception to Invalid social security number concatenated with the error
string.
2.
Christie_435966_LM
2/14/06
1:59 PM
Page 101
Chapter 10 Lab
2.
3.
Compile, debug, and run your program. Sample output is shown below with
user input in bold.
OUTPUT (boldface is user input)
Name? Sam Sly
SSN?
333-00-999
Invalid the social security number, wrong number of
characters
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
101
Christie_435966_LM
102
2/14/06
1:59 PM
Page 102
Christie_435966_LM
2/14/06
1:59 PM
Page 103
Chapter 11 Lab
GUI Applications
Objectives
Introduction
In this lab, we will be creating a graphical user interface (GUI) to 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 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
Christie_435966_LM
104
2/14/06
1:59 PM
Page 104
2.
3.
Create named constants for a width of 500 and height of 300 for the frame.
4.
Christie_435966_LM
2/14/06
1:59 PM
Page 105
Chapter 11 Lab
GUI Applications
2.
Create a bottom panel in the same way as the top panel above, but use radio
buttons with the colors green, blue, and cyan.
105
Christie_435966_LM
106
2/14/06
1:59 PM
Page 106
Christie_435966_LM
2/14/06
1:59 PM
Page 107
Chapter 11 Lab
GUI Applications
Write a main method that declares and creates one instance of a ColorFactory,
then use the setVisible method to show it on the screen.
107
Christie_435966_LM
2/14/06
1:59 PM
Page 108
Christie_435966_LM
2/14/06
1:59 PM
Page 109
Chapter 12 Lab
GUI ApplicationsPart 2
Objectives
Be able to add a menu to the menu bar
Be able to use nested menus
Be able to add scroll bars, giving the user the option of when they will be seen
Be able to change the look and feel, giving the user the option of which 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 the user 6 choices. 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.
Christie_435966_LM
110
2/14/06
1:59 PM
Page 110
2.
Compile and run the program. Observe the horizontal menu bar at the top
which has only one menu choice, Notes. We will be adding an item to this
menu bar called Views that has two submenus. One named Look and Feel and
one named Scroll Bars. The submenu named Look and Feel lets the user
change the look and feels: Metal, Motif, and Windows. The submenu named
Scroll Bars offers the user three choices: Never, Always, and As Needed.
When the user makes a choice, the scroll bars are displayed according to the
choice.
3.
We want to logically break down the problem and make our program easier to
read and understand. We will write separate methods to create each of the vertical menus. The three methods that we will be writing are createViews(),
createScrollBars(), and createLookAndFeel(). The method
headings with empty bodies are provided.
4.
Lets start with the createLookAndFeel() method. This will create the
first submenu shown in figure 1. There are three items on this menu, Metal,
Motif, and Windows. We will create this menu by doing the following:
a) Create a new JMenu with the name Look and Feel.
b) Create a new JMenuItem with the name Metal.
c) Add an action listener to the menu item (see the createNotes() method
to see how this is done).
d) Add the menu item to the menu.
e) Repeat steps b through d for each of the other two menu items.
5.
6.
Now that we have our submenus, these menus will become menu items for the
Views menu. The createViews() method will make the vertical menu
shown cascading from the menu choice Views as shown in figure. We will do
this as follows
a) Create a new JMenu with the name Views.
b) Call the createLookAndFeel() method to create the Look and Feel
submenu.
c) Add an action listener to the Look and Feel menu.
d) Add the look and feel menu to the Views menu.
e) Repeat steps b through d for the Scroll Bars menu item, this time calling
the createScrollBars() method.
7.
Finish creating your menu system by adding the Views menu to the menu bar
in the constructor.
Christie_435966_LM
2/14/06
1:59 PM
Page 111
Chapter 12 Lab
GUI ApplicationsPart 2
Add scroll bars to the text area by completing the following steps in the constructor
a) Create a JScrollPane object called scrolledText, passing in theText.
b) Change the line that adds to the textPanel, by passing in scrolledText
(which now has theText.)
2.
Edit the action listener by adding 6 more branches to the else-if 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 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 that have already been created need to be updated. This
can be accomplished by calling the
SwingUtilities.updateComponentTreeUI method, passing a
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
111
Christie_435966_LM
112
2/14/06
1:59 PM
Page 112
Figure 2
Figure 3
Christie_435966_LM
2/14/06
1:59 PM
Page 113
Chapter 12 Lab
GUI ApplicationsPart 2
113
Christie_435966_LM
114
2/14/06
1:59 PM
Page 114
Christie_435966_LM
2/14/06
1:59 PM
Page 115
Chapter 12 Lab
GUI ApplicationsPart 2
115
Christie_435966_LM
116
2/14/06
1:59 PM
Page 116
Christie_435966_LM
2/14/06
1:59 PM
Page 117
Chapter 13 Lab
Applets and More
Objectives
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 yellow. Then it will draw three circles in one column, to resemble the red, orange, and
green lights on the traffic signal. Only one circle at a time will be filled in. It will start
will green and cycle through the
orange, red, and back to green to start
the cycle again. However, unlike a
traffic signal, each light will remain
on for the same amount of time. To
accomplish this cycle, we will use a
timer object.
When you have finished your
applet should appear as shown in figure 1, but with the filled in circle
cycling up from green to orange to
red and starting over in a continuous
changing of the traffic light.
Christie_435966_LM
118
2/14/06
1:59 PM
Page 118
2.
This class currently has all the constants you will need to be able to create traffic signal. It doesnt have anything else. You will need to change the class heading so that it extends JApplet.
Christie_435966_LM
2/14/06
1:59 PM
Page 119
Chapter 13 Lab
2.
Inside the init method, create a timer object passing in the TIME_DELAY
constant and a new TimerListener (We will be creating the listener class next).
3.
Call the start method with the timer object to generate action events.
119
Christie_435966_LM
120
2/14/06
1:59 PM
Page 120
2.
Inside this class, write an actionPerformed method. This method will check the
status variable to see whether it is currently red, orange, or green. Since we
want the lights to cycle as a traffic signal, we need to cycle in the order: green,
orange, red, green, orange, red, Once the status is determined, the status
should then be set to the next color in the cycle.
3.
Christie_435966_LM
2/14/06
1:59 PM
Page 121
Chapter 13 Lab
Draw the traffic signal by overriding the paint method. For all graphics, use the
named constants included in the class.
2.
3.
Create a yellow rectangle (solid color) for the traffic signal. The constants
X_TRAFFICLIGHT, Y_TRAFFICLIGHT, TRAFFICLIGHT_WIDTH, and
TRAFFICLIGHT_HEIGHT have already been defined for your use.
4.
Create round lights of red, orange, and green for the signals. These should be
outlines of these colors. The constants X_LIGHTS, Y_REDLIGHT,
Y_GREENLIGHT, Y_ORANGELIGHT, and LIGHT_DIAMETER, have
already been defined for your use. Only one light will be filled in at a time,
when the status indicates that one has been chosen. You will need to check the
status to determine which light to fill in. Remember, the status is changed only
in the actionPerformed method (already defined) where the repaint method
is also called.
5.
Put the shade hoods above the lights by drawing black arcs above each light.
The constants HOOD_START_ANGLE and HOOD_ANGLE_SWEPT have
already been defined for your use.
6.
Try out your applet. If time permits, create a web page on which you can display your applet.
121
Christie_435966_LM
122
2/14/06
1:59 PM
Page 122
Christie_435966_LM
2/14/06
1:59 PM
Page 123
Chapter 14 Lab
Recursion
Objectives
Be able to trace recursive function calls
Be able to write non-recursive and recursive methods to find geometric and
harmonic progressions
Introduction
In this lab we will follow how the computer executes recursive methods, and will write
our own recursive method, as well as the iterative equivalent. There are two common
progressions in mathematics, the geometric progression and the harmonic progression.
The geometric progression is defined as the product of the first n integers. The harmonic progression is defined as the product of the inverses of the first n integers.
Mathematically, the definitions are as follows
n
n-1
Geometric (n) = q i = i * q i
i=1
n
i=1
n-1
1
1
1
Harmonic (n) = q = * q
i
i
i
i=1
i=1
Lets look at examples. If we use n = 4, the geometric progression would be
1 * 2 * 3 * 4 = 24, and the harmonic progression would be
1 *
1
1
1
1
* * =
= 0.04166
2
3
4
24
Christie_435966_LM
124
2/14/06
1:59 PM
Page 124
Copy the file Recursion.java (see code listing 14.1) from www.aw.com/cssupport or as directed by your instructor.
2.
Run the program to confirm that the generated answer is correct. Modify the
factorial method in the following ways:
a) add these lines above the first if statement
int temp;
System.out.println(
"Method call calculating Factorial of: " + n);
b) remove this line in the recursive section at the end of the method
return (factorial(n-1) *n);
c) add these lines in the recursive section
temp = factorial(n-1);
System.out.println(
"Factorial of: " + (n-1) + " is " + temp);
return (temp * n);
3.
Rerun the program and note how the recursive calls are built up on the run-time
stack and then the values are calculated in reverse order as the run-time stack
unwinds.
Christie_435966_LM
2/14/06
1:59 PM
Page 125
Chapter 14 Lab
Recursion
Copy the file Progression.java (see code listing 14.2) from www.aw.com/cssupport or as directed by your instructor.
2.
You need to write class (static) methods for an iterative and a recursive version
each of the progressions. You will have 4 methods, geometricRecursive,
geometricIterative, harmonicRecursive, and
harmonicIterative. Be sure to match them to the method calls in the
main method.
125
Christie_435966_LM
126
2/14/06
1:59 PM
Page 126
Christie_435966_LM
2/14/06
1:59 PM
Page 127
Chapter 14 Lab
Recursion
127
Christie_435966_LM
2/14/06
1:59 PM
Page 128