Lab Manual Java
Lab Manual Java
to Accompany
Diane Christie
University of Wisconsin Stout
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.
Copyright 2007 Pearson Education, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. Printed in the United States of America. For information on obtaining permission for use of material in this work, please submit a written request to Pearson Education, Inc., Rights and Contracts Department, 75 Arlington Street, Suite 300, Boston, MA 02116, fax your request to 617-848-7047, or e-mail at http://www.pearsoned.com/legal/permissions.htm. ISBN 0-321-43424-2 1 2 3 4 5 6 7 8 9 10BB09 08 07 06
Preface
About this Lab Manual
This lab manual accompanies Starting Out With Java 5: From Control Structures to 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 7 and 12 are written entirely by the student using the instructions in the various tasks, so there is no code provided as a starting basis.
iv
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
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: From Control Structures to Objects or Gaddis, Starting Out with Java 5: From Control Structures to 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.
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 Chapter 15 Lab Algorithms, Errors, and Testing Java Fundamentals Selection Control Structures Loops and Files Methods Classes and Objects GUI Applications Arrays More Classes and Objects Text Processing and Wrapper Classes Inheritance Exceptions and I/O Streams Advanced GUI Applications Applets and More Recursion 1 9 21 31 41 51 61 67 75 87 97 109 113 121 127
Chapter 1 Lab
Algorithms, Errors, and Testing
Objectives
Be able to write an algorithm Be able to compile a Java program Be able to execute a Java program using the Sun JDK or a Java IDE Be able to test a program Be able to debug a program with syntax and logic errors
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. Syntax Errorserrors in the grammar of the programming language. These 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
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 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. 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.
3.
Chapter 1 Lab
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
4.
Hours
Rate
Chapter 1 Lab
3.
4.
Item
Price
Tax
Total (calculated)
Total (output)
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
public class Pay { public static void main(String [] args) { //create a Scanner object to read from the keyboard Scanner keyboard = new Scanner(System.in); //identifier declarations double hours; //number of hours worked double rate; //hourly pay rate double pay; //gross pay //display prompts and get input System.out.print("How many hours did you work? "); hours = keyboard.nextDouble(); System.out.print("How much do you get paid per hour? "); rate = keyboard.nextDouble(); //calculations if(hours <= 40) pay = hours * rate; else pay = (hours - 40) * (1.5 * rate) + 40 * rate; //display results System.out.println("You earned $" + pay); } }
Chapter 1 Lab
");
Chapter 2 Lab
Java Fundamentals
Objectives
Write arithmetic expressions to accomplish a task Use casting to convert between primitive types Use a value-returning library method and a library constant Use string methods to manipulate string data Communicate with the user by using the Scanner class or dialog boxes Create a program from scratch by translating a pseudocode algorithm Be able to document a program
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.
10
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
We will bring everything we have learned together by creating a program from an algorithm. Finally, you will document the program by adding comments. Comments are not read by the computer, they are for use by the programmer. They are to help a programmer document what the program does and how it accomplishes it. This is very important when a programmer needs to modify code that is written by another person.
Chapter 2 Lab
Java Fundamentals
11
Each time you make changes to the program code, you must compile again for the changes to take effect before running the program again. 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.
12
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 2 Lab
Java Fundamentals
13
3. 4. 5. 6. 7.
14
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
2. 3. 4.
5.
Chapter 2 Lab
Java Fundamentals
15
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. Print your results to the screen with an appropriate message. Compile, debug, and run using the following test data and record the results.
16
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
3. 4.
Chapter 2 Lab
Java Fundamentals
17
2. 3. 4. 5.
18
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 2 Lab
Java Fundamentals
19
System.out.println(output); System.out.println(); // to leave a blank line // // // // // // // ADD LINES FOR TASK #2 HERE prompt the user for first name read the users first name prompt the user for last name read the users last name concatenate the users first and last names print out the users full name // to leave a blank line
System.out.println(); // // // // // //
ADD LINES FOR TASK #3 HERE get the first character from the users first name print out the users first initial convert the users full name to all capital letters print out the users full name in all capital letters and the number of characters in it // to leave a blank line
System.out.println(); // // // // // // } }
ADD LINES FOR TASK #4 HERE prompt the user for a diameter of a sphere read the diameter calculate the radius calculate the volume print out the volume
Chapter 3 Lab
Selection Control Structures
Objectives
Be able to construct boolean expressions to evaluate a given condition Be able to compare Strings Be able to use a flag Be able to construct if and if-else-if statements to perform a specific task Be able to construct a switch statement Be able to format numbers
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.
22
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
3.
4.
Chapter 3 Lab
23
2.
3.
24
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 3 Lab
25
2.
3.
26
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 3 Lab
27
//prompt user and get first name System.out.println("Welcome to Mike and Dianes Pizza"); System.out.print("Enter your first name: "); firstName = keyboard.nextLine(); Code Listing 3.1 continued on next page.
28
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects //determine if user is eligible for discount by //having the same first name as one of the owners //ADD LINES HERE FOR TASK #1 //prompt user and get pizza size choice System.out.println("Pizza Size (inches) Cost"); System.out.println(" 10 $10.99); System.out.println(" 12 $12.99"); System.out.println(" 14 $14.99"); System.out.println(" 16 $16.99"); System.out.println("What size pizza would you like?"); System.out.print( "10, 12, 14, or 16 (enter the number only): "); inches = keyboard.nextInt(); //set price and size of pizza ordered //ADD LINES HERE FOR TASK #2 //consume the remaining newline character keyboard.nextLine(); //prompt user and get crust choice System.out.println("What type of crust do you want? "); System.out.print("(H)Hand-tossed, (T) Thin-crust, or " + "(D) Deep-dish (enter H, T, or D): "); input = keyboard.nextLine(); crustType = input.charAt(0); //set users crust choice on pizza ordered //ADD LINES FOR TASK #3 //prompt user and get topping choices one at a time System.out.println("All pizzas come with cheese."); System.out.println("Additional toppings are $1.25 each," + " choose from"); System.out.println("Pepperoni, Sausage, Onion, Mushroom");
Chapter 3 Lab
29
//if topping is desired, //add to topping list and number of toppings System.out.print("Do you want Pepperoni? (Y/N): "); input = keyboard.nextLine(); choice = input.charAt(0); if (choice == Y || choice == y) { numberOfToppings += 1; toppings = toppings + "Pepperoni "; } System.out.print("Do you want Sausage? (Y/N): "); input = keyboard.nextLine(); choice = input.charAt(0); if (choice == Y || choice == y) { numberOfToppings += 1; toppings = toppings + "Sausage "; } System.out.print("Do you want Onion? (Y/N): "); input = keyboard.nextLine(); choice = input.charAt(0); if (choice == Y || choice == y) { numberOfToppings += 1; toppings = toppings + "Onion "; } System.out.print("Do you want Mushroom? (Y/N): "); input = keyboard.nextLine(); choice = input.charAt(0); if (choice == Y || choice == y) { numberOfToppings += 1; toppings = toppings + "Mushroom "; } //add additional toppings cost to cost of pizza
Code Listing 3.1 continued on next page.
30
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects cost = cost + (1.25*numberOfToppings); //display order confirmation System.out.println(); System.out.println("Your order is as follows: "); System.out.println(inches + " inch pizza"); System.out.println(crust + " crust"); System.out.println(toppings); //apply discount if user is eligible //ADD LINES FOR TASK #4 HERE //EDIT PROGRAM FOR TASK #5 //SO ALL MONEY OUTPUT APPEARS WITH 2 DECIMAL PLACES System.out.println("The cost of your order is: $" + cost); //calculate and display tax and total cost tax = cost * TAX_RATE; System.out.println("The tax is: $" + tax); System.out.println("The total due is: $" + (tax+cost)); System.out.println( "Your order will be ready for pickup in 30 minutes."); }
Chapter 4 Lab
Loops and Files
Objectives
Be able to convert an algorithm using control structures into Java Be able to write a while loop Be able to write an do-while loop Be able to write a for loop Be able to use the Random class to generate random numbers Be able to use file streams for I/O Be able to write a loop that reads until end of file Be able to implement an accumulator and a counter
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 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 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.
32
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
2.
3.
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 die by rolling the first die Get the value of the second die by 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. 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.
Chapter 4 Lab
33
34
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
3.
Chapter 4 Lab
35
2. 3. 4.
5. 6. 7.
36
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
2. 3. 4. 5.
6. 7.
8.
Chapter 4 Lab
37
public class DiceSimulation { public static void main(String[] args) { final int NUMBER = 10000; //the number of times to //roll the dice //a random number generator used in simulating //rolling a dice Random generator = new Random(); int die1Value; int die2Value; int count = 0; int snakeEyes = 0; int twos = 0; int threes = 0; int fours = 0; int fives = 0; int sixes = 0;
Code Listing 4.1 continued on next page.
// // // // // // // // // // // // // // // // // //
number of spots die number of spots die number of times rolled number of times rolled number of times two is rolled number of times is rolled number of times is rolled number of times is rolled number of times rolled
on the first on the second the dice were snake eyes is double double three double four double five double six is
38
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects //ENTER YOUR CODE FOR THE ALGORITHM HERE System.out.println ("You rolled snake eyes " + snakeEyes + " out of " + count + " rolls."); System.out.println ("You rolled double twos " + twos + " out of " + count + " rolls."); System.out.println ("You rolled double threes " + threes + " out of " + count + " rolls."); System.out.println ("You rolled double fours " + fours + " out of " + count + " rolls."); System.out.println ("You rolled double fives " + fives + " out of " + count + " rolls."); System.out.println ("You rolled double sixes " + sixes + " out of " + count + " rolls."); }
Chapter 4 Lab
39
//create an object of type Decimal Format DecimalFormat threeDecimals = new DecimalFormat("0.000"); //create an object of type Scanner Scanner keyboard = new Scanner (System.in); String filename; // the user input file name //Prompt the user and read in the file name System.out.println( "This program calculates statistics" + "on a file containing a series of numbers"); System.out.print("Enter the file name: "); filename = keyboard.nextLine(); //ADD LINES FOR TASK #4 HERE //Create a FileReader object passing it the filename //Create a BufferedReader object passing it the //FileReader object. Code Listing 4.2 continued on next page.
40
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects //priming read to read the first line of the file //create a loop that continues until you are at the //end of the file //convert the line to double value, add the value to //the sum //increment the counter //read a new line from the file //close the input file //store the calculated mean //ADD LINES FOR TASK #5 HERE //create a FileReader object passing it the filename //create a BufferedReader object passing it the //FileReader object. //reinitialize the sum of the numbers //reinitialize the number of numbers added //priming read to read the first line of the file //loop that continues until you are at the end of the //file //convert the line into a double value and subtract //the mean //add the square of the difference to the sum //increment the counter //read a new line from the file //close the input file //store the calculated standard deviation
//ADD LINES FOR TASK #3 HERE //create an object of type FileWriter using //"Results.txt" //create an object of PrintWriter passing it the //FileWriter object. //print the results to the output file //close the output file } }
Chapter 5 Lab
Methods
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, since the method can be called as many times as needed without rewriting the code each time. Finally, we will use documentation comments for each method, and 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
2.
3. 4.
43
6.
44
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
3.
Compile, debug, and run. Test out the program using your sample data.
45
2.
46
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
//create a scanner object to read from the keyboard Scanner keyboard = new Scanner (System.in); //do loop was chose to allow the menu to be displayed //first do { //call the printMenu method choice = keyboard.nextInt(); switch (choice) { Code Listing 5.1 continued on next page.
Chapter 5 Lab Methods 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 of the circle is " + 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.
47
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:
Methods
49
//consumes the new line character after the number keyboard.nextLine(); System.out.println("Do you want to exit the program " + "(Y/N)?: "); String answer = keyboard.nextLine(); letter = answer.charAt(0); }while (letter != Y && letter != y); } }
Chapter 6 Lab
Classes and Objects
Objectives
Be able to declare a new class Be able to write a constructor Be able to write instance methods that return a value Be able to write instance methods that take arguments Be able to instantiate an object Be able to use calls to instance methods to access and change the 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 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).
52
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
These attributes become fields in our class. The television object will also be able to control the state of its attributes. These controls become methods in our class. setChannel. The setChannel method will store the desired station in the channel field. power. The power method will toggle the power between on and off, changing the value stored in the powerOn field from true to false or from false to true. increaseVolume. The increaseVolume method will increase the value stored in the volume field by 1. decreaseVolume. The decreaseVolume method will decrease the value stored in the volume field by 1. getChannel. The getChannel method will return the value stored in the channel field. getVolume. The getVolume method will return the value stored in the volume field. getManufacturer. The getManufacturer method will return the constant value stored in the MANUFACTURER field. getScreenSize. The getScreenSize method will return the constant value stored in the SCREEN_SIZE field. 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.
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
Methods
Chapter 6 Lab
53
3. 4. 5. 6. 7.
54
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 6 Lab
55
Task #3 Methods
1. Define accessor methods called getVolume, getChannel, getManufacturer, and getScreenSize that return the value of the corresponding field. Define a mutator method called setChannel accepts a value to be stored in the channel field. 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. Write javadoc comments above each method header. Compile and debug. Do not run.
2. 3.
5. 6.
56
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
2. 3.
OUTPUT (boldface is user input) A 55 inch Toshiba has been turned on. What channel do you want? 56 Channel: 56 Volume: 21 Too loud!! I am lowering the volume. Channel: 56 Volume: 15
Chapter 6 Lab
57
OUTPUT (boldface is user input) A 19 inch Sharp has been turned on. What channel do you want? 7 Channel: 7 Volume: 18
58
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 6 Lab
59
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 } }
Chapter 7 Lab
GUI Applications
Objectives
Be able to create a closeable window Be able to create panels containing buttons Be able to use different layouts Be able to handle button events
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
62
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 7 Lab
GUI Applications
63
2.
64
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
2.
Chapter 7 Lab
GUI Applications
65
Chapter 8 Lab
Arrays
Objectives
Be able to declare and instantiate arrays Be able to fill an array using a for loop Be able to access and process data in an array Be able to write a sorting method Be able to use an array of objects
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.
68
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
69
2.
70
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
2. 3. 4. 5.
Chapter 8 Lab
Arrays
71
72
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 8 Lab
Arrays
73
Chapter 9 Lab
More Classes and Objects
Objectives
Be able to write a copy constructor Be able to write equals and toString methods Be able to use objects made up of other objects (Aggregation) Be able to write methods that pass and return objects
Introduction
We discussed objects in Chapter 6 and we modeled a television in the Chapter 6 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. 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.
76
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to 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. 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
Chapter 9 Lab
77
2.
78
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
2.
3.
Chapter 9 Lab
79
2.
3.
4.
5.
6. 7.
80
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 9 Lab
81
82
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 9 Lab
83
Money sum = new Money(0); sum.cents = this.cents + otherAmount.cents; long carryDollars = sum.cents/100; sum.cents = sum.cents%100; sum.dollars = this.dollars + otherAmount.dollars + carryDollars; return sum; } /**Subtracts the parameter Money object from the calling Money object and returns the difference. @param amount the amount of money to subtract @return the difference between the calling Money object and the parameter Money object*/ 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. @param amount the amount of money to compare against @return -1 if the dollars and the cents of the calling Code Listing 9.3 continued on next page.
84
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; }
Chapter 9 Lab
85
86
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 10 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.
88
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
3.
4. 5.
Chapter 10 Lab
89
2. 3.
90
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 10 Lab
91
//Check to make sure all other characters are //digits else if (//CONDITION TO CHECK FOR DIGIT) { System.out.println(militaryTime + " is not a valid military time." ); } else if (//CONDITION TO CHECK FOR DIGIT) { System.out.println(militaryTime + " is not a valid military time." ); } else if (//CONDITION TO CHECK FOR DIGIT) { System.out.println(militaryTime + " is not a valid military time." ); } else if (//CONDITION TO CHECK FOR DIGIT) { System.out.println(militaryTime + " is not a valid military time." ); } else { //SEPARATE THE STRING INTO THE HOURS //AND THE MINUTES, CONVERTING THEM TO //INTEGERS AND STORING INTO THE //INSTANCE VARIABLES //validate hours and minutes are valid //values if(hours > 23) { System.out.println(militaryTime + " is not a valid military" + " time." ); } Code Listing 10.1 continued on next page
92
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects else if(minutes > 59) { System.out.println(militaryTime + " is not a valid military" + " time." ); } //convert military time to conventional //time for afternoon times else if (hours > 12) { hours = hours - 12; afternoon = true; System.out.println(this.toString()); } //account for midnight else if (hours == 0) { hours = 12; System.out.println(this.toString()); } //account for noon else if (hours == 12) { afternoon = true; System.out.println(this.toString()); } //morning times dont need converting else { System.out.println(this.toString()); } } } }
Chapter 10 Lab
93
/**toString method returns a conventional time @return a conventional time with am or pm*/ public String toString() { 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; } }
94
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 10 Lab
95
Chapter 11 Lab
Inheritance
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.
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: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
Chapter 11 Lab
Inheritance
99
2. 3. 4.
5.
6.
100
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
4. 5.
6.
7. 8.
9. 10.
11.
Chapter 11 Lab
Inheritance
101
Account Number 100002-0 belonging to William Shakespeare Initial balance = $400.00 After deposit of $500.00, balance = $900.00 Insuffient funds to withdraw $1000.00, balance = $900.00 After monthly interest has been posted, balance = $901.88 Account Number 100002-1 belonging to William Shakespeare Initial balance = $5.00 After deposit of $500.00, balance = $505.00 Insuffient funds to withdraw $1000.00, balance = $505.00 Account Number 100003-10 belonging to Isaac Newton
102
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Inheritance
103
= 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 11.1 continued on next page
104
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects System.out.println ("Insuffient funds to " + "withdraw $" + money_out + ", balance = $" + money); } yourAccount.postInterest(); money = myFormat.format(yourAccount.getBalance()); System.out.println ("After monthly interest " + "has been posted," + "balance = $" + money); System.out.println();
// to test the copy constructor of the savings account //class SavingsAccount secondAccount = new SavingsAccount (yourAccount,5); System.out.println ("Account Number " + secondAccount.getAccountNumber()+ " belonging to " + secondAccount.getOwner()); money = myFormat.format(secondAccount.getBalance()); System.out.println ("Initial balance = $" + money); secondAccount.deposit (put_in); money_in = myFormat.format(put_in); money = myFormat.format(secondAccount.getBalance()); System.out.println ("After deposit of $" + money_in + ", balance = $" + money); secondAccount.withdraw(take_out); money_out = myFormat.format(take_out); money = myFormat.format(secondAccount.getBalance()); if (completed) { System.out.println ("After withdrawal of $" + money_out + ", balance = $" + money); } else { Code Listing 11.1 continued on next page
Chapter 11 Lab
Inheritance
105
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()); } }
106
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 11 Lab
Inheritance
107
@param the beginning balance of the new account*/ public BankAccount(BankAccount oldAccount, double amount) { owner = oldAccount.owner; balance = amount; accountNumber = oldAccount.accountNumber; } /**allows you to add money to the account @param amount the amount to deposit in 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. @param amount the amount to withdraw from the account @return true if there was sufficient funds to complete the transaction, false otherwise*/ public boolean withdraw(double amount) { boolean completed = true; if (amount <= balance) { balance = balance - amount; } else { completed = false; } return completed; } Code Listing 11.2 continued on next page
108
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects /**accessor method to balance @return the balance of the account*/ public double getBalance() { return balance; } /**accessor method to owner @return the owner of the account*/ public String getOwner() { return owner; } /**accessor method to account number @return the account number*/ public String getAccountNumber() { return accountNumber; } /**mutator method to change the balance @param newBalance the new balance for the account*/ public void setBalance(double newBalance) { balance = newBalance; } /**mutator method to change the account number @param newAccountNumber the new account number*/ public void setAccountNumber(String newAccountNumber) { accountNumber = newAccountNumber; }
Chapter 12 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.
110
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 12 Lab
111
2.
3.
112
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects Name? Jane Doe SSN? 333-333-333 Invalid the social security number, dashes at wrong positions Continue? n
Chapter 13 Lab
Advanced GUI Applications
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.
114
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
3.
4.
5. 6.
7.
Chapter 13 Lab
115
2.
116
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Figure 2
Figure 3
Chapter 13 Lab
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 //****THESE ITEMS ARE NOT YET USED. //****YOU WILL BE CREATING THEM IN THIS LAB private JMenu viewMenu; //vertical menu with choices for views private JMenu lafMenu; //vertical menu with look and feel private JMenu sbMenu; //vertical menu with scroll bar option private JScrollPane scrolledText;//scroll bars //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 //get contentPane and set layout of the window Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); //creates the vertical menus createNotes(); createViews(); //creates horizontal menu bar and //adds vertical menus to it mBar = new JMenuBar(); mBar.add(notesMenu); //****ADD THE viewMenu TO THE MENU BAR HERE setJMenuBar(mBar); //creates a panel to take notes on textPanel = new JPanel(); textPanel.setBackground(Color.blue); theText = new JTextArea(LINES, CHAR_PER_LINE); theText.setBackground(Color.white); //****CREATE A JScrollPane OBJECT HERE CALLED scrolledText //****AND PASS IN theText, THEN //****CHANGE THE LINE BELOW BY PASSING IN scrolledText textPanel.add(theText); contentPane.add(textPanel, BorderLayout.CENTER); } /**creates vertical menu associated with Notes menu item on menu bar*/ public void createNotes() { notesMenu = new JMenu("Notes"); JMenuItem item; item = new JMenuItem("Save Note 1"); item.addActionListener(new MenuListener()); notesMenu.add(item);
Chapter 13 Lab
119
item = new JMenuItem("Save Note 2"); item.addActionListener(new MenuListener()); notesMenu.add(item); item = new JMenuItem("Open Note 1"); item.addActionListener(new MenuListener()); notesMenu.add(item); item = new JMenuItem("Open Note 2"); item.addActionListener(new MenuListener()); notesMenu.add(item); item = new JMenuItem("Clear"); item.addActionListener(new MenuListener()); notesMenu.add(item); item = new JMenuItem("Exit"); item.addActionListener(new MenuListener()); notesMenu.add(item); } /**creates vertical menu associated with Views menu item on the menu bar*/ public void createViews() { } /**creates the look and feel submenu*/ public void createLookAndFeel() { } /**creates the scroll bars submenu*/ public void createScrollBars() {
Code Listing 13.1 continued on next page.
120 }
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
private class MenuListener implements ActionListener { public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); if (actionCommand.equals("Save Note 1")) note1 = theText.getText(); else if (actionCommand.equals("Save Note 2")) note2 = theText.getText(); else if (actionCommand.equals("Clear")) theText.setText(""); else if (actionCommand.equals("Open Note 1")) theText.setText(note1); else if (actionCommand.equals("Open Note 2")) theText.setText(note2); else if (actionCommand.equals("Exit")) System.exit(0); //****ADD 6 BRANCHES TO THE ELSE-IF STRUCTURE //****TO ALLOW ACTION TO BE PERFORMED FOR EACH //****MENU ITEM YOU HAVE CREATED else theText.setText("Error in memo interface"); } } public static void main(String[] args) { NoteTaker gui = new NoteTaker(); gui.setVisible(true); } }
Chapter 14 Lab
Applets and More
Objectives
Be able to write an applet Be able to draw rectangles, circles, and arcs Be able to override the paint method Be able to use a timer
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.
122
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 14 Lab
123
2. 3.
124
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
3.
Chapter 14 Lab
125
4.
5.
6.
126
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 15 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 i=1 n n-1 i=1
Geometric (n) = q i = i * q i 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
n-1
128
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
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.
Chapter 15 Lab
Recursion
129
130
Lab Manual to Accompany Starting Out with Java 5: From Control Structures to Objects
Chapter 15 Lab
Recursion
131