Absolute Java, Global Edition, 6th edition By Walter Savitch Solution Manual

Page 1

Absolute Java, Global Edition, 6th edition By Walter Savitch

Email: Richard@qwconsultancy.com


Savitch, Absolute Java 6/e, Global Edition: Chapter 1, Instructor’s Manual

Chapter 1

Getting Started Key Terms intermediate language byte-code code OOP object method class application program applet applet viewer println System.out.println invoking dot argument sending a message variable int equal sign assignment operator high-level language low-level language machine language compiler byte-code Java Virtual Machine interpreter run command source code object code code .java files javac .class files running a Java program bug debugging syntax error run-time error logic error identifier case-sensitive .


Savitch, Absolute Java 6/e, Global Edition: Chapter 1, Instructor’s Manual

keyword declare floating-point number primitive type assignment statement assignment operator uninitialized variable assigning int values to double values integers booleans literals, constants e notation quotes mixing types integer division % operator type coercion v++ versus ++v decrement operator String + operator concatenation class object method method call method invocation argument sending a message length position index backslash escape sequence immutable object ASCII Unicode // comments line comments /*comments*/ block comments when to comment self-documenting

.


Savitch, Absolute Java 6/e, Global Edition: Chapter 1, Instructor’s Manual

Brief Outline 1.1 Introduction to Java Origins of the Java Language Objects and Methods Applets A Sample Java Application Program Byte-Code and the Java Virtual Machine Class Loader Compiling a Java Program or Class Running a Java Program 1.2 Expressions and Assignment Statements Identifiers Variables Assignment Statements More Assignment Statements Assignment Compatibility Constants Arithmetic Operators and Expressions Parentheses and Precedence Rules Integer and Floating-Point Division Type Casting Increment and Decrement Operators 1.3 The Class String String Constants and Variables Concatenation of Strings Classes String Methods Escape Sequences String Processing The Unicode Character Set 1.4 Program Style Naming Constants Java Spelling Conventions Comments Indenting

Teaching Suggestions This chapter introduces the students to the history of the Java language and begins to tell them about what types of programs can be written in Java as well as the basic structure of a Java program. During the discussions on compilation and running a program, care should be taken to explain the process on the particular computer system that the students will be using, as different computing/development environments will each have their own specific directions that will need to be followed. What is especially important to note is that the basic unit of programming in Java is a class – every Java program is a class.

.


Savitch, Absolute Java 6/e, Global Edition: Chapter 1, Instructor’s Manual

Simple programming elements are then introduced, starting with simple variable declarations and assignment statements, and eventually evolving into arithmetic expressions and String manipulation. Primitive data types are introduced as well. If time allows, a discussion of how the computer stores data is appropriate. While some of the operations on the primitives are familiar to students, operations like modulas (mod, %) are usually not and require additional explanation. Also, the functionality of the increment and decrement operators requires attention. The issue of type casting is also introduced, which syntactically as well as conceptually can be difficult for students. Strings are introduced as the first object that students will be using. The distinction between an object and a primitive value should be discussed, as well as the distinction between an object and a class. Strings have operations that can be applied to them, but they also have methods that can be called on them. The ability to have methods is what makes an object so much different than a primitive value. The last section on programming style further introduces the ideas of conventions for naming of programmatic entities and the use and importance of commenting source code. Commenting is a skill that students will need to develop and they should begin commenting their code from the first program that they complete. Indentation is also discussed. However, many development environments actually handle this automatically. Key Points Compiler. The compiler is the program that translates source code into a language that a computer can understand. This process is different in Java than some other high-level languages. Java translates its source code into byte-code using the javac command. Students should be exposed to how the javac command gets executed in the particular development environment. Also, since javac is a program that can be run at the command prompt if using a Unix environment. Byte-Code. The compiler generates byte-code that is then interpreted by the Java Virtual Machine. This process occurs when the student uses the java command to execute the program. Once again, how this command is executed will vary depending on computing environments, and java is also a program that can be run at the command prompt. The interpretation of the byte-code by the Java Virtual Machine is the reason Java is considered so portable. The bytecode that is generated by the Java compiler is always the same no matter what the machine or operating system. As long as the Java Virtual Machine is loaded onto a computer, that computer can interpret the byte-code generated by the compiler. This second computer can be a different type or even running a different operating system than the one that originally compiled the source code and the byte-code will still be correctly interpreted. Syntax and Semantics. When discussing any programming language, we describe both the rules for writing the language, often referred to as its grammar, as well as the interpretation of what has been written. The first is the syntax of the language, while the second is the semantics of the language. For syntax, we have a compiler that will tell us when we have made a mistake. We can correct the error and try compiling again. However, the bigger challenge may lie in the understanding of what the code actually means. There is no “compiler” for telling us if the code .


Savitch, Absolute Java 6/e, Global Edition: Chapter 1, Instructor’s Manual

that is written will do what we want it to, and this is when the code does not do what we want, it most often takes longer to fix than a simple syntax error. Names (Identifiers). Java has specific rules for how you can name an entity in a program. These rules are compiler enforced, but students should be able to recognize a correct or incorrect identifier. Also, there are common conventions for how Java names its programming entities. Class names begin with a capital letter followed by lower case letters. All other entities have names that begin with a lower case letter. However, these conventions are not compiler enforced. The book and the source code for Java itself use these conventions and it is helpful for students to understand that if they follow them, their code is easier for others to read. Variable Declarations. Java requires that all variables be declared before they are used. The declaration consists of the type of the variable as well as the name. You can declare more than one variable per line. Assignment Statements with Primitive Types. To assign a value to a variable whose type is a primitive, we use the assignment operator, which is the equals (=) sign. Assignment occurs by first evaluating the expression on the right hand side of the equals sign and then assigning the value to the variable on the left. Confusion usually arises for students when assigning the value of one variable to another. Showing that x = y is not the same as y = x is helpful when trying to clear up this confusion. Initializing a Variable in a Declaration. We can and should give our variables an initial value when they are declared. This is achieved through the use of the assignment operator. We can assign each variable a value on separate lines or we can do multiple assignments in one line as shown on page 19. Assignment Compatibility. Normally, we can only assign values to a variable that are of the same type as we declared the variable to be. For example, we can assign an integer value to an integer variable. However, we can also assign a byte value to an integer due to the following ordering: byte -> short -> int -> long -> float -> double Values on the left can be assigned to variables whose types are to the right. You cannot go in the other direction. In fact, the compiler will give an error if you do. What is Doubled? This discussion concerns how floating-point numbers are stored inside the computer. A related topic would be to show the conversion of these numbers into the format that the computer uses. The String Class. Java has many predefined classes that are always available for you to use. String is one of these. A String object can be represented by a sequence of alpha-numeric characters written inside of quotes (“). You can create variables of type String and assign values to them using the assignment operator just as we have seen with the primitive types. There are also operations defined on Strings, which will be defined in the next section.

.


Savitch, Absolute Java 6/e, Global Edition: Chapter 1, Instructor’s Manual

Using the + sign with Strings. The operator + can be used with Strings to “add” two Strings together. This is commonly called concatenation and using this operator is similar to what students have seen with the primitive types. Strings also have methods, which are used in a different way than has been seen up until this point. Classes, Objects, and Methods. This is the section where the class/object distinction needs to be addressed. The distinction is important for students to understand. The idea of an object having methods that can be called or invoked is terminology that will be introduced at this time. The syntax of calling a method should also be discussed. There are many methods that are defined in the String class that can make for interesting examples of how to call methods and what they do. These methods are summarized in Display 1.4. Returned Value. One of the things a method can do is return a value. When we call a method, we are asking the object to do something for us. The returned value is the result of that action. We can use the returned value in later computation if we wish. Naming Constants. Program style is important and varies from one person to another. However, having programmatic style standards makes programs easier to read for everyone. One of these style points can be the naming of constants in the program. The convention that is introduced is the one that is common to Java and the text. Tips Error Messages. One of the most frustrating parts of learning how to program is learning to understand the error messages of the compiler. These errors, which are commonly called syntax errors, frustrate students. It is helpful to show some common error messages from the compiler so that students have a frame of reference when they see the errors again themselves. Also important for students to note is that even though Java states the line number that the error occurred on, it is not always accurate. Run-time errors occur when the program has been run. These most commonly take the form of exceptions in Java. For this section, creating a simple statement that divides by zero can generate one such error. The last type of error, a logic error is one that is hardest to spot because on the surface the program runs fine, but does not produce the correct result. Writing some statements that are supposed to compute sales tax for your area can show these, but instead of multiplying the total by the percentage of sales tax, the division sign is substituted. Initialize Variables. Variables that are declared but not assigned a value are uninitialized. It is good programming practice to always initialize your variables. In some cases, variables may be assigned a default value, however, one should not count on this occurring. Uninitialized variables used in computation can cause errors in your program and the best way to avoid these errors is to always give variables an initial value. This can most easily be done right when the variable is declared. Pitfalls Round-off Errors in Floating-Point Numbers. One of the places to show the fallibility of computers is in the round-off errors that we experience when using floating point numbers. This topic relates to why the type is named double and also deals with the representation of floating .


Savitch, Absolute Java 6/e, Global Edition: Chapter 1, Instructor’s Manual

point numbers in the system. This problem occurs because not all floating-point numbers are finite, a common example being the decimal representation of the fraction 1/3. Because we can only store so many digits after the decimal points, our computation is not always accurate. A discussion of when this type of round off error could be a problem would be appropriate to highlight some of the shortcomings of computing. Division with Whole Numbers. In Java, all of the arithmetic operations are closed within their types. Therefore, division of two integers will produce an integer, which will produce an answer that most students do not expect. For example, the integer 1 divided by the integer 2 will produce the integer 0. Students will expect 0.5. One way to get a floating-point answer out of integer division is to use typecasting. Another way is to force floating-point division by making one of the integers a floating-point number by placing a “.0” at the end. Experimentation with this issue is important to show the different results that can be obtained from integer division. Programming Projects Answers 1. /** * * Question1.java * * This program calculates and prints the Body Mass Index(BMI) value of a person with * body weight 70 kilograms and height 5.8 meters. * BMI is calculated using the formula * BMI = Body Weight in Kilograms / Body Height in Meters * * Created: Jan 30, 2016 * * @author * @version 1 */ public class Question1 { public static void main(String[] args) { double bodyMassIndex; double weight = 70.0; double height = 5.8; bodyMassIndex = weight / height; System.out.println("Your weight is = " + weight); System.out.println("Your height is " + height); System.out.println("Your BMI is = " + bodyMassIndex); } }

.


Savitch, Absolute Java 6/e, Global Edition: Chapter 1, Instructor’s Manual

2. /** * Question2.java * * This program computes the number of candy bars and gumballs you * can get by redeeming coupons at an arcade. 10 coupons is * redeemable for candy bars and 3 coupons for gumballs. You * would like as many candy bars as possible and only use * remaining coupons on gumballs. * * Created: Sat Mar 05 2005 * * @author Kenrick Mock * @version 1 */ public class Question2 { public static void main(String[] args) { // Variable declarations int num_coupons = 108; // If we have 108 coupons; change variable as desired int num_coupons_after_candybars = 0; int num_coupons_after_gumballs = 0; int num_candy_bars = 0; int num_gumballs = 0; System.out.println("Candy calculator."); // Integer division below discards any remainder num_candy_bars = num_coupons / 10; // Calculate remaining coupons num_coupons_after_candybars = num_coupons % 10; // Calculate gumballs num_gumballs = num_coupons_after_candybars / 3; // Calculate any leftover coupons num_coupons_after_gumballs = num_coupons_after_candybars % 3; // Output the number of candy bars and gumballs System.out.println("Your " + num_coupons + " coupons can be redeemed for " + num_candy_bars + " candy bars and " + num_gumballs + " gumballs with " + num_coupons_after_gumballs + " coupons leftover."); .


Savitch, Absolute Java 6/e, Global Edition: Chapter 1, Instructor’s Manual

} } // Question 2 3. /** * Question3.java * * This program outputs a name in lowercase to a name in Pig Latin * with the first letter of each name capitalized. * * Created: Sat Mar 05 2005 * * @author Kenrick Mock * @version 1 */ public class Question3 { public static void main(String[] args) { // Variable declarations String first = "walt"; String last = "savitch"; System.out.println(first + " " + last + " turned to Pig Latin is:"); // First convert first name to pig latin String pigFirstName = first.substring(1,first.length()) + first.substring(0,1) + "ay"; // Then capitalize first letter pigFirstName = pigFirstName.substring(0,1).toUpperCase() + pigFirstName.substring(1,pigFirstName.length()); // Repeat for the last name String pigLastName = last.substring(1,last.length()) + last.substring(0,1) + "ay"; // Then capitalize first letter pigLastName = pigLastName.substring(0,1).toUpperCase() + pigLastName.substring(1,pigLastName.length()); System.out.println(pigFirstName + " " + pigLastName); } } // Question 3 4. /** * Question4.java .


Savitch, Absolute Java 6/e, Global Edition: Chapter 1, Instructor’s Manual

* * Created: Sat Nov 08 15:41:53 2003 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ public class Question4 { public static final int AMT_NEEDED_TO_KILL_MOUSE_GRAMS = 30; public static final int MOUSE_WEIGHT_LBS = 1; public static final int DIETER_GOAL_WEIGHT_LBS = 210; public static final int WEIGHT_OF_CAN_SODA_GRAMS = 30; public static final double AMT_SWEETNR_IN_SODA = 0.001; public static void main(String[] args) { double amountPerCanGrams = (double)WEIGHT_OF_CAN_SODA_GRAMS * AMT_SWEETNR_IN_SODA; double proportionSwtnrBodyWeight = (double) (AMT_NEEDED_TO_KILL_MOUSE_GRAMS / MOUSE_WEIGHT_LBS); double amtNeededToKillFriend = proportionSwtnrBodyWeight * DIETER_GOAL_WEIGHT_LBS; double cansOfSoda = amtNeededToKillFriend * amountPerCanGrams; System.out.println("You should not drink more than " + cansOfSoda + " cans of soda."); } } // Question4 5. /** * Question5.java * * * Created: Sat Nov 08 16:04:41 2003 * Modified: Sat Mar 05 2005, Kenrick Mock * .


Savitch, Absolute Java 6/e, Global Edition: Chapter 1, Instructor’s Manual

* @author Adrienne Decker * @version 2 */ public class Question5 { public static final String sentence = "I hate programming."; public static void main (String[] args) { int position = sentence.indexOf("hate"); String firstPart = sentence.substring(0, position); String afterHate = sentence.substring(position + 4); String newString = firstPart + "love" + afterHate; System.out.println("The line of text to be changed is: "); System.out.println(sentence); System.out.println("I have rephrased the line to read:"); System.out.println(newString); } // end of main () }// Question5

6. /** * * Question6.java * * This program calculates the simple interest of a loan with a * principal amount of $1000 for the tenure of 5 years at 5.0% * rate of interest. Simple interest(SI) is calculated using the formula * SI = (principal * period in years * rate of interest)/100 * * Created: Jan 30, 2016 * * @author * @version 1 */ public class Question6 { .


Savitch, Absolute Java 6/e, Global Edition: Chapter 1, Instructor’s Manual

public static void main(String[] args) { double simple_int; double princi_amnt = 1000; double int_rate = 5.0; double no_of_yrs = 5.0; simple_int = (princi_amnt * int_rate * no_of_yrs) / 100; System.out.println("Simple Interest for Loan =" + simple_int); } }

7. /** * Question7.java * * This program outputs the number of hours, minutes, * and seconds that corresponds to 50391 total seconds. * The output should be 13 hours, 59 minutes, and 51 seconds. * * Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ public class Question7 { public static void main(String[] args) { int hours, minutes, seconds; // These are calculated int totalSeconds = 50391; // 3600 seconds per hour; use integer division hours = totalSeconds / 3600; // Get remaining seconds after hours are // accounted for and then divide by 60 // to get minutes minutes = (totalSeconds % 3600) / 60; // Get remaining seconds after minutes are // accounted for. Could just % 60 since // 60 divides into 3600. .


Savitch, Absolute Java 6/e, Global Edition: Chapter 1, Instructor’s Manual

seconds = (totalSeconds % 3600) % 60; System.out.println(totalSeconds + " seconds is " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds."); } } // Question 7

8. /** Program to calculate vehicle’s average speed with given time and distance */ /** * * Question8.java * * The program calculates the average speed (in miles per hour) * of a vehicle given the time duration of travel in minutes * and distance traveled in miles. * Formula used to find the average speed is * Average_Speed(miles/hour) = (distance/time_in_mins) * 60 * The program ensures that the naming conventions of * variables and constants, and formatting style used are as per * recommendations mentioned in the book. * * Created: Jan 30, 2016 * * @author * @version 1 */ public class Question8 { /* 180 miles */ public static final double distance = 180; /* 20 minutes and 30 seconds */ public static final double time = 20.5; public static void main(String[] args) { double average_speed; System.out.println("Distance traveled: "+distance+" miles"); System.out.println("Time taken: "+time+" mins"); // computes average speed average_speed = (distance / time) * 60; // prints average speed in miles per hour .


Savitch, Absolute Java 6/e, Global Edition: Chapter 1, Instructor’s Manual

System.out.println("Average speed is " + average_speed + " miles per hour."); } }

9. /** * Question9.java * * Estimate ideal body weight. * * Created: Fri Apr 27 2014 * * @author Kenrick Mock * @version 1 */ public class Question9 { public static void main(String[] args) { int heightFeet = 5; int heightInches = 5; System.out.println("Your ideal body weight is "); int weight = 110 + ((heightFeet - 5)*12 + heightInches) * 5; System.out.println(weight + " pounds."); } } // Question 9

10. /** * Question10.java * * Estimate fatal dose of caffeine in mg * * Created: Tue May 19 2015 * * @author Kenrick Mock * @version 1 */ public class Question10 .


Savitch, Absolute Java 6/e, Global Edition: Chapter 1, Instructor’s Manual

{ public static void main(String[] args) { int mgCaffeinePerDrink = 160; int mgFatal = 10 * 1000; // Convert 10 grams to milligrams int drinksFatal = mgFatal / mgCaffeinePerDrink; System.out.println("It will take approximately " + drinksFatal + " drinks at " + mgCaffeinePerDrink + " mg of caffeine per drink to be lethal."); } } // Question 10

.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

Chapter 2

Console Input and Output Key Terms console I/O System.out.println print versus println System.out.printf format specifier field width conversion character e and g right justified-left justifie more arguments (for printf) format string new lines %n legacy code NumberFormat package java.text import statement, java.util java.lang import patterns percentages e-notation mantissa import nextInt, whitespace nextDouble, word empty string echoing input

Brief Outline 2.1 Screen Output System.out.println Formatting Output with printf Money Formats Using NumberFormat Importing Packages and Classes Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

The DecimalFormat Class 2.2 Console Input Using the Scanner Class The Scanner Class The Empty String Other Input Delimiters 2.3 Introduction to File Input Teaching Suggestions This chapter discusses both the topics of input and output for Java programs. The Chapter features the Scanner class, which is the new input option available in Java 5.0. Other options for input like the original Java class BufferedReader and the JOptionPane that were covered in previous versions of this text are no longer covered. Outputting information is something the students have already seen and done. However, this section deals with outputting in a way so that the information is formatted. This is especially important when dealing with money or decimal numbers. Students may have already seen results that did not look nice when printed to the screen. Several of the built-in formatters are introduced to help students get better looking results when they output. Also introduced is using System.out.printf for outputting information to the screen. The programs that the students have been able to write so far have not been able to require input from the user. They have simply been computations that the computer executes and gives results for. Now it is time to introduce a way for the students to get user input and use that input in their computations. The method that is introduced makes use of the java.util.Scanner class, which is new to Java 5.0. Upon creating an instance of the Scanner object, the programmer can use the nextInt, nextDouble, next, nextLine and other methods to get input from the keyboard. The Scanner delineates different input values using whitespace.

Key Points println Output. We have seen using System.out.println already, but it is important to once again note that we can output Strings as well as the values of variables of primitive type or a combination of both. println versus print. While println gives output and then positions the cursor to produce output on the next line, print will ensure that multiple outputs appear on the same line. Which one you use depends on how you want the output to look on the screen. System.out.printf. This new feature of Java 5.0 can be used to help format output to the screen. System.out.printf takes arguments along with the data to be outputted to format the output as specified by the user. This feature is similar to the printf function that is available in the C language.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

Outputting Amounts of Money. When we want to output currency values, we would like the appropriate currency markers to appear as well as our output to have the correct number of decimal places (if dollars and cents). Java has built in the facilities for giving currency output for many countries. This section introduces the idea that there are packages in Java, and that these packages may contain classes that can be useful. In order to gain access to classes in another package, we can use an import statement. We can then create an instance of the NumberFormat class to help us output currency in the proper format. DecimalFormat Class. We might also like to format decimal numbers that are not related to currency. To do this, we can use the DecimalFormat class. When we use this class, we need to give a pattern for how we want the output to be formatted. This pattern can include the number of digits before and after a decimal point, as well as helping us to format percentages. Keyboard Input Using the Scanner Class. To do keyboard input in a program, you need to first create an instance of the Scanner class. This may be the first time the students are required to create an instance of an object using the keyword new. The methods for the Scanner class, nextInt, nextDouble, and next are used to get the user’s input. The nextLine method reads an entire line of text up to the newline character, but does not return the newline character.

Tips Different Approaches to Formatting Output. With the addition of System.out.printf in Java 5, there are now two distinct ways to format output in Java programs. This chapter of the book will discuss both methods. Formatting Money Amounts with printf. When formatting output that is of currency, the most common way that the programmer wants the user to see the ouput is with only two decimal places. If the amount of money is stored as a double, you can use %.2f to format the output to two decimal places. Legacy Code. Code that is in an older style or an older language, commonly called legacy code can often be difficult and expensive to replace. Many times, legacy code is translated to a more modern programming language. Such is the legacy of printf being incorporated into Java. Prompt for Input. It is always a good idea to create a meaningful prompt when asking the user to provide input to the program. This way the user knows that the program is waiting for a response and what type of response he/she should provide. Echo Input. It is a good idea to echo the user’s input back to them after they have entered it so that they can ensure its accuracy. However, at this point in time, we have no way to allow for them to answer if it is correct and change it if it is not. Later on, we will introduce language constructs (if-statements) that will help us do this type of operation. For now, this tip can serve as a good software engineering practices tip.

Pitfalls Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

Dealing with the Line Terminator ‘\n’. This pitfall illustrates the important point that some of the methods of the Scanner class read the new line character and some methods do not. In the example shown, nextInt is used to show a method that does not read the line terminator. The nextInt method actually leaves the new line character on the input stream. Therefore, the next read of the stream would begin with the new line character. The method readLine does read the line terminator character and removes it from the input stream. This pitfall is one that should be discussed when reading input of different types from the same input stream.

Programming Example Self-Service Check Out. This example program is an interactive check-out program for a store, where the user inputs the information about the items that are being purchased and the program outputs the total amount owed for the purchase. It illustrates the use of the Scanner class as well as System.out.printf. Programming Projects Answers 1. /** * Question1.java * * This program uses the Babylonian algorithm, using five * iterations, to estimate the square root of a number n. * Created: Sat Mar 05, 2005 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; public class Question1 { public static void main(String[] args) { // Variable declarations Scanner scan = new Scanner(System.in); double guess; int n; double r; System.out.println("This program makes a rough estimate for square roots."); System.out.println("Enter an integer to estimate the square root of: "); n = scan.nextInt(); // Initial guess Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

guess = (double) n/2; // First guess r = (double) n/ guess; guess = (guess+r)/2; // Second guess r = (double) n/ guess; guess = (guess+r)/2; // Third guess r = (double) n/ guess; guess = (guess+r)/2; // Fourth guess r = (double) n/ guess; guess = (guess+r)/2; // Fifth guess r = (double) n/ guess; guess = (guess+r)/2; // Output the fifth guess System.out.printf("The estimated square root of %d is %4.2f\n", n, guess); } } // Question1 2. /** * Question2.java * * This program outputs a name in lowercase to a name in Pig Latin * with the first letter of each name capitalized. It inputs the * names from the console using the Scanner class. * Created: Sat Mar 05, 2005 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; public class Question2 { public static void main(String[] args) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

// Variable declarations Scanner scan = new Scanner(System.in); String first; String last; System.out.println("Enter your first name:"); first = scan.nextLine(); System.out.println("Enter your last name:"); last = scan.nextLine(); System.out.println(first + " " + last + " turned to Pig Latin is:"); // First convert first name to pig latin String pigFirstName = first.substring(1,first.length()) + first.substring(0,1) + "ay"; // Then capitalize first letter pigFirstName = pigFirstName.substring(0,1).toUpperCase() + pigFirstName.substring(1,pigFirstName.length()); // Repeat for the last name String pigLastName = last.substring(1,last.length()) + last.substring(0,1) + "ay"; // Then capitalize first letter pigLastName = pigLastName.substring(0,1).toUpperCase() + pigLastName.substring(1,pigLastName.length()); System.out.println(pigFirstName + " " + pigLastName); } } // Question2 3. /** * * Question3.java * * The program reads two integer numbers to perform division operation * and display the dividend, divisor, quotient and remainder * values on the screen. * * Created: Jan 30, 2016 * * @author * @version 1 */ import java.util.Scanner; public class Question3 { public static void main(String[] args) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

Scanner keyboard = new Scanner(System.in); System.out.print("Enter the first number :"); int firstNumber = keyboard.nextInt(); System.out.print("Enter the second number :"); int secondNumber = keyboard.nextInt(); keyboard.close(); int quotient = firstNumber / secondNumber; int remainder = firstNumber % secondNumber; System.out.println("Dividend = " + firstNumber); System.out.println("Divisor = " + secondNumber); System.out.println("Quotient = " + quotient); System.out.println("Remainder = " + remainder); } }

4. /** * * Question4.java * * This program calculates the time required to travel * a distance of 55 miles at an average speed of 15 miles * per hour. The travel time is displayed in hours and minutes on the screen. * * Created: Jan 30, 2016 * * @author * @version 1 */ public class Question4 { public static void main(String[] args) { double distance = 55.0; double averageSpeed = 15; int hour, minutes; double timeTaken; timeTaken = distance / averageSpeed; hour = (int) timeTaken; minutes = (int) ((timeTaken - hour) * 60); System.out.println("Time and distance covered = " + distance); System.out.println("Average Speed = " + averageSpeed); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

System.out.println("Total Time taken is= " + hour + "hour " + minutes + "minutes"); } }

5. /** * * Question5.java * * The program reads a student's academic result in * percentage, converts it into Grade Point Average (GPA) * out of scale 4 and prints the same on the output console. * * GPA is obtained using the formula * GPA = (percentage/100) * 4 * * Created: Jan 30, 2016 * * @author * @version 1 */ import java.util.Scanner; public class Question5 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter percentage of marks :"); double percentage = keyboard.nextDouble(); keyboard.close(); double gpa = (percentage / 100) * 4; System.out.println("GPA = (" + percentage + "/100)*4 = " + gpa); } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

6.

/** * Question6.java * * Created: Sat Nov 08 15:41:53 2003 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ import java.util.Scanner; public class Question6 { public static final int WEIGHT_OF_CAN_SODA_GRAMS = 30; public static final double AMT_SWEETNR_IN_SODA = 0.001; public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("Enter the amount of grams of " + "sweetener needed to kill the " + "mouse: "); int amountNeededToKillMouse = keyboard.nextInt();

System.out.println("Enter the weight of the mouse " + "in pounds."); int weightOfMouse = keyboard.nextInt();

System.out.println("Enter the desired weight of the" + " dieter in pounds."); double desiredWeight = keyboard.nextDouble();

double amountPerCanGrams = (double)WEIGHT_OF_CAN_SODA_GRAMS * AMT_SWEETNR_IN_SODA; double proportionSwtnrBodyWeight = (double) (amountNeededToKillMouse / weightOfMouse );

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

double amtNeededToKillFriend = proportionSwtnrBodyWeight * desiredWeight; double cansOfSoda = amtNeededToKillFriend * amountPerCanGrams; System.out.println("You should not drink more than " + cansOfSoda + " cans of soda."); } } // Question6 7. /** * Question7.java * * Created: Sat Nov 08 15:41:53 2003 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ import java.util.Scanner; public class Question7 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter the price of the item " + "from 25 cents to one dollar " + "in five cent increments:"); int priceOfItem = scan.nextInt(); int change = 100 - priceOfItem; int numQuarters = change / 25; change = change - (numQuarters * 25); int numDimes = change / 10; change = change - (numDimes * 10); int numNickels = change / 5;

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

System.out.println("You bought an item for " + priceOfItem + " cents and gave me one dollar, so your change is\n" + numQuarters + " quarters,\n" + numDimes + " dimes, and \n" + numNickels + " nickels."); } } // Question7 8. /** * * Question8.java * * This programs reads a line of text that contains * 3 words separated by comma and prints each word * in a different line. * * Created: Jan 30, 2016 * * @author * @version 1 */ import java.util.Scanner; public class Question8 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); //Sets comma as a delimiter between words keyboard.useDelimiter(","); System.out.print("Enter your text :"); //read first word String word1 = keyboard.next(); //read second word String word2 = keyboard.next(); //read third word String word3 = keyboard.next(); System.out.println(word1); System.out.println(word2); System.out.println(word3); } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

9. /** * Question9.java * * Created: Sat Nov 08 15:41:53 2003 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ import java.util.Scanner; public class Question9 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("Enter a line of text: " ); String firstString = keyboard.nextLine(); int position = firstString.indexOf("hate"); String firstPart = firstString.substring(0, position); String afterHate = firstString.substring(position + 4); String newString = firstPart + "love" + afterHate; System.out.println("I have rephrased that line to read:\n" + newString); } } // Question9

10. /** * Question10.java * * This program outputs a bill for three items. * The bill should be formatted in columns with 30 * characters for the name, 10 characters for the Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

* quantity, 10 characters for the price, and * 10 characters for the total. * * Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; public class Question10 { public static double SALESTAX = 0.0625; public static void main(String[] args) { String name1, name2, name3; int quantity1, quantity2, quantity3; double price1, price2, price3; double total1, total2, total3; double subtotal; double tax; double total; Scanner kbd = new Scanner(System.in); System.out.println("Name of item 1:"); name1 = kbd.nextLine(); System.out.println("Quantity of item 1:"); quantity1 = kbd.nextInt(); System.out.println("Price of item 1:"); price1 = kbd.nextDouble(); kbd.nextLine(); System.out.println("Name of item 2:"); name2 = kbd.nextLine(); System.out.println("Quantity of item 2:"); quantity2 = kbd.nextInt(); System.out.println("Price of item 2:"); price2 = kbd.nextDouble(); kbd.nextLine(); System.out.println("Name of item 3:"); name3 = kbd.nextLine(); System.out.println("Quantity of item 3:"); quantity3 = kbd.nextInt(); System.out.println("Price of item 3:"); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

price3 = kbd.nextDouble(); kbd.nextLine(); total1 = quantity1 * price1; total2 = quantity2 * price2; total3 = quantity3 * price3; subtotal = total1 + total2 + total3; tax = SALESTAX * subtotal; total = tax + subtotal; // Allot 30 characters for the name, then 10 // for the quantity, price, and total. The hyphen after the % // makes the field left-justified System.out.printf("%-30s %-10s %-10s %-10s\n", "Item", "Quantity", "Price", "Total"); System.out.printf("%-30s %-10d %-10.2f %-10.2f\n", name1, quantity1, price1, total1); System.out.printf("%-30s %-10d %-10.2f %-10.2f\n", name2, quantity2, price2, total2); System.out.printf("%-30s %-10d %-10.2f %-10.2f\n", name3, quantity3, price3, total3); System.out.println(); System.out.printf("%-52s %-10.2f\n", "SubTotal", subtotal); System.out.printf("%-52s %-10.2f\n", SALESTAX * 100 + " Sales Tax", tax); System.out.printf("%-52s %-10.2f\n", "Total", total); } } // Question 10 11. /** * Question11.java * * This program calculates the total grade for three * classroom exercises as a percentage. It uses the DecimalFormat * class to output the value as a percent. * The scores are summarized in a table. * * Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

import java.text.DecimalFormat; public class Question11 { public static void main(String[] args) { String name1, name2, name3; int points1, points2, points3; int total1, total2, total3; int totalPossible, sum; double percent; Scanner kbd = new Scanner(System.in); System.out.println("Name of exercise 1:"); name1 = kbd.nextLine(); System.out.println("Score received for exercise 1:"); points1 = kbd.nextInt(); System.out.println("Total points possible for exercise 1:"); total1 = kbd.nextInt(); kbd.nextLine(); System.out.println("Name of exercise 2:"); name2 = kbd.nextLine(); System.out.println("Score received for exercise 2:"); points2 = kbd.nextInt(); System.out.println("Total points possible for exercise 2:"); total2 = kbd.nextInt(); kbd.nextLine(); System.out.println("Name of exercise 3:"); name3 = kbd.nextLine(); System.out.println("Score received for exercise 3:"); points3 = kbd.nextInt(); System.out.println("Total points possible for exercise 3:"); total3 = kbd.nextInt(); kbd.nextLine(); totalPossible = total1 + total2 + total3; sum = points1 + points2 + points3; percent = (double) sum / totalPossible; // Allot 30 characters for the exercise name, then 6 // for the score and total. The hyphen after the % // makes the field left-justified System.out.printf("%-30s %-6s %-6s \n", "Exercise", "Score", "Total Possible"); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

System.out.printf("%-30s %-6d %-6d \n", name1, points1, total1); System.out.printf("%-30s %-6d %-6d \n", name2, points2, total2); System.out.printf("%-30s %-6d %-6d \n", name3, points3, total3); System.out.printf("%-30s %-6d %-6d \n", "Total", sum, totalPossible); DecimalFormat formatPercent = new DecimalFormat("0.00%"); System.out.println("\nYour total is " + sum + " out of " + totalPossible + ", or " + formatPercent.format(percent) + " percent."); } } // Question 11

/** * Question12.java * * This program changes "hate" to "love" in a file. It is a bit awkward because * if statements haven't been covered yet. * * Created: Fri Apr 27 2015 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; import java.io.FileInputStream; import java.io.FileNotFoundException; public class Question12 { public static void main(String[] args) { Scanner fileIn = null; // Initializes fileIn to an empty object try { // Attempt to open the file fileIn = new Scanner( new FileInputStream("file.txt")); } catch (FileNotFoundException e) { // If the file could not be found, this code is executed // and then the program exits System.out.println("File not found."); System.exit(0); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

} // If the program gets here then // the file was opened successfully String line; line = fileIn.nextLine(); int position = line.indexOf("hate"); System.out.println( line.substring(0,position) + "love" + line.substring(position+4)); fileIn.close(); } } // Question12

Question 13: No solution provided

/** * Question14.java * * This first version inputs the name of the drink and number of mg of caffeine * and outputs how many drinks it will take to be lethal. * * Created: Tue May 19 2015 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; public class Question14 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int mgCaffeinePerDrink = 0; int mgFatal = 10 * 1000; // Convert 10 grams to milligrams String drinkName = ""; System.out.println("Enter the name of the drink."); drinkName = keyboard.nextLine(); System.out.println("Enter the number of milligrams of caffeine per drink."); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

mgCaffeinePerDrink = keyboard.nextInt(); // Convert to a double to get floating point result double drinksFatal = (double) mgFatal / mgCaffeinePerDrink; System.out.println("It will take approximately " + drinksFatal + " drinks of " + drinkName + " at " + mgCaffeinePerDrink + " mg of caffeine per drink to be lethal."); } } // Question 14 /** * Question14.java * * This second version inputs the name of the drink and number of mg of caffeine * from a file and outputs how many drinks it will take to be lethal. * * Created: Tue May 19 2015 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; import java.io.FileInputStream; import java.io.FileNotFoundException; public class Question14 { public static void main(String[] args) { Scanner fileIn = null; try { fileIn = new Scanner(new FileInputStream("drink.txt")); } catch (FileNotFoundException e) { System.out.println("drink.txt not found."); System.exit(0); } int mgCaffeinePerDrink = 0; int mgFatal = 10 * 1000; // Convert 10 grams to milligrams String drinkName = ""; // Read the name of the drink drinkName = fileIn.nextLine(); // Read the milligrams of caffeine Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 2, Instructor’s Manual

mgCaffeinePerDrink = fileIn.nextInt(); // Convert to a double to get floating point result double drinksFatal = (double) mgFatal / mgCaffeinePerDrink; System.out.println("It will take approximately " + drinksFatal + " drinks of " + drinkName + " at " + mgCaffeinePerDrink + " mg of caffeine per drink to be lethal."); fileIn.close(); } } // Question 14

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

Chapter 3

Flow of Control Key Terms parentheses if-else if-else with multiple statements compound statements indenting multiway if-else switch statement controlling expression case labels break default conditional operator Boolean expression lexicographical ordering compareTo compareToIgnoreCase && means “and” || means “or” truth tables Boolean variables in assignments short-circuit evaluation lazy evaluation complete evaluation precedence rules associativity rules higher precedence binding side effects while and do-while compared executing the body zero times algorithm pseudocode sentinel values for statement empty statement infinite loop nested loop break statement continue statement label Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

off-by-one error incremental development cod review pair programming assertion assert assertion check

Brief Outline 3.1 Branching Mechanism If-else statements Omitting the else Compound Statements Nested Statements Multiway if-else Statement The switch Statement The Conditional Operator 3.2 Boolean Expressions Simple Boolean Expressions Lexicographic and Alphabetic Order Building Boolean Expressions Evaluating Boolean Expressions Short-Circuit and Complete Evaluation Precedence and Associativity Rules 3.3 Loops While statement and do-while statement Algorithms and Pseudocode The for Statement The Comma in for Statements Nested Loops The break and continue Statements The exit Statement 3.4 Debugging Loop Bugs Tracing Variables General Debugging Techniques Preventive Coding Assertion Checks Teaching Suggestions This chapter discusses flow of control using both selection and iteration. The if-statement and loops are introduced both in this chapter. With both topics in one chapter, it is conceivable that this chapter will take longer for students to work through than many of the others in the text.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

Branching, or selection, is introduced using the if-statement, the if-else statement, and the switch statement. Multiple paths and therefore, nested if-else statements are introduced. As the last form of selection available, the conditional operator is introduced at the end of the chapter. The coverage of the conditional operator is optional and can be omitted. The section on Boolean expressions follows the introduction of selection. However, some instructors might choose to put the second section before the first so that more complicated conditions on if-statements can be introduced right away. The third section on looping introduces all three looping constructs available inside Java. Loops can pose many challenges for students as illustrated by the Pitfall sections in the chapter. Having all of these tools available to them, students can write some fairly complex programs at the end of this chapter. However, what usually begins to happen is that students will write code that has errors. Finding these errors can be tedious and time-consuming. The last section on tracing loops, common loop bugs, and debugging is included as a way to help students begin to understand how to track down their errors in code. An option that would be useful to them if it is available would be to introduce and discuss the use of your computing environment’s debugger at this time. Key Points If-else statement & Multiway if-else Statement. There are many ways to give the program a sense of choice or branching. First, we can use an if-statement by itself without an else. This allows us the option to do something or skip over it. We can also use an if-else statement, which allows us to take one path or another. Lastly, we can use combinations of these to have more than two choices for execution. As the number of paths increase, so does the complexity of code for the students. Students should be able to follow as well as write these more complicated branching code segments. The switch Statement. The switch also allows for branching, but it has limitations as to what the condition for branching can be. Also, the syntax contains more keywords and is more structured than the if-else. Discussion of the break statement is needed here as the switch will not function properly without the correct use of break between the cases. The Methods equals and equalsIgnoreCase. Since the equality operator cannot be used on objects, we have the equals method. On Strings, we also have the equalsIgnoreCase method when we are concerned with the content of the String, not necessarily that all of the same words are capitalized within the String. The equalsIgnoreCase can be important especially when taking user input. If you ask the user to input a certain letter as a choice, some of them might instinctively make that letter capital. If you are not ignoring case, equals may return false even if the user has pressed the correct key. The “and” Operator &&. In the section on Boolean Expressions, we introduce the Boolean operators && and ||. It is important for students to realize when the && operator returns true and when it returns false.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

The “or” Operator. The introduction of the || operator once again compels students to understand when it will return true and when it will return false in their programs. The Boolean Values are true and false. In Java, the values for the boolean data type are constants that are defined within the system. Therefore, they must always be written in all lower case as true or false. true and false are not Numbers. This point coincides with the last one because in some other languages, true and false can be represented as the numbers 1 and 0. However, in Java this is not the case and trying to use a number where the system expects a boolean value will cause a compiler error. You also can not typecast a number to a boolean or a boolean to a number. Rules for Evaluating Expressions. The precedence and associativity rules for evaluating expressions are given in charts within this chapter. Understanding how to evaluate a boolean expression is as important as how to evaluate the arithmetic expressions in Chapter 1. Syntax for while and do-while Statements. The while and do-while loops are the indefinite loops supported by Java. They also illustrate the differences between an entry-test and an exit-test loop. The for Statement. The for loop is a definite loop or counting loop that is also an entry-test loop. The syntax for the for loop is different from the other two loops and has a loop counter built right into the construct. However, in Java, we can have more than one statement inside the parts of the for-loop separated by commas and we can also leave parts empty, which can create many different results when using a for-loop. Assertion Checking. The assert statement can help you ensure that a particular condition is true at a given time in a program. You can use this feature to make sure that a variable is positive at a given point in the program, for example. You need to turn on assertion checking to make Java execute the assert statements in the program. If at any time, an assertion fails, the program will exit with an error. Tips Placing of Braces. The book introduces its way of placing braces for an if-statement. There are other options, which are presented. Style will vary on what an instructor/programmer wants. There is no correct way to place your braces. However, having braces or not definitely makes a difference in the code. Naming boolean Variables. It is helpful to name boolean variables with names that will indicate what they are holding the values for. Names like isFull, isEmpty, etc will help distinguish what it is that you are holding the value for and make the code that is written easier for others to read and understand. End of Input Character. This tip is optional and discusses how the user can indicate the end of input to the program. This involves the introduction of control characters in the system and uses the ConsoleIn classes in the example. Therefore, instructors that did not cover ConsoleIn will Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

not be able to cover this point to its entirety, but could discuss how the program will know when the user is done entering input to the program. Repeat N Times Loops. The easiest way to repeat something a definitive number of times is to use the for-loop. The loop counter does not have to be referenced in the loop body, so it can simply just keep track of how many times the loop has been executed.

Pitfalls Forgetting a break in a Switch Statement. This is an important pitfall because of the fact that the compiler will not tell you that you have forgotten it. Simply, the program will not execute correctly. Therefore, it is important to show what will happen if the break statements are not properly inserted in the switch statement. Using = Place of ==. Now that we have introduced the notion of equality, one element that is of confusion is that the double equals sign is what actually tests for equality, while the single equals is assignment. This is different than in mathematics and can be confusing for students. In some instances, the confusion of the two may not even cause a compiler error, but once again the program will not run correctly. Using == with Strings. Since Strings are objects, the equality operator does not always give the correct result and should not be used to check for two Strings that contain the same character sequence. The equals method is introduced as the way to achieve the correct answer always to this problem. Strings of Inequalities. Unlike in mathematics, where x < 10 < y is understood, Java will not be able to understand the previous statement. Therefore, it needs to be broken up into two parts, x < 10 && 10 < y. Students who fail to do this will usually receive a compiler error. Extra Semicolon in a for Statement. The extra semicolon at the end of the for loop will not cause a compiler error, but will cause the loop to execute the proper amount of times with an empty loop body. This can also arise with the while loop. However, the do-while needs the semicolon at the end of its condition to work properly. Infinite Loops. It is quite possible and quite common to accidentally write a loop that never ends because the condition on the loop will never become false. These infinite loops will generally cause errors to be generated when the program is run and can be difficult to spot. It is helpful in these cases to use the technique of tracing variables to find the problem. Examples State Income Tax. In this example we see how to use multiway if-else statements with the example of computing how much state income tax one owes. Depending on your level of income, the program gives the amount of tax that should be paid. This problem’s solution is given in the text in Display 3.1.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

Averaging a List of Scores. The second example in this chapter looks at a program that will average a list of scores inputted by the user. This example brings together the input/output from last chapter and the looping that was introduced in this chapter. The code is once again presented in Display 3.8. Programming Projects Answers 1. /** * Question1.java * * This program uses the Babylonian algorithm, and keeps looping * until the current guess is within 1% of the previous guess value * to estimate the square root of a number n. * * Created: Sat Mar 05, 2005 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; public class Question1 { public static void main(String[] args) { // Variable declarations Scanner scan = new Scanner(System.in); double guess, previousGuess; int n; double r; System.out.println("This program estimate square roots."); System.out.println("Enter an integer to estimate the square root of: "); n = scan.nextInt(); // Initial guess guess = (double) n/2; previousGuess = n; // Keep looping as long as (oldguess - guess) / old guess is > 0.01. // The ratio should always be positive since we approach the // square root starting at n/2 and work our way down to the actual square root. while (((previousGuess-guess)/previousGuess) > 0.01) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

{ r = (double) n / guess; previousGuess = guess; guess = (guess+r)/2; System.out.println("Current guess: " + guess); } System.out.printf("\nThe estimated square root of %d is %6.2f\n", n , guess); } } // Question1 2. /** * * Question2.java * * This program allows the user to input the color codes of the five * colors to be used in a stripe on fabric. As the user enters a color * code, the program checks for 2 conditions: 1. Whether the color * code entered is one among the color codes the user is allowed to * choose, and 2. Whether the color code entered is same as the previously * entered color code. * * Created: Jan 30, 2016 * * @author * @version 1 */ import java.util.Scanner; public class Question2 { public static void main(String s[]) { //Declare and initialize allowed color codes in the fabric's color stripe char color1 = 'R', color2 = 'R', color3 = 'R', color4 = 'R', color5 = 'R'; int i = 1; //flag to set it to false when two conditions of the color stripe are not met boolean flag = true; String word; Scanner keyboard = new Scanner(System.in); System.out.println("Colors available for selection with Character Code"); System.out.println("RED(R)"); System.out.println("Green(G)"); System.out.println("Blue(B)"); System.out.println("Color Selection for the strips"); //Read the user input color code until the 2 conditions matched for the first color Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

while (flag) { System.out.print("Enter the color character code for the first color = "); word = keyboard.next(); color1 = word.charAt(0); if (color1 != 'R' && color1 != 'G' && color1 != 'B') System.out.println("Wrong character color "); else flag = false; } flag = true; //Read the user input color code until the 2 conditions matched for the second color while (flag) { System.out.print("Enter the color character code for the second color = "); word = keyboard.next(); color2 = word.charAt(0); if (color2 != 'R' && color2 != 'G' && color2 != 'B') System.out.println("Wrong character color "); else if (color1 == color2) System.out.println("Adjacent colors cannot be same"); else flag = false; } flag = true; //Read the user input color code until the 2 conditions matched for the third color while (flag) { System.out.print("Enter the color character code for the third color = "); word = keyboard.next(); color3 = word.charAt(0); if (color3 != 'R' && color3 != 'G' && color3 != 'B') System.out.println("Wrong character color "); else if (color2 == color3) System.out.println("Adjacent colors cannot be same"); else flag = false; } //Read the user input color code until the 2 conditions matched for the fourth color flag = true; while (flag) { System.out.print("Enter the color character code for the fourth color = "); word = keyboard.next(); color4 = word.charAt(0); if (color4 != 'R' && color4 != 'G' && color4 != 'B') System.out.println("Wrong character color "); else if (color3 == color4) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

System.out.println("Adjacent colors cannot be same"); else flag = false; } //Read the user input color code until the 2 conditions matched for the fifth color flag = true; while (flag) { System.out.print("Enter the color character code for the fifth color = "); word = keyboard.next(); color5 = word.charAt(0); if (color5 != 'R' && color5 != 'G' && color5 != 'B') System.out.println("Wrong character color "); else if (color4 == color5) System.out.println("Adjacent colors cannot be same "); else flag = false; } System.out.println("Final Pattern is =" + color1 + "-" + color2 + "-" + color3 + "-" + color4 + "-" + color5); } } 3. /** * * Question3.java * * This program reads the mass of a car in kilograms and calculates * the car's weight on the Earth and the Moon in Newtons. * Weight on earth = (mass of the body) * 9.81 (earth's gravity in m/s^2). * Weight on moon = (mass of the body) * (9.81/6) (1/6 the of gravity on earth). * * Created: Jan 31, 2016 * * @author * @version 1 */ import java.util.Scanner; public class Question3 { public static void main(String[] args) { //Declare the variables double mass = 0, weightOnEarth, weightOnMoon; boolean flag = true; char ch; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

//Scanner object to read the user input Scanner keyboard = new Scanner(System.in); while (flag) { System.out.println("Calculating the weight of the car " + "in Newtons on Earth or Moon"); System.out.println("Press M for Moon"); System.out.println("Press E for Earth"); System.out.println("Press X for Exit"); System.out.print("Enter your choice="); ch = keyboard.next().charAt(0); if (ch == 'M' || ch == 'E') { System.out.print("Enter the mass of the car in Kg="); mass = keyboard.nextDouble(); } switch (ch) { case 'M': weightOnMoon = (mass * 9.81) / 6; System.out.println("Weight on Moon in " + "Newtons = (" + mass + " in kg ) * (9.81 in m/s2) = " + weightOnMoon + " N"); break; case 'E': weightOnEarth = (mass * 9.81); System.out.println("Weight on Earth in Newtons" + " = (" + mass + " in kg ) * (9.81 in m/s2)" + " = " + weightOnEarth + " N"); break; case 'X': flag = false; break; } } } } 4. /** * Question4.java * * * Created: Sun Nov 09 16:00:30 2003 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

* @version 2 */ import java.util.Scanner; import java.text.NumberFormat; public class Question4 { public static void main (String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("Enter the cost of the item " + "in the present as a decimal with" + " no dollar sign:"); double price = keyboard.nextDouble(); System.out.println("Enter the number of years from now" + " you will be purchasing the item:"); int years = keyboard.nextInt(); System.out.println("Enter the rate of inflation as " + "a decimal number.\nFor " + "example, enter 5.6 for 5.6%"); double inflation = keyboard.nextDouble() / 100; double newPrice = price; for ( int i = 0; i < years; i++ ) { newPrice = newPrice + (newPrice * inflation); } // end of for () NumberFormat moneyFormater = NumberFormat.getCurrencyInstance(); System.out.println("in " + years + " years, your item that costs " + moneyFormater.format(price) + " now, will cost " + moneyFormater.format(newPrice)); } // end of main () }// Question4 5. /** * Question5.java * * Created: Sun Nov 09 16:14:44 2003 Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

* Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ import java.text.NumberFormat; public class Question5 { public static final int STEREO_COST = 1000; public static final double YEARLY_INTEREST = 0.18; public static final double MONTHLY_INTEREST = 0.015; public static final int MONTHLY_PAYMENT = 50; public static void main(String[] args) { NumberFormat moneyFormater = NumberFormat.getCurrencyInstance(); int monthNumber = 1; double amountRemaining = STEREO_COST; double interestAccrued = 0; double diff = 0; double totalInterestPaid = 0; while ( amountRemaining > 0.0) { //System.out.println("For month number " + monthNumber); /*System.out.println("You will pay " + moneyFormater.format(MONTHLY_PAYMENT));*/ interestAccrued = amountRemaining * MONTHLY_INTEREST; totalInterestPaid = totalInterestPaid + interestAccrued; /*System.out.println(moneyFormater.format(interestAccrued) + " will go towards interest.");*/ diff = MONTHLY_PAYMENT - interestAccrued; /*System.out.println(moneyFormater.format(diff) + " will go towards principle.");*/ amountRemaining = amountRemaining - diff; /*System.out.println("You still have " + moneyFormater.format(amountRemaining) + " to pay.");*/

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

monthNumber++; } // end of while () System.out.println("It will take you " + monthNumber + " months to pay off the stereo."); System.out.println("You will have paid " + moneyFormater.format(totalInterestPaid) + " in interest."); } } // Question5

6. /** * Question6.java * * Created: Sun Nov 09 16:14:44 2003 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ import java.util.Scanner; public class Question6 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); while ( true ) { System.out.println("Enter the initial size of the green crud" + " in pounds.\nIf you don't want to " + "calculate any more enter -1."); int initialSize = keyboard.nextInt(); if ( initialSize == -1) { break; } // end of if () System.out.println("Enter the number of days: "); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

int numDays = keyboard.nextInt(); int numOfRepCycles = numDays / 5; int prevPrevGen = 0; int prevGen = initialSize; int finalAnswer = initialSize; for ( int i = 0; i < numOfRepCycles; i++ ) { finalAnswer = prevPrevGen + prevGen; prevPrevGen = prevGen; prevGen = finalAnswer; } // end of for () System.out.println("The final amount of green crud will be: " + finalAnswer + " pounds.\n"); } // end of while () } } // Question6 7. /** * * Question7.java * * This program accepts as input, the starting and ending numbers in a * range of numbers and then prints all Armstrong numbers that present * in the range. An n-digit long number is Armstrong number if the sum * of nth power of all the digits is equal to the number itself. The * program prompts for new values of start and end range until the * user says he/she is through. Created: Jan 31, 2016 * * @author * @version 1 */ import java.util.Scanner; public class Question7 { public static void main(String[] args) { //Declare all the required variables int startRange, endRange, index, digits, temp, remainder, sum; char choice = 'Y'; Scanner keyboard = new Scanner(System.in); //Loop until the user inputs 'N' Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

while (choice == 'Y') { System.out.print("\nEnter the starting number of the range :"); startRange = keyboard.nextInt(); System.out.print("Enter the ending number of the range :"); endRange = keyboard.nextInt(); System.out.println("\nThe Armstrong numbers between " + "the given range are :"); //Start a loop from startRange to endRange for (index = startRange; index <= endRange; index++) { temp = index; digits = 0; /* * count the total number of digits by repeatedly * dividing the number by 10 until the remainder * becomes zero */ while (temp != 0) { digits++; temp = temp / 10; } temp = index; sum = 0; // find sum of the individual digits raise to //the power of number of digits while (temp != 0) { remainder = temp % 10; /* * Add the result of obtaining digit raised to the * number of digits to a variable sum */ sum += Math.pow(remainder, digits); temp = temp / 10; } // check whether sum equals to the number itself if (sum == index) { System.out.println(index + " "); } } System.out.print("Do you want to repeat? (Y/N) : "); choice = keyboard.next().charAt(0); } keyboard.close(); } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

8. /** * * Question8.java * * This program converts an input number into a sequence of characters * as per the symbol codes associated with each digit and based on * following rules. * a. If the first and the last digits are odd, both are to be coded as ‘X’. * b. If the first and the last digits are even, both are to be coded as ‘$’. * c. If the last digit is ‘0’, it is to be coded as ‘#’ * * Created: Jan 30, 2016 * * @author * @version 1 */ import java.util.Scanner; public class Question8 { public static void main(String[] args) { int inputNumber, tempNumber, noOfDigits, firstDigit, lastDigit; String numerals = "0123456789"; String codes = "*BEA@FK%RM"; String encoded = null; Scanner keyboard = new Scanner(System.in); System.out.print("Enter the Number to be decoded :"); inputNumber = keyboard.nextInt(); tempNumber = inputNumber; noOfDigits = 0; if (inputNumber == 0) noOfDigits = 1; //count the total number of digits while (tempNumber != 0) { noOfDigits++; if (encoded == null) //pick the code associated with the digit encoded = codes.substring(tempNumber % 10, tempNumber % 10 + 1); else //pick the code associated with the digit //and append it to encoded string encoded = codes.substring(tempNumber % 10, tempNumber % 10 + 1) + encoded; tempNumber = tempNumber / 10; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

} if (noOfDigits == 1) { firstDigit = lastDigit = inputNumber; if (lastDigit == 0) encoded = "#"; if (firstDigit % 2 == 0) encoded = "$"; if (firstDigit % 2 != 0) encoded = "X"; } else { firstDigit = inputNumber / (int) Math.pow(10, noOfDigits - 1); lastDigit = inputNumber % 10; if (lastDigit == 0) encoded = encoded.substring(0, noOfDigits - 1) + "#"; else if (firstDigit % 2 == 0 && lastDigit % 2 == 0) encoded = "$" + encoded.substring(1, noOfDigits - 1) + "$"; else if (firstDigit % 2 != 0 && lastDigit % 2 != 0) encoded = "X" + encoded.substring(1, noOfDigits - 1) + "X"; } System.out.println("Encoded String is = " + encoded); } } 9. /** * Question9.java * * This program calculates the total grade for N classroom * exercises as a percentage. It uses the DecimalFormat class * to output the value as a percent. * * Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; import java.text.DecimalFormat; public class Question9 { public static void main(String[] args) { int totalScore = 0, totalPossible = 0; int score, total; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

double percent; Scanner kbd = new Scanner(System.in); int numExercises; System.out.println("How many exercises to input?"); numExercises = kbd.nextInt(); for (int i = 1; i <= numExercises; i++) { System.out.println("Score received for exercise " + i + ":"); score = kbd.nextInt(); System.out.println("Total points possible for exercise " + i + ":"); total = kbd.nextInt(); totalScore += score; totalPossible += total; } percent = (double) totalScore / totalPossible; DecimalFormat formatPercent = new DecimalFormat("0.00%"); System.out.println("\nYour total is " + totalScore + " out of " + totalPossible + ", or " + formatPercent.format(percent) + " percent."); } } // Question 9

10. /** * Question10.java * * This program plays the game of Pig * vs. the computer. * * Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; class Question10 { public static void main(String[] argv) { Scanner keyboard = new Scanner(System.in); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

String s; int scoreComputer = 0, scoreHuman = 0; int turnScore; boolean turnOver; boolean gameOver; int dice; System.out.println("Welcome to the game of Pig!"); System.out.println(); gameOver = false; while (!gameOver) { // ******* HUMAN'S TURN ************/ turnScore = 0; turnOver = false; do { dice = (int) (Math.random() * 6) + 1; System.out.println("You rolled: " + dice); if (dice == 1) { System.out.println("You lose your turn!" + " Your total is " + scoreHuman); turnScore = 0; turnOver = true; } else { turnScore += dice; System.out.println("Your turn score is " + turnScore + " and your " + "total score is " + scoreHuman); System.out.println("If you hold, you will have " + (turnScore + scoreHuman) + " points."); System.out.println("Enter 'r' to roll again, " + "'s' to stop."); s = keyboard.next(); if (s.equals("s")) turnOver = true; } } while (!turnOver); // Add in any points the human got scoreHuman += turnScore; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

System.out.println("Your score is " + scoreHuman); // Check for human winning if (scoreHuman >= 100) { System.out.println("YOU WIN!"); gameOver = true; return; // Exit immediately if win } // ******* COMPUTER'S TURN ************/ System.out.println(); System.out.println("It is the computer's turn."); // It is the computer's turn turnScore = 0; turnOver = false; do { dice = (int) (Math.random() * 6) + 1; System.out.println("The computer rolled: " + dice); if (dice == 1) { System.out.println("The computer lost its turn!" + " Computer total is " + scoreComputer); turnScore = 0; turnOver = true; } else { turnScore += dice; if ((turnScore + scoreComputer) >=100) { // Hold if the computer will win System.out.println("The computer holds."); turnOver = true; } else if (turnScore >= 20) { // Or hold if we get more than 20 this round System.out.println("The computer holds."); turnOver = true; } } } while (!turnOver); // Add in any points the computer got Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

scoreComputer += turnScore; System.out.println("The computer's score is " + scoreComputer); System.out.println(); // Check for computer winning if (scoreComputer >= 100) { System.out.println("THE COMPUTER WINS!"); gameOver = true; } } } } // Question 10

11. /** * Question11.java * * Randomly pick three unique numbers from 1 to 30. * * Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; class Question11 { public static void main(String[] argv) { int num1, num2, num3; do { // Pick three numbers at random num1 = (int) (Math.random() * 30) +1; num2 = (int) (Math.random() * 30) +1; num3 = (int) (Math.random() * 30) +1; } // Keep picking if any two numbers are // the same while ((num1 == num2) || (num1 == num3) || (num2 == num3)); System.out.printf("%d, %d, %d\n", Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

num1, num2, num3); } } // Question 11

Question 12: No solution provided

13. /** * Question13.java * * Find the longest palindrome from a word file. * * Created: Fri Apr 27 2012 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; import java.io.FileInputStream; import java.io.FileNotFoundException; class Question13 { public static void main(String[] args) { Scanner fileIn = null; // Initializes fileIn to an empty object try { // Attempt to open the file fileIn = new Scanner( new FileInputStream("words.txt")); } catch (FileNotFoundException e) { // If the file could not be found, this code is executed // and then the program exits System.out.println("File not found."); System.exit(0); } String word; String longest=""; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

while (fileIn.hasNext()) { word = fileIn.next(); //System.out.println(word); // Check if palindrome int start, end; start = 0; end = word.length()-1; boolean isPalindrome = true; while (start < end) { if (word.charAt(start)!=word.charAt(end)) isPalindrome = false; start++; end--; } if (isPalindrome) { //System.out.println(word); if (word.length() > longest.length()) { longest = word; } } } System.out.println(longest); fileIn.close(); } } // Question 13

14. /** * Question14.java * * Find the word with the most consecutive vowels from a word file. * * Created: Fri Apr 27 2012 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; import java.io.FileInputStream; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

import java.io.FileNotFoundException; class Question14 { public static void main(String[] args) { Scanner fileIn = null; // Initializes fileIn to an empty object try { // Attempt to open the file fileIn = new Scanner( new FileInputStream("words.txt")); } catch (FileNotFoundException e) { // If the file could not be found, this code is executed // and then the program exits System.out.println("File not found."); System.exit(0); } String word; String strVowels=""; int maxVowels = 0; // Track max number of consecutive vowels while (fileIn.hasNext()) { word = fileIn.next(); //System.out.println(word); // Check number of consecutive vowels int vowelCount = 0; int curMax = 0; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if ((c=='a') || (c=='e') || (c=='i') || (c=='o') || (c=='u')) vowelCount++; else vowelCount=0; // remember if this is a new high number of vowels for this word if (vowelCount > curMax) curMax = vowelCount; } if (curMax > maxVowels) { // Remember the word and vowel count if it’sthe max seen so far maxVowels = curMax; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

strVowels = word; } } System.out.println(strVowels + " has " + maxVowels + " consecutive vowels."); fileIn.close(); } } // Question 14

Question 15: No solution provided

16. /** * * Question16.java * * The program reads a file that contains text and prints all the * words which are starting with the an vowel that the user inputs. * * Created: Jan 30, 2016 * * @author * @version 1 */ import java.util.Scanner; import java.io.FileInputStream; import java.io.FileNotFoundException; public class Question16 { public static void main(String[] args) { // Initializes fileIn to empty Scanner fileIn = null; Scanner keyboard = new Scanner(System.in); try { // Attempt to open the file fileIn = new Scanner(new FileInputStream("d:\\phrase.txt")); } catch (FileNotFoundException e) { System.out.println("File not found."); System.exit(0); } char ch; String word; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 3, Instructor’s Manual

System.out.print("Enter a vowel for searching from the file = "); word = keyboard.next(); ch = word.charAt(0); if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u') { System.out.println("Not a Vowel"); System.exit(0); } System.out.println("Following words are found that start with " + " the entered vowel"); while (fileIn.hasNext()) { word = fileIn.next(); if (word.charAt(0) == ch) System.out.println(word); } fileIn.close(); } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

Chapter 4

Defining Classes I Key Terms object method instance member field instance variable new heading method body invocation body return statement return in a void method local variable block compound statement parameter argument call-by-value parameters as local variables formal parameter actual parameter this parameter mask a variable equals toString println used with objects + used with objects recursive method driver program bottom-up testing stub information hiding abstraction encapsulation, public private accessor method, mutator method precondition postcondition Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

overloading method signature constructor constructor arguments resetting object values no-argument constructor default constructor import tokens nextToken hasMoreTokens choosing delimiters

Brief Outline 4.1 Class Definitions Instance Variables and Methods More about Methods Local Variables Blocks Parameters of a Primitive Type Simple Cases with Class Parameters The this Parameter Methods that Return a Boolean Value The Methods equals and toString Recursive Methods 4.2 Information Hiding and Encapsulation public and private Modifiers Accessor and Mutator Methods Preconditions and Postconditions 4.3 Overloading Rules for Overloading 4.4 Constructors Constructor Definitions Default Variable Initializations An Alternative Way to Initialize Instance Variables The StringTokenizer Class

Teaching Suggestions This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the two components of classes. With the introduction of methods, we can discuss parameters and parameter passing. Encapsulation is then introduced with the designation of accessor and mutator methods. Then, the concept of method overloading is introduced. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

Constructors are given coverage in the last section of this chapter. However, some instructors might want to move their introduction earlier as one cannot make an instance of an object without calling the constructor. However, in this section, the idea of constructor overloading is discussed, which relies heavily on the material in Section 3. The StringTokenizer class, which was introduced previously, is discussed in depth at the very end of this chapter. While this section is not optional and is used in examples and problems in the book, it may be considered optional to some instructors and could be omitted without hurting the student’s understanding of writing their own classes.

Key Points A Class is a Type. The notion of the difference between a class and an instance comes up again in this chapter. Also, students need to be made aware that you can create a variable whose value will be an object. The type of the variable will be the class. The new Operator. The new operator is what is used to actually create an instance. You would use the new operator when you are assigning a value to a variable whose type is a class. Class Definition. A class’ definition begins with the keywords public class followed by the name of the class. The definition of the class is enclosed between {} and usually the instance variables for a class are listed before the methods. This is by convention and not compiler enforced. Normally, all the instance variables are placed at the top of the file. File Names and Locations. In java, each file should contain one class and the name of the class and the file will be the same. For now, all files for the same project should be in the same directory. There are other ways to organize files, namely into packages, but the text has not introduced this idea yet. return Statements. When writing a method that has a return type that is other than void, a return statement needs to be in the method. If omitted, this will cause a compiler error. A void method does not need a return statement. Method Definitions. The first part of a method definition is the method signature, which consists of its visibility, which is usually public, its return type, the method name and the parenthesized list of parameters. Methods are first introduced where they do not take any parameters. The method body is enclosed in {} and if the return type of a method is other than void, a return statement must be included in the list of statements for the method. Local Variables. You can have instance variables that are accessible to the entire class. You can also create variables inside a method that are only accessible within that method. With these variables, you do not need to give them a visibility, just a type and a name. You can then use these variables in any computation within the method. Global Variables. This type of variable in not available in Java. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

Blocks. The notion of blocks of code encompasses the idea that code enclosed in {} is considered a block. This can be the {} around a loop body or within an if-else statement. However, for purposes of local variables, they are only accessible from within the block, but their names cannot be repeated within the method. Parameters of a Primitive Type. Parameters into a method can be of a primitive type. When primitive values are passed into a method, the value of the parameter is initialized to the value that is passed in from the method call. This method is call-by-value parameter passing and unlike other languages, is the only type of parameter passing that Java supports for primitive types. You can also pass in parameters whose type is a class. These parameters are handled by Java differently and will be discussed in the next chapter. Main is a void Method. If you look at the method signature of the main method, you will see that its return type is void. It also takes a parameter named args. We will discuss static and the type of thing that the parameter is (an array) in later chapters. The this Parameter. There is a keyword in Java whose meaning is to refer to the class itself. The keyword this is used whenever you want to refer to the class. You can use the keyword this as a calling object for methods within the same class. We will see using this as a parameter when we talk about passing objects as parameters. The Methods equals and toString. It is good practice when writing Java classes that you write an equals and a toString method. The equals method can help determine whether two objects are equal and returns a Boolean value. The toString method returns a String representation of an object. The Fundamental Rule for Testing Methods. When testing a new method, it should be maintained that all of the other methods being called in the testing program have already been tested and debugged. Encapsulation. The idea of encapsulation is that all of the data and the actions that can be performed are combined in one place (class). If a class is well designed, the user of the class only needs to be told what the class is capable of, not the specific details of how it is implemented. API. The Application Programmer Interface is used to tell users of the class what the class can do. There is an online Java API that is available for all of the classes inside Java. ADT. Abstract Data Types are written using good information hiding techniques and we discuss some ADT’s later in the text. Signature. The signature of the method consists of its visibility, return type, method name, and parameter list. This term can also be introduced right when methods are first introduced in the text.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

Overloading. Java supports method overloading. Two methods can have the same name if they differ in number and or type of parameters. You Cannot Overload Operators in Java. Unlike other languages, Java does not provide the ability to overload operators. Constructor. The constructor is a special method that is in charge of setting up the initial state of an object. It is executed when an object is created using the keyword new. Is a Constructor Really a Method? There is debate about this question because a constructor does not follow the same signature as other methods (no return type) and it is not called in the same manner (it uses the keyword new). Therefore, the text will be explicit about when we are referring to constructors and methods, or just methods and not constructors. Tips Any Method Can Be Used as a void Method. This tip points out the fact that if the return value from a method is not placed into a variable, the value is essentially lost. This could be a positive for a program in that we can ignore a value that is returned if we do not need it. However, this could also be a potential problem if students forget to assign a return value to a variable when they need to keep track of the value. Declaring Variables in a for Statement. In a for statement, the first part is an initialization, commonly seen as int n = value. However, when the variable n is declared in the for loop, it is not accessible outside of the loop. To avoid this problem, we must declare the variable outside of the loop and only initialize it in the loop. This feature of when variables can be accessed can be both a pitfall and a help depending on when the variable needs to be accessed. Testing Methods. Each method of a class should be tested. One of the easiest and best ways to do this is to create a driver class that creates an instance of the object and tests each method in turn. Care needs to be taken when testing methods that call other methods so that it is assured that all methods are working properly. A Class has Access to Private Members of All Objects of the Class. When an entity is declared private the only elements that have access to it are other entities inside that same class. This is the most restrictive visibility. Mutator Methods Can Return a Boolean Value. An alternative implementation for a mutator method is to have the method return a boolean value that indicates whether the changes requested by the caller were successful. Using this method, the mutator is not responsible for ending the program or issuing error messages. You Can Invoke Another Method in a Constructor. You can make a call to another method from the constructor by simply using the same technique as we have used to call methods previously. Include a No-Argument Constructor. If you do not provide a constructor for a class, Java provides one for you that takes no arguments. It is a good idea to include a no-arg constructor Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

that does something meaningful so that the default constructor that does nothing will not be called. You lose the default no-arg constructor as soon as there is at least one constructor defined in the class, so having another that takes no parameters is a good programming practice.

Pitfalls Use of the Terms “Parameter” and “Argument”. The use of these two terms varies from author to author and it should be well known which context the words are used in. For this text, parameter is used to describe the formal parameter or the name of the parameter in the method signature. The word argument is used to describe the actual parameter or the actual value that is passed into the method when it is called. Overloading and Automatic Type Conversion. When a method is called in Java, it looks to match the method signature. If it fails to match the signature exactly, Java will try to do a conversion to match. For example, it may convert an int into a double to match for a signature. This has the potential to cause problems within a program. You Cannot Overload Based on the Type Returned. A method can not be overloaded based on the return type of the method. Overloading is only concerned with the parameters for a method, not the return types.

Examples Yet Another Date Class. The code for the Date class has been going under revisions throughout the chapter and is given once again in Display 4.7 and incorporates much of what this chapter has been discussing. Methods, parameters, instance variables, the equals and toString methods are all included so that students can have an example of an entire class. The Final Date Class. The final version of the date class is given in Display 4.11 and will be revisited again in Chapter 5. A Pet Record Class. The final programming example for this section is a class that represents a pet record that has information about a particular pet. This example has multiple constructors as well as accessor and mutator methods. There is also an example of how to use the class in conjunction with the StringTokenizer section in this chapter.

Programming Projects Answers 1. /** * * PrintCodeWord.java * * The program generates a series that has code words that * match the following guidelines. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

* 1. Each code word comprises of a letter followed by a * digit, for example, A0, B1, C2, D3, and so on. * 2. The first code word's letter and digit values are * passed in the constructor of the class. * 3. The letters and digits are circularly used in the series. * For example, after Z, the next code word starts with A. * Similarly after 9, the next code word ends with 0. * 4. The series should contain just 26 code words and only * one print statement should be used. * * * Created: Jan 31, 2016 * * @author * @version 1 */ public class PrintCodeWord { char letter; int digit; /** * Constructor that sets initial letter and initial digit * @param initialLetter - Initial letter (A-Z) * @param intialDigit - Initial Digit (0-9) */ public PrintCodeWord(char initialLetter, int intialDigit) { letter = initialLetter; digit = intialDigit; } //Print the codes public void printCode() { System.out.println("The generated series of codes are" + " as follows: "); for (int i = 1; i <= 26; i++) { System.out.print(letter + digit + " , "); if (letter == 'Z') letter = 'A'; else letter++; if (digit == 9) digit = 0; else digit++; } } public static void main(String[] args) { char initialLetter = 'D'; int initialDigit = 5; PrintCodeWord pcw = new PrintCodeWord(initialLetter, initialDigit); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

}

pcw.printCode();

}

2. /** * * CalAge.java * * The program calculates the age of a person from his or her date of * birth and the current date. Both the date of birth and current * date values are read from the user input console. * * * Created: Jan 31, 2016 * * @author * @version 1 */ import java.util.Scanner; /** * Class named Date to store the date fields, day, month and year. */ class Date { private int month; private int day; private int year; // ====================== // Various mutator methods // ====================== public void setMonth(int monthNumber) { //Check if month value falls in the range from 1 to 12 if ((monthNumber <= 0) || (monthNumber > 12)) { System.out.println("Enter a valid month"); System.exit(0); } else this.month = monthNumber; } //mutator for date public void setDay(int day) { //Check if day value falls in the range from 1 to 31 if ((day <= 0) || (day > 31)) { System.out.println("Enter a valid day"); System.exit(0); } else this.day = day; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

} //mutator for year public void setYear(int year) { //Check if year value is of 4 digit long if ((year < 1000) || (year > 9999)) { System.out.println("Enter a valid year"); System.exit(0); } else this.year = year; } //method that reads user input date public void readInput() { Scanner keyboard = new Scanner(System.in); System.out.print("Input day : "); setDay(keyboard.nextInt()); System.out.print("Input month : "); setMonth(keyboard.nextInt()); System.out.print("Input year : "); setYear(keyboard.nextInt()); } public void writeOutput() { System.out.println(month + "/" + day + "/" + year); } //calculate age as on current date double getAge(Date currentDate) { double age; int years, months; //Get difference between years years = currentDate.year - this.year; //Get difference between months months = currentDate.month - this.month; /* * if month difference is in negative then reduce years by one * and calculate the number of months. */ if (months < 0) { years--; months = 12 - this.month + currentDate.month; if (currentDate.day < this.day) months--; } else if (months == 0 && currentDate.day < this.day) { years--; months = 11; } //Create new Age object age = years + (double) months / 100; return (age); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

} public class CalAge { public static void main(String[] args) { Date dateOfBirth = new Date(); Date currentDate = new Date(); System.out.println("Input your date of birth :"); dateOfBirth.readInput(); System.out.println("Input today's date :"); currentDate.readInput(); System.out.println("Your age is " + dateOfBirth.getAge(currentDate)); } }

3. /** * * FuelMonitor.java * * This program creates a class Vehicle with fuel tank * capacity (in litres) and the initial efficiency (in kilometers per litre fuel) values, and * then check the amount of fuel left in a vehicle after traveling * a certain distance. * * Created: Jan 31, 2016 * * @author * @version 1 */ public class FuelMonitor { public static void main(String[] args) { //TestCar Vehicle c = new Vehicle(60, 10); //returns fuelInTank from initial constructor System.out.println("Fuel In Tank = " + c.getPetrol()); //returns tankSize from initial constructor System.out.println("Total Capacity of Tank = " + c.getCapacity()); //returns efficiency from initial constructor System.out.println("Fuel Efficiency = " + c.getEfficiency()); c.addPetrol(20); System.out.println("Fuel In Tank = " + c.getPetrol()+" litres"); c.addPetrol(20); System.out.println("Fuel In Tank = " + c.getPetrol()+" litres"); c.driveTo(100); System.out.println("Fuel In Tank = " + c.getPetrol()+" litres");

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

}

}

/** * Class Vehicle with properties tank capacity, efficiency and remaining fuel in tank * */ class Vehicle { //capacity of tank private double tankSize; //litres per 100km private double efficiency; //litres in tank private double fuelInTank; /** * Constructor to initialize tank capacity and efficiency * @param initTankSize_ Tank capacity in litres * @param initEfficiency_ Vehicle efficency in kilometers per litre fuel */ Vehicle(int initTankSize_, double initEfficiency_) { tankSize = initTankSize_; efficiency = initEfficiency_; fuelInTank = 0; } // ====================== // Various accessor methods // ====================== public double getPetrol() { return fuelInTank; } public double getEfficiency() { return efficiency; } public double getCapacity() { return tankSize; } public void addPetrol(double litres) { System.out.println("Adding "+litres+" litres fuel to the tank."); fuelInTank = fuelInTank + litres; if (fuelInTank > tankSize) { fuelInTank = tankSize; } } public void driveTo(double km) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

System.out.println("Driven car for "+km+" kilometeres"); double distance = (fuelInTank * efficiency); if (distance > km) { distance = km; } fuelInTank = (fuelInTank - (distance / efficiency)); }

}

4. /** * * Journal.java * * The class Journal used to store an entry for a research paper that * will be published. Each research paper consists a title, author’s name * and date of submission values which are stored using instance * variables. * * Created: Jan 31, 2016 * * @author * @version 1 */ import java.util.StringTokenizer; public class Journal { private String authorName; private String title; private Date dateOfSubmission; // /** * Constructs Journal class with author name, paper title and submission date * @param name Author name * @param title Title of the paper * @param submissionDate Submission date */ public Journal(String name, String title, Date submissionDate) { this.authorName = name; this.title = title; this.dateOfSubmission = submissionDate; } //Displays the title, author name and date of submission public void displayDetails() { System.out.println("Author Name = " + authorName); System.out.println("Title = " + title); System.out.print("Date of submission = "); dateOfSubmission.writeOutput(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

} /* * Returns paper title with each word's first character in upper * case and replaces spaces with "-". */ public String getSubmissionDetails() { StringTokenizer tokenizer = new StringTokenizer(title); String updatedTitle = null, temp; while (tokenizer.hasMoreTokens()) { temp = tokenizer.nextToken(); temp = temp.substring(0, 1).toUpperCase() + temp.substring(1) + "-"; if (updatedTitle == null) updatedTitle = temp; else updatedTitle += temp; } //remove last space; updatedTitle = updatedTitle.substring(0, updatedTitle.length() - 1); return (updatedTitle); }

}

public static void main(String[] args) { Date dateOfSubmission = new Date(); dateOfSubmission.setDay(22); dateOfSubmission.setMonth(4); dateOfSubmission.setYear(2014); Journal j1 = new Journal("Ajita Verma", "Big data: A " + "security compliance model",dateOfSubmission); j1.displayDetails(); System.out.println( "\nThe title of the paper with first " + "letter of the each word capitalize is :"); System.out.println(j1.getSubmissionDetails()); }

5. /** * WordCount.java * * This program creates a class called WordCount which is used as a * counter to count the number of words in a sentence. The class * provides methods to increase/decrease/reset the counter value. * * Created: Jan 31, 2016 * * @author * @version 1 */ import java.util.StringTokenizer; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

public class WordCount { private int count; /** * Default constructor that sets the count value to zero */ public WordCount() { count = 0; } //reset the counter to zero public void restCounter() { count = 0; } //Increases the count value by 1 void increaseCounter() { count++; } /* * Decreases the count value by 1 and ensures that the count * remains non-negative */ void decreaseCounter() { count--; if (count == -1) count = 0; } public int getCount() { return (count); } public String toString() { return ("Count =" + count); } /* * Compares the count values of current WordCount object and the * WordCount object passed as an argument */ public boolean equals(WordCount object) { if (count == object.count) return true; else return false; } public static void main(String[] args) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

String sentense = "A phrase is a group or words that expresses" + " a concept and is used as a unit within a sentence"; String token; StringTokenizer tokens = new StringTokenizer(sentence); WordCount wcount1 = new WordCount(); wcount1.restCounter(); StringTokenizer tokenizer = new StringTokenizer(sentence); while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); if (token.charAt(0) == 'A' || token.charAt(0) == 'a') wcount1.increaseCounter(); } System.out.println("\nThe given Sentence is = " + sentence); System.out.println("\nThe Word Count of words starting with" + " a or A is =" + wcount1.getCount()); } }

6. /** * StudentRecord.java * * * Created: Fri Dec 12 15:56:54 2003 * * @author Adrienne Decker * @version */ public class StudentRecord { private int _quiz1; private int _quiz2; private int _quiz3; private int _midterm; private int _final; private double _numericScore; private char _letterGrade; private final int A_GRADE = 90; private final int B_GRADE = 80; private final int C_GRADE = 70; private final int D_GRADE = 60; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

public StudentRecord (int quiz1, int quiz2, int quiz3, int midterm, int finalExam) { _quiz1 = quiz1; _quiz2 = quiz2; _quiz3 = quiz3; _midterm = midterm; _final = finalExam; } public int getQuiz1() { return _quiz1; } public int getQuiz2() { return _quiz2; } public int getQuiz3() { return _quiz3; } public int getMidterm() { return _midterm; } public int getFinal() { return _final; } public void setQuiz1(int quiz1) { _quiz1 = quiz1; } public void setQuiz2(int quiz2) { _quiz2 = quiz2; } public void setQuiz3(int quiz3) { _quiz3 = quiz3; } public void setMidterm(int midterm) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

_midterm = midterm; } public void setFinal(int finalExam) { _final = finalExam; } public void computeNumericScore() { int quiz1Percent = (_quiz1/10) * 100; int quiz2Percent = (_quiz2/10) * 100; int quiz3Percent = (_quiz3/10) * 100; double quizAverage = (quiz1Percent + quiz2Percent + quiz3Percent)/3.0; double quizPart = quizAverage * 0.25; double midtermPart = _midterm * 0.35; double finalPart = _final * 0.40; _numericScore = quizPart + midtermPart + finalPart; } public void computeLetterGrade() { this.computeNumericScore(); if ( _numericScore >= A_GRADE ) { _letterGrade = 'A'; } // end of if () else if ( _numericScore >= B_GRADE ) { _letterGrade = 'B'; } // end of else if () else if ( _numericScore >= C_GRADE ) { _letterGrade = 'C'; } // end of else if () else if ( _numericScore >= D_GRADE ) { _letterGrade = 'D'; } // end of else if ()

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

else { _letterGrade = 'F'; } // end of else } public boolean equals(StudentRecord other) { return (_quiz1 == other._quiz1) && (_quiz2 == other._quiz2) && (_quiz3 == other._quiz3) && (_midterm == other._midterm) && (_final == other._final); } public String toString() { this.computeNumericScore(); this.computeLetterGrade(); return "Quiz 1: " + _quiz1 + ", Quiz 2: " + _quiz2 + ", Quiz3: " + _quiz3 + ", Midterm: " + _midterm + ", Final: " + _final + ". Overall numeric grade: " + _numericScore + ", Letter Grade: " + _letterGrade; } }// StudentRecord

/** * Question6.java * * Created: Fri Dec 12 15:50:00 2003 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ import java.util.Scanner; public class Question6 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("Enter the student's score on the first quiz: "); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

int quiz1 = keyboard.nextInt(); System.out.println("Enter the student's score on the second quiz: "); int quiz2 = keyboard.nextInt(); System.out.println("Enter the student's score on the third quiz: "); int quiz3 = keyboard.nextInt(); System.out.println("Enter the student's score on the midterm: "); int midterm = keyboard.nextInt(); System.out.println("Enter the student's score on the final: " ); int finalExam = keyboard.nextInt(); StudentRecord student = new StudentRecord(quiz1, quiz2, quiz3, midterm, finalExam); System.out.println("Student record: " + student); } } // Question6 7. /** * Temperature.java * * * Created: Fri Dec 12 16:17:11 2003 * * @author Adrienne Decker * @version */ public class Temperature { private double _value; private char _scale; public Temperature () { _value = 0.0; _scale = 'C'; } public Temperature(double value) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

_value = value; _scale = 'C'; } public Temperature(char scale) { if ( scale != 'C' && scale != 'F') { _scale = 'C'; } // end of if () else { _scale = scale; } // end of else _value = 0.0; } public Temperature(double value, char scale) { if ( scale != 'C' && scale != 'F' ) { _scale = 'C'; } // end of if () else { _scale = scale; } // end of else _value = value; } public double getTemperatureFahrenheit() { if ( _scale == 'F' ) { return _value; } // end of if () else { return (9 * _value / 5) + 32; } // end of else } public double getTemperatureCelsius() Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

{ if ( _scale == 'C' ) { return _value; } // end of if () else { return 5 * (_value - 32)/9; } // end of else } public void setValue(double value) { _value = value; } public void setScale(char scale) { if ( scale != 'C' && scale != 'F' ) { _scale = 'C'; } // end of if () else { _scale = scale; } // end of else } public void setValueAndScale(double value, char scale) { _value = value; _scale = scale; } public boolean equals (Temperature other) { if ( _scale == other._scale ) { return _value == other._value; } // end of if () else { return this.getTemperatureCelsius() == other.getTemperatureCelsius(); } // end of else }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

public boolean isGreaterThan(Temperature other) { if ( _scale == other._scale ) { return _value > other._value; } // end of if () else { return this.getTemperatureCelsius() > other.getTemperatureCelsius(); } // end of else } public boolean isLessThan(Temperature other) { if ( _scale == other._scale ) { return _value < other._value; } // end of if () else { return this.getTemperatureCelsius() < other.getTemperatureCelsius(); } // end of else } public String toString() { return "" + _value + " degrees " + _scale; } }// Temperature

/** * Question7.java * * Created: Fri Dec 12 16:16:13 2003 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ public class Question7 {

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

public static void main(String[] args) { Temperature one = new Temperature(); System.out.println("Temp one: " + one); Temperature two = new Temperature(56.8); System.out.println("Temp two: " + two); Temperature three = new Temperature('F'); System.out.println("Temp three: " + three); Temperature four = new Temperature(33.5, 'F'); System.out.println("Temp four: " + four); System.out.println("Temp one as Fahrenheit: " + one.getTemperatureFahrenheit()); System.out.println("Temp three as Celsius: " + three.getTemperatureCelsius()); System.out.println("Changing temp two's degrees."); two.setValue(34.6); System.out.println(two); System.out.println("Changing temp four's scale."); four.setScale('C'); System.out.println(four); System.out.println("Changing scale and value of temp three."); three.setValueAndScale(100, 'C'); System.out.println(three); System.out.println("Are temp two and three equal: " + two.equals(three)); System.out.println("Creating a duplicate of temp four."); Temperature fourDup = new Temperature(); fourDup.setValueAndScale(four.getTemperatureFahrenheit(), 'F'); System.out.println(fourDup); System.out.println("Temp four is equal to fourDup: " + four.equals(fourDup));

System.out.println("Temp two greater than temp three: " + two.isGreaterThan(three)); System.out.println("Temp three greater than temp two: " + three.isGreaterThan(two));

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

System.out.println("Temp two less than temp three: " + two.isLessThan(three)); System.out.println("Temp three less than temp two: " + three.isLessThan(two)); } } // Question7 8. /** * Question8Date.java * * Created: Sat Dec 13 11:56:49 2003 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ import java.util.Scanner; public class Question8Date { private int _month; private int _day; private int _year; public Question8Date () { _month = 1; _day = 1; _year = 1000; } public Question8Date(int monthInt, int day, int year) { setDate(monthInt, day, year); } public Question8Date(String monthString, int day, int year) { setDate(monthString, day, year); } public Question8Date(int year) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

{ setDate(1, 1, year); } public Question8Date(Question8Date aDate) { if ( aDate == null ) { System.out.println("Fatal error."); System.exit(0); } // end of if () _month = aDate._month; _day = aDate._day; _year = aDate._year; } public void setDate(int monthInt, int day, int year) { if ( dateOK(monthInt, day, year) ) { _month = monthInt; _day = day; _year = year; } // end of if () else { System.out.println("Fatal Error"); System.exit(0); } // end of else } public void setDate(String monthString, int day, int year) { if ( dateOK(monthString, day, year) ) { _month = this.monthInt(monthString); _day = day; _year = year; } // end of if () else { System.out.println("Fatal error."); System.exit(0); } // end of else } public void setDate(int year) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

setDate(1, 1, year); } public void setYear(int year) { if ( (year < 1000) || (year > 9999) ) { System.out.println("Fatal Error."); System.exit(0); } // end of if () else { _year = year; } // end of else } public void setMonth(int monthNumber) { if ( (monthNumber <= 0) || (monthNumber > 12) ) { System.out.println("Fatal Error."); System.exit(0); } // end of if () else { _month = monthNumber; } // end of else } public void setDay(int day) { if ( (day <= 0) || (day > 31) ) { System.out.println("Fatal Error."); System.exit(0); } // end of if () else { _day = day; } // end of else } public int getMonth() { return _month; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

public int getDay() { return _day; } public int getYear() { return _year; } public String toString() { String monthString = this.monthString(_month); return (monthString + " " + _day + ", " + _year); } public boolean equals(Question8Date otherDate) { return ( (_month == otherDate._month) && (_day == otherDate._day) && (_year == otherDate._year) ); } public boolean precedes(Question8Date otherDate) { return ( (_year < otherDate._year) || (_year == otherDate._year && getMonth() < otherDate.getMonth()) || (_year == otherDate._year && _month == otherDate._month && _day < otherDate._day) ); } public void readInput () { boolean tryAgain = true; Scanner keyboard = new Scanner(System.in); while ( tryAgain ) { System.out.println("Enter month, day, and year on three lines."); System.out.println( "Enter month, day, and year as three integers."); int monthInput = keyboard.nextInt(); int dayInput = keyboard.nextInt(); int yearInput = keyboard.nextInt();

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

if ( dateOK(monthInput, dayInput, yearInput) ) { setDate(monthInput, dayInput, yearInput); tryAgain = false; } // end of if () else { System.out.println("Illegal date. Reenter input."); } // end of else } // end of while () } private boolean dateOK(int monthInt, int dayInt, int yearInt) { return ( (monthInt >= 1) && (monthInt <= 12) && (dayInt >= 1) && (dayInt <= 31) && (yearInt >= 1000) && (yearInt <= 9999) ); } private boolean dateOK(String monthString, int dayInt, int yearInt) { return ( monthOK(monthString) && (dayInt >= 1) && (dayInt <= 31) && (yearInt >= 1000) && (yearInt <= 9999) ); } private boolean monthOK(String month) { return (month.equals("Jan") || month.equals("Feb") || month.equals("Mar") || month.equals("Apr") || month.equals("May") || month.equals("Jun") || month.equals("Jul") || month.equals("Aug") || month.equals("Sep") || month.equals("Oct") || month.equals("Nov") || month.equals("Dec") ); } private String monthString(int monthNumber) { switch ( monthNumber ) { case 1: return "Jan"; case 2: return "Feb"; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

case 3: return "Mar"; case 4: return "Apr"; case 5: return "May"; case 6: return "Jun"; case 7: return "Jul"; case 8: return "Aug"; case 9: return "Sep"; case 10: return "Oct"; case 11: return "Nov"; case 12: return "Dec"; default: System.out.println("Fatal Error."); System.exit(0); return "Error"; } // end of switch () } private int monthInt(String month) { if ( month.equals("Jan") ) { return 1; } // end of if () else if ( month.equals("Feb") ) { return 2; } // end of if () else if ( month.equals("Mar") ) { return 3; } // end of if () else if ( month.equals("Apr") ) { return 4; } // end of if () else if ( month.equals("May") ) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

{ return 5; } // end of if () else if ( month.equals("Jun") ) { return 6; } // end of if () else if ( month.equals("Jul") ) { return 7; } // end of if () else if ( month.equals("Aug") ) { return 8; } // end of if () else if ( month.equals("Sep") ) { return 9; } // end of if () else if ( month.equals("Oct") ) { return 10; } // end of if () else if ( month.equals("Nov") ) { return 11; } // end of if () else if ( month.equals("Dec") ) { return 12; } // end of if () else { System.out.println("Fatal Error."); System.exit(0); return 0; } // end of else } }// Question8Date /** * Question8.java * * Created: Sat Dec 13 11:56:04 2003 * Modified: Sat Mar 05 2005, Kenrick Mock Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

* * @author Adrienne Decker * @version 2 */ public class Question8 { public static void main(String[] args) { //Testing Display 4.12 Question8Date date1 = new Question8Date("Dec", 16, 1770), date2 = new Question8Date(1, 27, 1756), date3 = new Question8Date(1882), date4 = new Question8Date(); System.out.println("Whose birthday is " + date1 + "?"); System.out.println("Whose birthday is " + date2 + "?"); System.out.println("Whose birthday is " + date3 + "?"); System.out.println("The default date is " + date4 + "."); //Checking other methods that were changed date1.setDate(3, 31, 2001); System.out.println("New date1 is: " + date1); date2.setDate("Dec", 23, 1956); System.out.println("New date2 is: " + date2); date3.setMonth(10); System.out.println("New month for date3: " + date3); System.out.println("The default month is : " + date4.getMonth()); Question8Date copy = new Question8Date(date2); System.out.println("date2 equal to its copy: "+ date2.equals(copy)); System.out.println("date2 equal to date3: " + date2.equals(date3)); System.out.println("date2 is before date3: " + date2.precedes(date3)); System.out.println("date3 is before date2: " + date3.precedes(date2)); } } // Question8 9. /** Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

* SpeciesRecord.java * * * Created: Thu Dec 11 21:17:31 2003 * * @author Adrienne Decker * @version */ import java.text.DecimalFormat; public class SpeciesRecord { private String _name; private int _population; private double _growthRate; public SpeciesRecord () { _name = ""; _population = 0; _growthRate = 0.0; } public SpeciesRecord(String name) { _name = name; _population = 0; _growthRate = 0.0; } public SpeciesRecord(String name, int population) { _name = name; _population = population; _growthRate = 0.0; } public SpeciesRecord(String name, double growthRate) { _name = name; _population = 0; _growthRate = growthRate; } public SpeciesRecord(String name, int population, double growthRate) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

{ _name = name; _population = population; _growthRate = growthRate; } public void setName(String name) { _name = name; } public void setPopulation(int population) { _population = population; } public void setGrowthRate(double growthRate) { _growthRate = growthRate; } public String getName() { return _name; } public int getPopulation() { return _population; } public double getGrowthRate() { return _growthRate; } public boolean endangered() { if ( _growthRate < 0) { return true; } // end of if () return false; } public boolean equals(SpeciesRecord otherRecord) { return _name.equals(otherRecord._name) && _population == otherRecord._population && _growthRate == otherRecord._growthRate; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

} public String toString() { DecimalFormat percent = new DecimalFormat("0.00%"); return "Name: " + _name + ", current population: " + _population + ", growth rate: " + percent.format(_growthRate); } }// SpeciesRecord

/** * Question9.java * * Created: Thu Dec 11 21:16:51 2003 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ import java.text.DecimalFormat; public class Question9 { public static void main(String[] args) { SpeciesRecord sr = new SpeciesRecord(); System.out.println("Record is: " + sr); System.out.println("Setting name."); sr.setName("Unicorn"); System.out.println("Record is now: " + sr); SpeciesRecord sr2 = new SpeciesRecord("Rabbit"); System.out.println("Record is: " + sr2); SpeciesRecord sr3 = new SpeciesRecord("Horse", 3000); System.out.println("Record is: " + sr3); System.out.println("Setting growth rate."); sr3.setGrowthRate(0.567); System.out.println("Record is now: " + sr3); SpeciesRecord sr4 = new SpeciesRecord("Dodo", -0.335); System.out.println("Record is: " + sr4); System.out.println("Setting population."); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

sr4.setPopulation(2); System.out.println("Record is now: " + sr4); SpeciesRecord sr5 = new SpeciesRecord("German Shepherd", 550, 0.45); System.out.println("Record is: " + sr5); System.out.println("Getting population of rabbits: " + sr2.getPopulation()); DecimalFormat percent = new DecimalFormat("0.00%"); System.out.println("Getting growth rate of German Shepherds: " + percent.format(sr5.getGrowthRate())); System.out.println("Getting name from first record: " + sr.getName()); System.out.println("The Dodo is endangered: " + sr4.endangered()); System.out.println("The rabbit is endangered: " + sr2.endangered()); System.out.println("Horses and Unicorns are the same: " + sr.equals(sr3)); System.out.println("Making an identical object of German Shepherds."); SpeciesRecord duplicate = new SpeciesRecord(); duplicate.setName("German Shepherd"); duplicate.setPopulation(sr5.getPopulation()); duplicate.setGrowthRate(sr5.getGrowthRate()); System.out.println("Duplicate record is: " + duplicate); System.out.println("Duplicate is same as original German Shepherd: " + duplicate.equals(sr5)); } } // Question9

10. /** * Question 10 * * Modification of Display 4.15 to include a type variable * and acepromazine and carprofen methods. * */ /** Class for basic pet records: name, age, and weight. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

*/ public class Pet { private String name; private int age;//in years private double weight;//in pounds private String type; // *** cat or dog public String toString( ) { return ("Type: " + type + " Name: " + name + " Age: " + age + " years" + "\nWeight: " + weight + " pounds"); } public Pet(String initialName, int initialAge, double initialWeight, String initialType) { name = initialName; type = initialType; if ((initialAge < 0) || (initialWeight < 0)) { System.out.println("Error: Negative age or weight."); System.exit(0); } else { age = initialAge; weight = initialWeight; } } public void set(String newName, int newAge, double newWeight, String newType) { name = newName; type = newType; if ((newAge < 0) || (newWeight < 0)) { System.out.println("Error: Negative age or weight."); System.exit(0); } else { age = newAge; weight = newWeight; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

} } public Pet(String initialName) { name = initialName; age = 0; weight = 0; type = "No type yet"; } public void setName(String newName) { name = newName; } public Pet(int initialAge) { name = "No name yet."; type = "No type yet"; weight = 0; if (initialAge < 0) { System.out.println("Error: Negative age."); System.exit(0); } else age = initialAge; } public void setAge(int newAge) { if (newAge < 0) { System.out.println("Error: Negative age."); System.exit(0); } else age = newAge; } public Pet(double initialWeight) { name = "No name yet"; type = "No type yet"; age = 0; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

if (initialWeight < 0) { System.out.println("Error: Negative weight."); System.exit(0); } else weight = initialWeight; } public void setWeight(double newWeight) { if (newWeight < 0) { System.out.println("Error: Negative weight."); System.exit(0); } else weight = newWeight; } public Pet( ) { name = "No name yet."; type = "No type yet"; age = 0; weight = 0; } public String getName( ) { return name; } public int getAge( ) { return age; } public double getWeight( ) { return weight; } // Returns dosage in mL of acepromazine for // a dog or cat, 0 if unknown. public double acepromazine() Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

{ double dose = 0; if (type.equals("cat")) { dose = (weight / 2.2) * (0.002 / 10); } else if (type.equals("dog")) { dose = (weight / 2.2) * (0.03 / 10); } return dose; } // Returns dosage in mL of carprofen for // a dog or cat, 0 if unknown. public double carprofen() { double dose = 0; if (type.equals("cat")) { dose = (weight / 2.2) * (0.025 / 10); } else if (type.equals("dog")) { dose = (weight / 2.2) * (0.5 / 12); } return dose; } }

public class PetDemo { public static void main(String[] args) { Pet usersPet = new Pet("Jane Doe"); System.out.println("My records on your pet are incomplete."); System.out.println("Here is what they currently say:"); System.out.println(usersPet); Scanner keyboard = new Scanner(System.in); System.out.println("Please enter the pet's name:"); String name = keyboard.nextLine( ); System.out.println("Please enter the pet's type (dog or cat):"); String type = keyboard.nextLine( ); System.out.println("Please enter the pet's age:"); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

int age = keyboard.nextInt( ); System.out.println("Please enter the pet's weight:"); double weight = keyboard.nextDouble( ); usersPet.set(name, age, weight, type); System.out.println("My records now say:"); System.out.println(usersPet); System.out.printf("Dose of carprofen: %.4f\n", usersPet.carprofen()); System.out.printf("Dose of acepromazine: %.4f\n", usersPet.acepromazine()); } } // Question 10

11. /** * Question 11 * * Pizza class that stores information about a single pizza. * * Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ public class Pizza { private String size; private int numCheeseToppings; private int numHamToppings; private int numPepperoniToppings; public Pizza() { size = "Large"; numCheeseToppings = 1; numHamToppings = 0; numPepperoniToppings = 0; } public Pizza(String pizzaSize, int cheese, int ham, int pepperoni) { size = pizzaSize; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

numCheeseToppings = cheese; numHamToppings = ham; numPepperoniToppings = pepperoni; } public void setPizzaInfo(String newSize, int cheese, int ham, int pepperoni) { size = newSize; numCheeseToppings = cheese; numHamToppings = ham; numPepperoniToppings = pepperoni; } public String getSize() { return size; } public int getNumCheeseToppings() { return numCheeseToppings; } public int getNumHamToppings() { return numHamToppings; } public int getNumPepperoniToppings() { return numPepperoniToppings; } public double calcCost() { double baseCost = 10; if (size.equals("Small")) { baseCost = 10; } else if (size.equals("Medium")) { baseCost = 12; } else if (size.equals("Large")) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

{ baseCost = 14; } else { System.out.println("Error, unknown size."); return 0; } return baseCost + (numHamToppings + numCheeseToppings + numPepperoniToppings)*2; } public String getDescription() { return "Size: " + size + ", Cheese Toppings: " + numCheeseToppings + " Pepperoni Toppings: " + numPepperoniToppings + " Ham Toppings: " + numHamToppings + ". Cost: " + calcCost(); } public static void main(String[] args) { // Create a few sample pizzas and output their prices Pizza supreme = new Pizza("Large",1,2,1); Pizza cheese = new Pizza("Medium",2,0,0); Pizza pepperoni = new Pizza("Small",0,0,2); System.out.println(supreme.getDescription()); System.out.println(cheese.getDescription()); System.out.println(pepperoni.getDescription()); } } // Question 11

12. /** * Question 12 * * The PizzaOrder class allows up to 3 pizzas to be * saved in an order. * * Created: Sat Mar 15 2009 * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

* @author Kenrick Mock * @version 1 */ public class PizzaOrder { private Pizza pizza1, pizza2, pizza3; private int numPizzas; public PizzaOrder() { numPizzas = 0; pizza1 = null; pizza2 = null; pizza3 = null; } public void setNumPizzas(int num) { numPizzas = num; } public void setPizza1(Pizza pizza) { pizza1 = pizza; } public void setPizza2(Pizza pizza) { pizza2 = pizza; } public void setPizza3(Pizza pizza) { pizza3 = pizza; } public double calcTotal() { double total = 0; if (numPizzas >= 1) total += pizza1.calcCost(); if (numPizzas >= 2) total += pizza2.calcCost(); if (numPizzas >= 3) total += pizza3.calcCost(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

return total; } // Sample main public static void main(String[] args) { Pizza pizza1 = new Pizza("Large",1,1,0); Pizza pizza2 = new Pizza("Medium",2,0,2); PizzaOrder order = new PizzaOrder(); order.setNumPizzas(2); // 2 pizzas in the order order.setPizza1(pizza1); // Set first pizza order.setPizza2(pizza2); // Set second pizza double total = order.calcTotal(); // Should be 18+20 = 38 System.out.println("The order total is " + total); } } // Question 12

// Question 13 File: produce.txt Broccoli Tomato Kiwi Kale Tomatillo /** * Question 13 * * Box of Produce class. Holds 3 bundles of fruit or vegetables. * * Created: Fri Apr 27 2012 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Random; public class BoxOfProduce { private String bundle1,bundle2,bundle3;

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

public BoxOfProduce() { bundle1 = ""; bundle2 = ""; bundle3 = ""; } public BoxOfProduce(String b1, String b2, String b3) { bundle1 = b1; bundle2 = b2; bundle3 = b3; } public void setBundle1(String b1) { bundle1 = b1; } public String getBundle1() { return bundle1; } public void setBundle2(String b2) { bundle2 = b2; } public String getBundle2() { return bundle2; } public void setBundle3(String b3) { bundle3 = b3; } public String getBundle3() { return bundle3; } public String toString() { return "The box contains: " + bundle1 + ", " + bundle2 + ", " + bundle3; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

public static void main(String[] args) { // Create a Box BoxOfProduce box = new BoxOfProduce(); // Pick three random numbers from 0 to 4 for the 5 possible food choices Random rnd = new Random(); int num1, num2, num3; num1 = rnd.nextInt(5); num2 = rnd.nextInt(5); num3 = rnd.nextInt(5); int lineRead = 0; Scanner fileIn = null; // Initializes fileIn to an empty object try { // Attempt to open the file fileIn = new Scanner( new FileInputStream("produce.txt")); } catch (FileNotFoundException e) { // If the file could not be found, this code is executed // and then the program exits System.out.println("File not found."); System.exit(0); } // Read from the file and if the line read in matches one of the // random numbers then set the corresponding bundle while (fileIn.hasNext()) { String food = fileIn.next(); if (lineRead == num1) box.setBundle1(food); if (lineRead == num2) box.setBundle2(food); if (lineRead == num3) box.setBundle3(food); lineRead++; } fileIn.close(); // Show the box contents to the user and allow substitutions Scanner kbd = new Scanner(System.in); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 4, Instructor’s Manual

String selection = ""; do { System.out.println(box.toString()); System.out.println("Enter '1' to change bundle 1."); System.out.println("Enter '2' to change bundle 2."); System.out.println("Enter '3' to change bundle 3."); System.out.println("Enter 'q' to quit."); selection = kbd.next(); kbd.nextLine(); if (selection.equals("1")) { System.out.println("Enter item to substitute."); String item = kbd.nextLine(); box.setBundle1(item); } else if (selection.equals("2")) { System.out.println("Enter item to substitute."); String item = kbd.nextLine(); box.setBundle2(item); } else if (selection.equals("3")) { System.out.println("Enter item to substitute."); String item = kbd.nextLine(); box.setBundle3(item); } } while (!selection.equals("q")); System.out.println("Final Contents:"); System.out.println(box.toString()); } } // Question 13 Question 14: No solution provided Question 15: No solution provided

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

Chapter 5

Defining Classes II Key Terms static method static variable default initialization Math methods floor and ceil Math constants wrapper class Integer class boxing unboxing other wrapper classes automatic boxing automatic unboxing largest and smallest value parseDouble parseInt Character Boolean secondary and main memory byte address memory location variables of a primitive type references assignment with variables of class type == with variables of a class type null anonymous object static import statement static import of constants copy constructor clone leaking accessor methods privacy leak leaking mutator methods clone immutable class mutable class package import statement Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

CLASSPATH variable default package current directory name clash fully qualified class name javadoc @ tag deprecated

Brief Outline 5.1 Static Methods and Static Variables Static Methods Static Variables The Math Class Wrapper Classes Automatic Boxing and Unboxing Static Methods in Wrapper Classes 5.2 References and Class Parameters Variables and Memory References Class Parameters The Constant null The new Operator and Anonymous Objects 5.3 Using a Misusing References Copy Constructors Mutable and Immutable Classes 5.4 Packages and javadoc Packages and import Statements The Package java.lang Package Names and Directories The Default Package Specifying a Class Path When You Compile Name Clashes Introduction to javadoc Commenting Classes for javadoc Running javadoc

Teaching Suggestions This chapter goes deeper into the discussion of classes. The first section of the chapter deals with static methods and variables. The distinction of a class type being different than a primitive type is given coverage throughout this chapter. First, there is a discussion of the wrapper classes for all of the primitive types. Then, the new Java 5 feature of automatic boxing and unboxing is discussed.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

The second and third sections deal with the notion that a class type is treated differently in the system than a primitive type. The way that references are used in Java is an important topic that needs to be discussed because it is different than how the primitives are treated. The second section discusses this issue as well as the == operator. The final section of this chapter introduces packages and JavaDoc. Packages provide a way to organize our classes and JavaDoc is a tool that can be used to help us document our code.

Key Points Static Methods. This type of method can be called without the creation of a calling object for it. The keyword static in the method definition shows that this method is static. You cannot call non-static methods from within a static method. Static Variables. A static variable is designated by the keyword static before the type in its declaration. These variables are available to the class as a whole. Variables that are declared as public and static are accessible even outside the class. These types of variables should only be created when defining program-wide constants. Wrapper Classes. For each of the primitives in Java, there is a corresponding Wrapper class that allows us to take a primitive value and treat it like it was an object. There are many methods defined in the wrapper classes that can help us do more interesting things with the primitive data. Bytes and Addresses. This section begins to delve into the topics of how the computer manages things in memory and how memory is classified. It introduces the terms bit and byte and memory addresses as locations where information is stored in memory. Why Eight Bits? Eight is a power of two and eight bits being in a byte has also to do with how character are encoded in the computer with the ASCII encoding scheme. Variables of Class Type Hold References. Unlike the primitives, when we create a variable for a class type, we are storing the information about where the actual object is located in memory, not the actual object. Reference Types. Refers to types whose variables contain references instead of actual values. Class types are reference types, while primitive types are not. Differences Between Primitive and Class-Type Parameters. When you pass in an object into a method, the values of that object can be changed. This is different from how primitive types behaved as parameters. Their values could not be changed directly by a method. null. null is a constant defined in the system. It represents an address that points to nothing. Therefore, we can use == and != to test if an object is null. Anonymous Objects. This occurs when an object is created and not assigned to a variable. This is a fairly common occurrence and will be used even more as the class progresses. For example, Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

in opening files, the parameter that is sent in to the FileReader constructor is an instance of an InputStreamReader that is created right in the method call. Class Invariants. This is a statement about a class that is true for each and every instance of it. Copy Constructor. A copy constructor is one that takes in a parameter whose type is the same as the class type and makes an independent copy of the parameter. Some instructors might want to introduce the method clone to do this operation. Never Return a Reference to a Mutable Private Object. This box relates to the pitfall discussed below. It is a good idea not to allow another object direct access to your private instance variables that are objects themselves. Import Statement. It is good practice when writing Java classes that you write an equals and a toString method. The equals method can help determine whether two objects are equal and returns a Boolean value. The toString method returns a String representation of an object. Package. Packages are an excellent way to keep pieces of code that are common to each other separate from other pieces of code. They allow us to better organize our code. The classes that are built into java are already in packages and we use the import statement to gain access to them. This was seen especially when we have been taking keyboard input from the user. Package Names and the Classpath Variable. The packages that you refer to in your program must be known to the compiler. The only way for the compiler to be made aware of these packages is to tell it using the CLASSPATH environment variable. If you are only using other classes that come with Java, this is not crucial. However, if students put their code in packages, the compiler will need to know where that code is located on the system. Each system has a different way to change this variable and some IDE’s build the changing of these environment variables in as a menu option. You should find out the easiest way for the students to do this on your system if you will be using packages.

Tips You Can Put a main in Any Class. There is no restriction on which class can have a main method. However, you should carefully determine whether or not a class needs a main method. If it is to be used as a program, it should have a main method, but if it is a class that will just be used as an object, it should probably not have a main method. If a class does have a main method, it must be remembered that main is a static method and only static methods can be called from within a static method. Deep Copy Versus Shallow Copy. This tip points out the difference between a deep copy and a shallow copy. The difference is that in a deep copy there are no references in common between the two objects. A more in depth explanation of this topic is usually mounted in a programminglanguages class, so it might not be appropriate or relevant for introductory students. However, the distinction of what is happening in these code examples is important to note.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

Assume Your Coworkers are Malicious. You should be extremely careful about your code and assume that eventually someone will intend to be malicious with your code.

Pitfalls Invoking a Nonstatic Method within a Static Method. You cannot call a non-static method from within a static method. This is true of static methods that a student writes, or even calling methods from main. Static methods can be called from within other static methods. A Wrapper Class Does not Have a No-Argument Constructor. This is a case where a noargument constructor does not make sense. The wrapper classes have mainly static methods that do not need an object of that type created for their use. It also usually wraps a value of a primitive type, so an empty value or default value for a wrapper class does not make sense. The compiler will notify you if you try to call the no-argument constructor for a wrapper class. Use of = and == with Variables of a Class Type. Obviously the = operator does not assign the value of an object to the variable, but rather the address of where the object is stored in memory. The == also behaves differently, as it looks for object address equality, not object value equality. Therefore, two objects that are not stored at the same location in memory are not considered equal under ==. Null Pointer Exception. This is probably one of the most common exceptions that students will run into when they are first using objects. If a reference to an object does not point to an actual instance of an object and you try to call a method on that object, the system will throw a NullPointerException indicating this fact. Null Can Be an Argument to a Method. We can use null as an argument to a method to stand in for an object. It is very important to note the change in the equals method. We should be checking in our equals methods if the object that is passed in as the parameter is null and return false if it is. Privacy Leaks. We do not necessarily want to return to a calling object a mutable object that is one of our instance variables. We should always return a copy so that the caller does not have direct access to our instance variables through our accessor methods. We should also do the same with our mutator methods that take in an object. However, some instructors might choose to overlook this point, or introduce the same thing using the clone method as stated previously. Subdirectories are not Automatically Imported. When you use import statements, the subpackages of a package are not automatically imported. Using a * at the end will import the classes in that package, but will not import the subpackage. You will need another explicit import statement for the subpackage. Not Including the Current Directory in your Classpath. If you will be setting the CLASSPATH variable in your environment, make sure to always include your current directory along with the other directories that you will be adding to your classpath.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

Examples A Person Class. A fairly large class that contains both primitive typed instance variables and class type instance variables. It is described fully in Display 5.11.

Programming Projects Answers 1. /** * BicycleShop.java * * The BicycleShop class can be used to track the sales of bicycles * happening in shops across the city. Each BicycleShop instance is * associated with a shop id and contains an instance variable to set * the number of bicycles sold by the shop. The class also provides a * static variable to track the sales across all the shops. * * Created: Jan 31, 2016 * * @author * @version 1 */ public class BicycleShop { private String shopID; private int saleForToday; private static int totalSale; /** * Constructor that sets the shop id and sales per day for a * bicycle shop. * * @param id * Shop ID to identify the shop * @param salePerDay * sales per day, a non negative number */ public BicycleShop(String id, int salePerDay) { shopID = id; saleForToday = salePerDay; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

//The method increases the sales counter by 1 public void sold() { saleForToday++; totalSale++; } //returns the total sales across all the shops public static int overallSale() { return (totalSale); } //prints the sales status of the shop public void trackSaleStatus() { System.out.println(shopID + " has sold " + saleForToday + " " + "Bicycles till now for Today"); } public static void main(String[] args) { BicycleShop shop1 = new BicycleShop("SP001", 0); BicycleShop shop2 = new BicycleShop("SP002", 0); BicycleShop shop3 = new BicycleShop("SP003", 0); shop1.sold(); shop1.sold(); shop1.sold(); shop2.sold(); shop2.sold(); shop3.sold(); shop1.trackSaleStatus(); shop2.trackSaleStatus(); shop3.trackSaleStatus(); System.out.println("The total sale by all the shops" + " till now is " + BicycleShop.overallSale()); } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

2. /** * Question2Fraction.java * * This program defines a class for fractions, which stores a numerator * and denominator. A member functions allows for retrieval of the * fraction as a double and another outputs the value in lowest * terms. * * The greatest common divisor is found to reduce the fraction. * In this case we use a brute-force method to find the gcd, but * a more efficient solution such as euclid's method could also be * used. * This extends an earlier exercise on Fractions by adding an * equals method to the fraction. * Created: Sat Mar 05 2005 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; public class Question2Fraction { private int numerator; private int denominator;

// Store numerator and denominator

/** * Default constructor; Initialize num=0, denominator=1 to avoid divide by zero */ public Question2Fraction() { numerator = 0; denominator = 1; } /** * Fraction constructor. * * @param num The initial numerator * @param denom The initial denominator */ public Question2Fraction(int num, int denom) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

numerator = num; denominator = denom; } /** * Finds greatest common divisor of numerator and denominator * by brute force (start at larger of two, work way down to 1) * * @return The greatest common denominator of the numerator and denominator */ private int gcd() { int g; // candidate for gcd, start at the smaller of the // numerator and denominator if (numerator > denominator) { g = denominator; } else { g = numerator; } // Work down to 1, testing to see if both numerator and denominator // can be divided by g. If so, return it. while (g>1) { if (((numerator % g)==0) && ((denominator % g)==0)) return g; g--; } return 1; } /** * Mutator to set the numerator. * * @param n The new value for the numerator. */ public void setNumerator(int n) { numerator = n; } /** Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

* Mutator to set the denominator. * * @param d The new value for the denominator */ public void setDenominator(int d) { denominator = d; } /** * Accessor to retrieve the fraction's value as a double. * * @return The fraction's value as a double. */ public double getDouble() { return (double) numerator / denominator; } /** * Output the fraction with no reduction. */ public void DisplayFraction() { System.out.println(numerator + "/" + denominator); } /** * Returns true if the two fractions are equal, false otherwise. * It computes the gcd for both fractions and determines if the * numerator and denominator are equivalent. */ public boolean equals(Question2Fraction otherFraction) { int gcdMe, gcdOther; gcdMe = gcd(); gcdOther = otherFraction.gcd(); return (((numerator/gcdMe) == (otherFraction.numerator/gcdOther)) && ((denominator/gcdMe) == (otherFraction.denominator/gcdOther))); } /** * Output the reduced fraction to the console. * Uses a private greatest-common-denominator method to Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

* reduce the fraction. */ public void outputReducedFraction() { int g; g = gcd(); System.out.println(numerator / g + " / " + denominator / g); return; } /** * This is the main method. It creates a target fraction of 8/24 and determines if * input fractions are equal or not, using an anonymous Fraction class. */ public static void main(String[] args) { Question2Fraction target = new Question2Fraction(8,24); int numerator, denominator; String s; Scanner scan = new Scanner(System.in); do { System.out.println("You are comparing to "); target.outputReducedFraction(); System.out.println(); System.out.println("Enter a numerator:"); numerator = scan.nextInt(); System.out.println("Enter a denominator:"); denominator = scan.nextInt(); if (target.equals(new Question2Fraction(numerator,denominator))) { System.out.println("They are the same."); } else { System.out.println("They are not the same."); } System.out.println(); scan.nextLine(); // Skip newline System.out.println("Enter 'Y' to go again, anything else to exit."); s = scan.nextLine(); } while (s.equals("Y")); } } // Question2Fraction Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

3. /** * Container.java * * Creates a class called container that has properties, maximum * capacity and current capacity and that performs the following * operations. * a. Return the current quantity of liquid at any given time in liters. * b. Return the quantity of liquid that can be filled in the current * container before it is full. * c. Fill the current container fully. * d. Make the container completely empty. * e. Transfer a certain amount of liquid from one container to another. * f. Display the current quantity in liters/milliliters/kiloliters. * * Created: Jan 31, 2016 * * @author * @version 1 */ public class Container { private double maximumCapacity; private double currentCapacity; /** * Constructor that sets the maximum capacity and current capacity * of the Container * * @param maxCapacity * - Maximum Capacity * @param currCapacity * - Current Capacity */ public Container(double maxCapacity, double currCapacity) { this.maximumCapacity = maxCapacity; this.currentCapacity = currCapacity; } //Calling this method would set the current capacity to the maximum capacity public void completelFilled() { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

currentCapacity = currentCapacity + (maximumCapacity - currentCapacity); System.out.println("Container is completely filled now"); } //calling this method would set the current capacity to zero public void fullyEmpty() { currentCapacity = 0; System.out.println("Container is completely Empty now"); } /* * transfers the contents of specified quantity of this container * to the second container that is passed as an argument */ public void transferInto(Container secondContainer, double litres) { if (litres > this.getCurrentCapacity() && litres < secondContainer.getLeftOverCapacity()) System.out.println("Can't be accommodated"); else { this.currentCapacity = this.currentCapacity - litres; secondContainer.fill(litres); System.out.println(litres + " litres of liquid is transferred"); } } //adds the specified litres of contents to the container public void fill(double litres) { if (getLeftOverCapacity() >= litres) { currentCapacity = currentCapacity + litres; System.out.println(litres + " litres of liquid is added"); } else System.out.println("Can't be accomodated"); } // ====================== // Various accessor methods // ====================== public double getCurrentCapacity() { return (currentCapacity); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

} public double getLeftOverCapacity() { return (maximumCapacity - currentCapacity); } public static void main(String[] args) { Container firstContainer = new Container(100, 0); Container secondContainer = new Container(70, 0); firstContainer.fill(30); secondContainer.fill(60); System.out.println("\nCurrent Capacity of the first container is " + firstContainer.getCurrentCapacity()); System.out.println("Current Capacity of the second container is " + secondContainer.getCurrentCapacity()); firstContainer.transferInto(secondContainer, 10); System.out.println("\nCurrent Capacity of the first container is " + firstContainer.getCurrentCapacity()); System.out.println("Current Capacity of the second container is " + secondContainer.getCurrentCapacity()); secondContainer.transferInto(firstContainer, 50); System.out.println("\nCurrent Capacity of the first container is " + firstContainer.getCurrentCapacity()); System.out.println("Current Capacity of the second container is " + secondContainer.getCurrentCapacity()); }

} 4. /** * Competition.java * * This class is used by Team.java. It contains information about * a particular programming competition. * Created: Sat Mar 05 2005 * * @author Kenrick Mock Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

* @version 1 */ public class Competition { private String competitionName; private String winner; private String runnerup; private int year; /** * Default constructor; Initialize variables and year to 0. */ public Competition() { competitionName = "No Competition Name"; winner = "Unknown"; runnerup = "Unknown"; year = 0; } /** * Constructor; Initialize variables to input values. * * @param competitionName Name of the competition * @param winner Name of the winning team * @param runnerup Name of the runner-up team * @param year Year of the competition */ public Competition(String competitionName, String winner, String runnerup, int year) { this.competitionName = competitionName; this.winner = winner; this.runnerup = runnerup; this.year = year; } /** * Return competition information as a string. * * @return String encapsulating all of the competition information. */ public String toString() { return "Competition Name:" + competitionName + "\n" + "Winner: " + winner + "\n" + Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

"Runner-Up: " + runnerup + "\n" + "Year: " + year; }

// ====================== // Various accessor and mutator methods // ====================== public String getCompetitionName() { return competitionName; } public void setCompetitionName(String competitionName) { this.competitionName = competitionName; } public String getWinner() { return winner; } public void setWinner(String winner) { this.winner = winner; } public String getRunnerup() { return runnerup; } public void setRunnerup(String runnerup) { this.runnerup = runnerup; } public int getYear() { return year; } public void setYear(int year) { this.year = year; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

} } // Competition

/** * Question4Team.java * * This program helps you keep track of the team members and competition information * for your school’s annual entries in computer science programming competitions. * Each team consists of exactly four team members. * Every year your team competes in two competitions. Competition * information is stored in the Competition class. * Created: Sat Mar 05 2005 * * @author Kenrick Mock * @version 1 */ public class Question4Team { // Name for the team private String teamName; // Names for each team members. The next chapter introduces a much nicer way // to store this information, using arrays. private String name1, name2, name3, name4; // Info on each competition private Competition competition1, competition2; /** * Default constructor; Initialize variables. */ public Question4Team() { teamName = "No Team Name Set"; name1 = "Name not set."; name2 = "Name not set."; name3 = "Name not set."; name4 = "Name not set."; competition1 = null; competition2 = null; } /** * Team constructor; Initialize variables to passed-in values. * The competition objects must be created outside this constructor. */ Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

public Question4Team(String teamName, String name1, String name2, String name3, String name4, Competition competition1, Competition competition2) { this.teamName = teamName; this.name1 = name1; this.name2 = name2; this.name3 = name3; this.name4 = name4; this.competition1 = competition1; this.competition2 = competition2; } /** * Team copy constructor; Performs a deep copy from the Competition class * instead of just copying a reference to the same Competition objects. */ public Question4Team(Question4Team otherTeam) { this.teamName = otherTeam.teamName; this.name1 = otherTeam.name1; this.name2 = otherTeam.name2; this.name3 = otherTeam.name3; this.name4 = otherTeam.name4; // Copy the competition classes to new instances if (otherTeam.competition1 != null) { this.competition1 = new Competition(otherTeam.competition1.getCompetitionName(), otherTeam.competition1.getWinner(), otherTeam.competition1.getRunnerup(), otherTeam.competition1.getYear()); } else { this.competition1 = null; } if (otherTeam.competition2 != null) { this.competition2 = new Competition(otherTeam.competition2.getCompetitionName(), otherTeam.competition2.getWinner(), otherTeam.competition2.getRunnerup(), otherTeam.competition2.getYear()); } else { this.competition2 = null; } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

/** * Output all team information to the console. */ public void OutputTeamInfo() { System.out.println("Team name:" + teamName); System.out.println("Team member 1: " + name1); System.out.println("Team member 2: " + name2); System.out.println("Team member 3: " + name3); System.out.println("Team member 4: " + name4); System.out.println("Competitions:"); if (competition1 != null) { System.out.println(competition1.toString()); } if (competition2 != null) { System.out.println(competition2.toString()); } System.out.println(); } // ====================== // Various accessor and mutator methods // ====================== public String getTeamName() { return teamName; } public void setTeamName(String teamName) { this.teamName = teamName; } public String getName1() { return name1; } public void setName1(String name1) { this.name1 = name1; } public String getName2() { return name2; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

} public void setName2(String name2) { this.name2 = name2; } public String getName3() { return name3; } public void setName3(String name3) { this.name3 = name3; } public String getName4() { return name4; } public void setName4(String name4) { this.name4 = name4; } public Competition getCompetition1() { return competition1; } public void setCompetition1(Competition competition1) { this.competition1 = competition1; } public Competition getCompetition2() { return competition2; } public void setCompetition2(Competition competition2) { this.competition2 = competition2; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

/** * This is the main method. * It creates a Team object and then tests the copy constructor. */ public static void main(String[] args) { Question4Team team1 = new Question4Team("The Java Studs", "Bill", "Ted", "Carol", "Alice", new Competition("ACM Programming Contest","The Java Studs", "Team University Java", 2004), new Competition("Antarctic Programming Contest","The Java Studs", "Frigid South", 2004) ); Question4Team team2 = new Question4Team(team1); // Copy constructor // Change competition information for team2 team2.getCompetition1().setYear(2005); team2.getCompetition1().setWinner("Mmm Java"); team2.getCompetition1().setRunnerup("Java By Night Java By Day"); team2.getCompetition2().setYear(2005); // Output information for both team1 and team2. // Team1's should be unchanged from the original values. team1.OutputTeamInfo(); team2.OutputTeamInfo(); } } // Question4Team

5. /** * Money.java * * * Created: Sun Dec 14 13:19:23 2003 * * @author Adrienne Decker * @version */ import java.text.DecimalFormat; public class Money { private int _dollars; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

private int _cents; public Money () { _dollars = 0; _cents = 0; } public Money(int dollars, int cents) { _dollars = dollars; _cents = cents; } public Money(int dollars) { _dollars = dollars; _cents = 0; } public int getDollars() { return _dollars; } public int getCents() { return _cents; } public void setDollars(int dollars) { _dollars = dollars; } public void setCents(int cents) { _cents = cents; } public boolean equals(Money other) { if ( other == null ) { return false; } // end of if () Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

else { return _dollars == other._dollars && _cents == other._cents; } // end of else } public String toString() { DecimalFormat decimal = new DecimalFormat("#.00"); double cents = (double)_cents/100; return "$" + _dollars + decimal.format(cents); } public static Money add(Money money1, Money money2) { int newDollars = money1.getDollars() + money2.getDollars(); int newCents = money1.getCents() + money2.getCents(); if ( newCents >= 100 ) { newDollars++; newCents -= 100; } // end of if () return new Money(newDollars, newCents); } public static Money subtract(Money money1, Money money2) { int newDollars = money1.getDollars() - money2.getDollars(); int newCents = money1.getCents() - money2.getCents(); if ( newCents < 0 ) { newDollars--; newCents += 100; } // end of if () return new Money(newDollars, newCents); } }// Money

/** * Question5.java * * * Created: Sun Dec 14 13:33:20 2003 Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

* Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ public class Question5 { public static void main(String[] args) { Money money1 = new Money(); System.out.println("Money is: " + money1); Money money2 = new Money(5); System.out.println("Money is: " + money2); Money money3 = new Money(10, 99); System.out.println("Money is: " + money3); System.out.println("Money1's dollars are: " + money1.getDollars()); System.out.println("Money1's cents are: " + money1.getCents()); System.out.println("Changing money1's dollars."); money1.setDollars(3); System.out.println("Money1 is : " + money1); System.out.println("Chaning money1's cents."); money1.setCents(50); System.out.println("Money1 is: " + money1); System.out.println("Money1 is equal to money2: " + money1.equals(money2)); Money money2copy = new Money(money2.getDollars(), money2.getCents()); System.out.println("Money2 is equal to a copy of money2: " + money2.equals(money2copy)); Money result = Money.add(money1, money2); System.out.println("Adding money1 and money2: " + result); System.out.println("Adding result from above and money3: " + Money.add(result, money3)); System.out.println("Subtracting money1 from money2: " Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

+ Money.subtract(money2, money1)); System.out.println("Subtracting money1 from money3: " + Money.subtract(money3, money1)); } } // Question5 /** * MoneyPart2.java * * * Created: Sun Dec 14 13:19:23 2003 * * @author Adrienne Decker * @version */ import java.text.DecimalFormat; public class MoneyPart2 { private int _dollars; private int _cents; public MoneyPart2 () { _dollars = 0; _cents = 0; } public MoneyPart2(int dollars, int cents) { _dollars = dollars; _cents = cents; } public MoneyPart2(int dollars) { _dollars = dollars; _cents = 0; } public int getDollars() { return _dollars; }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

public int getCents() { return _cents; } public void setDollars(int dollars) { _dollars = dollars; } public void setCents(int cents) { _cents = cents; } public boolean equals(MoneyPart2 other) { if ( other == null ) { return false; } // end of if () else { return _dollars == other._dollars && _cents == other._cents; } // end of else } public String toString() { DecimalFormat decimal = new DecimalFormat("#.00"); double cents = (double)_cents/100; return "$" + _dollars + decimal.format(cents); } public static MoneyPart2 add(MoneyPart2 money1, MoneyPart2 money2) { int newDollars = money1.getDollars() + money2.getDollars(); int newCents = money1.getCents() + money2.getCents(); if ( newCents >= 100 ) { newDollars++; newCents -= 100; } // end of if () return new MoneyPart2(newDollars, newCents); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

public static MoneyPart2 subtract(MoneyPart2 money1, MoneyPart2 money2) { int newDollars = money1.getDollars() - money2.getDollars(); int newCents = money1.getCents() - money2.getCents(); if ( newCents < 0 ) { newDollars--; newCents += 100; } // end of if () return new MoneyPart2(newDollars, newCents); } public MoneyPart2 add(MoneyPart2 other) { int newDollars = this.getDollars() + other.getDollars(); int newCents = this.getCents() + other.getCents(); if ( newCents >= 100 ) { newDollars++; newCents -= 100; } // end of if () return new MoneyPart2(newDollars, newCents); } public MoneyPart2 subtract(MoneyPart2 other) { int newDollars = this.getDollars() - other.getDollars(); int newCents = this.getCents() - other.getCents(); if ( newCents < 0 ) { newDollars--; newCents += 100; } // end of if () return new MoneyPart2(newDollars, newCents); } }// MoneyPart2

/** * Question5Part2.java * * Created: Sun Dec 14 13:33:20 2003 Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

* Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ public class Question5Part2 { public static void main(String[] args) { MoneyPart2 money1 = new MoneyPart2(); System.out.println("Money is: " + money1); MoneyPart2 money2 = new MoneyPart2(5); System.out.println("Money is: " + money2); MoneyPart2 money3 = new MoneyPart2(10, 99); System.out.println("Money is: " + money3); System.out.println("Money1's dollars are: " + money1.getDollars()); System.out.println("Money1's cents are: " + money1.getCents()); System.out.println("Changing money1's dollars."); money1.setDollars(3); System.out.println("Money1 is : " + money1); System.out.println("Chaning money1's cents."); money1.setCents(50); System.out.println("Money1 is: " + money1); System.out.println("Money1 is equal to money2: " + money1.equals(money2)); MoneyPart2 money2copy = new MoneyPart2(money2.getDollars(), money2.getCents()); System.out.println("Money2 is equal to a copy of money2: " + money2.equals(money2copy)); MoneyPart2 result = MoneyPart2.add(money1, money2); System.out.println("Adding money1 and money2: " + result); System.out.println("Adding result from above and money3: " + MoneyPart2.add(result, money3)); System.out.println("Subtracting money1 from money2: " Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

+ MoneyPart2.subtract(money2, money1)); System.out.println("Subtracting money1 from money3: " + MoneyPart2.subtract(money3, money1)); result = money1.add(money2); System.out.println("Using non-static add for money1 and money2: " + result); System.out.println("Using non-static add for adding result from" + " before and money3: " + result.add(money3)); System.out.println("Using non-static subtract, money1 from money2: " + money2.subtract(money1)); System.out.println("Using non-static subtract, money1 from money3: " + money3.subtract(money1)); } } // Question5Part2 /** * MoneyPart2Alternate.java * * Created: Sun Dec 14 13:19:23 2003 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ import java.text.DecimalFormat; public class MoneyPart2Alternate { private int _dollars; private int _cents; public MoneyPart2Alternate () { _dollars = 0; _cents = 0; } public MoneyPart2Alternate(int dollars, int cents) { _dollars = dollars; _cents = cents; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

} public MoneyPart2Alternate(int dollars) { _dollars = dollars; _cents = 0; } public int getDollars() { return _dollars; } public int getCents() { return _cents; } public void setDollars(int dollars) { _dollars = dollars; } public void setCents(int cents) { _cents = cents; } public boolean equals(MoneyPart2Alternate other) { if ( other == null ) { return false; } // end of if () else { return _dollars == other._dollars && _cents == other._cents; } // end of else } public String toString() { DecimalFormat decimal = new DecimalFormat("#.00"); double cents = (double)_cents/100; return "$" + _dollars + decimal.format(cents); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

public static MoneyPart2Alternate add(MoneyPart2Alternate money1, MoneyPart2Alternate money2) { int newDollars = money1.getDollars() + money2.getDollars(); int newCents = money1.getCents() + money2.getCents(); if ( newCents >= 100 ) { newDollars++; newCents -= 100; } // end of if () return new MoneyPart2Alternate(newDollars, newCents); } public static MoneyPart2Alternate subtract(MoneyPart2Alternate money1, MoneyPart2Alternate money2) { int newDollars = money1.getDollars() - money2.getDollars(); int newCents = money1.getCents() - money2.getCents(); if ( newCents < 0 ) { newDollars--; newCents += 100; } // end of if () return new MoneyPart2Alternate(newDollars, newCents); } public void add(MoneyPart2Alternate other) { int newDollars = this.getDollars() + other.getDollars(); int newCents = this.getCents() + other.getCents(); if ( newCents >= 100 ) { newDollars++; newCents -= 100; } // end of if () _dollars = newDollars; _cents = newCents; } public void subtract(MoneyPart2Alternate other) { int newDollars = this.getDollars() - other.getDollars(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

int newCents = this.getCents() - other.getCents(); if ( newCents < 0 ) { newDollars--; newCents += 100; } // end of if () _dollars = newDollars; _cents = newCents; } }// MoneyPart2Alternate

/** * Question1Part2Alternate.java * * Created: Sun Dec 14 13:33:20 2003 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ public class Question5Part2Alternate { public static void main(String[] args) { MoneyPart2Alternate money1 = new MoneyPart2Alternate(); System.out.println("Money is: " + money1); MoneyPart2Alternate money2 = new MoneyPart2Alternate(5); System.out.println("Money is: " + money2); MoneyPart2Alternate money3 = new MoneyPart2Alternate(10, 99); System.out.println("Money is: " + money3); System.out.println("Money1's dollars are: " + money1.getDollars()); System.out.println("Money1's cents are: " + money1.getCents()); System.out.println("Changing money1's dollars."); money1.setDollars(3); System.out.println("Money1 is : " + money1); System.out.println("Chaning money1's cents."); money1.setCents(50); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

System.out.println("Money1 is: " + money1); System.out.println("Money1 is equal to money2: " + money1.equals(money2)); MoneyPart2Alternate money2copy = new MoneyPart2Alternate(money2.getDollars(), money2.getCents()); System.out.println("Money2 is equal to a copy of money2: " + money2.equals(money2copy)); MoneyPart2Alternate result = MoneyPart2Alternate.add(money1, money2); System.out.println("Adding money1 and money2: " + result); System.out.println("Adding result from above and money3: " + MoneyPart2Alternate.add(result, money3)); System.out.println("Subtracting money1 from money2: " + MoneyPart2Alternate.subtract(money2, money1)); System.out.println("Subtracting money1 from money3: " + MoneyPart2Alternate.subtract(money3, money1)); money1.add(money2); System.out.println("Using non-static alternate add for money1 and" + " money2: " + money1); money1.add(money3); System.out.println("Using non-static alternate add for adding" + " money1 and money3: " + money1); money3.subtract(money2); System.out.println("Using non-static alternate subtract, money2" + " from money3: " + money3); money1.subtract(money3); System.out.println("Using non-static alternate subtract, money3" +" from money1: " + money1); } } // Question5Part2Alternate 6. /** * Rational.java * * Created: Sun Dec 14 13:19:23 2003 * * @author Adrienne Decker Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

* @version */ public class Rational { private int _numerator; private int _denominator; public Rational () { _numerator = 0; _denominator = 1; } public Rational(int numerator, int denominator) { _numerator = numerator; _denominator = denominator; } public Rational (int wholeNumber) { _numerator = wholeNumber; _denominator = 1; } public int getNumerator() { return _numerator; } public int getDenominator() { return _denominator; } public void setNumerator(int numerator) { _numerator = numerator; } public void setDenominator(int denominator) { if ( denominator == 0 ) { System.out.println("Fatal error."); System.exit(1); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

} // end of if () _denominator = denominator; } public boolean equals(Rational other) { if ( other == null ) { return false; } // end of if () else { this.normalize(); other.normalize(); return _numerator * other._denominator == _denominator * other._numerator; } // end of else } public String toString() { this.normalize(); return "" + _numerator + "/" + _denominator; } public void normalize() { if ( _denominator < 0 ) { _denominator = -_denominator; _numerator = -_numerator; } // end of if () } public static Rational add(Rational rational1, Rational rational2) { int newNum, newDenom; if ( rational1._denominator == rational2._denominator ) { newNum = rational1._numerator + rational2.getNumerator(); newDenom = rational1.getDenominator(); } // end of if () else { newNum = rational1.getNumerator() * rational2.getDenominator() Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

+ rational2.getNumerator() * rational1.getDenominator(); newDenom = rational1.getDenominator() * rational2.getDenominator(); } // end of else return new Rational(newNum, newDenom); } public static Rational subtract(Rational rational1, Rational rational2) { int newNum, newDenom; if ( rational1._denominator == rational2._denominator ) { newNum = rational1._numerator - rational2.getNumerator(); newDenom = rational1.getDenominator(); } // end of if () else { newNum = rational1.getNumerator() * rational2.getDenominator() - rational2.getNumerator() * rational1.getDenominator(); newDenom = rational1.getDenominator()* rational2.getDenominator(); } // end of else return new Rational(newNum, newDenom); } public static Rational multiply(Rational rational1, Rational rational2) { int newNum = rational1.getNumerator() * rational2.getNumerator(); int newDenom= rational1.getDenominator() * rational2.getDenominator(); return new Rational(newNum, newDenom); } public static Rational divide(Rational rational1, Rational rational2) { Rational newRational2 = new Rational(rational2.getDenominator(), rational2.getNumerator()); return Rational.multiply(rational1, newRational2); } }// Rational

/** Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

* Question6.java * * Created: Sun Dec 14 13:33:20 2003 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ public class Question6 { public static void main(String[] args) { Rational rational1 = new Rational(); System.out.println("Number is: " + rational1); Rational rational2 = new Rational(5); System.out.println("Number is: " + rational2); Rational rational3 = new Rational(1, 4); System.out.println("Number is: " + rational3); System.out.println("Rational1's numerator is: " + rational1.getNumerator()); System.out.println("Rational1's denominator is: " + rational1.getDenominator()); System.out.println("Changing rational1's numerator."); rational1.setNumerator(3); System.out.println("Rational1 is : " + rational1); System.out.println("Chaning rational1's denominator."); rational1.setDenominator(4); System.out.println("Rational1 is: " + rational1); System.out.println("rational1 is equal to rational2: " + rational1.equals(rational2)); Rational rational2copy = new Rational(rational2.getNumerator(), rational2.getDenominator()); System.out.println("Rational is equal to a copy of rational2: " + rational2.equals(rational2copy)); Rational nonNormal = new Rational(10, -25); System.out.println("A non-normalized number (10, -25)," Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

+ " should normalize before printing: " + nonNormal); System.out.println("Adding 1/4 and 3/4: " + Rational.add(rational1, rational3)); System.out.println("Adding 3/4 and 5/1: " + Rational.add(rational1, rational2)); System.out.println("Subtracting 3/4 - 1/4: " + Rational.subtract(rational1, rational3)); System.out.println("Subtracting 5/1 - 3/4: " + Rational.subtract(rational2, rational1)); System.out.println("Multiplying 1/4 * 3/4: " + Rational.multiply(rational1, rational3)); System.out.println("Dividing 5/1 by 1/2: " + Rational.divide(rational2, new Rational(1,2))); } } // Question6 /** * Rational2.java * * * Created: Sun Dec 14 13:19:23 2003 * * @author Adrienne Decker * @version */ public class Rational2 { private int _numerator; private int _denominator; public Rational2 () { _numerator = 0; _denominator = 1; } public Rational2(int numerator, int denominator) { _numerator = numerator; _denominator = denominator; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

} public Rational2 (int wholeNumber) { _numerator = wholeNumber; _denominator = 1; } public int getNumerator() { return _numerator; } public int getDenominator() { return _denominator; } public void setNumerator(int numerator) { _numerator = numerator; } public void setDenominator(int denominator) { if ( denominator == 0 ) { System.out.println("Fatal error."); System.exit(1); } // end of if () _denominator = denominator; } public boolean equals(Rational2 other) { if ( other == null ) { return false; } // end of if () else { this.normalize(); other.normalize(); return _numerator * other._denominator == _denominator * other._numerator; } // end of else Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

} public String toString() { this.normalize(); return "" + _numerator + "/" + _denominator; } public void normalize() { if ( _denominator < 0 ) { _denominator = -_denominator; _numerator = -_numerator; } // end of if () } public static Rational2 add(Rational2 rational1, Rational2 rational2) { int newNum, newDenom; if ( rational1._denominator == rational2._denominator ) { newNum = rational1._numerator + rational2.getNumerator(); newDenom = rational1.getDenominator(); } // end of if () else { newNum = rational1.getNumerator() * rational2.getDenominator() + rational2.getNumerator() * rational1.getDenominator(); newDenom = rational1.getDenominator() * rational2.getDenominator(); } // end of else return new Rational2(newNum, newDenom); } public static Rational2 subtract(Rational2 rational1, Rational2 rational2) { int newNum, newDenom; if ( rational1._denominator == rational2._denominator ) { newNum = rational1._numerator - rational2.getNumerator(); newDenom = rational1.getDenominator(); } // end of if () else Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

{ newNum = rational1.getNumerator() * rational2.getDenominator() - rational2.getNumerator() * rational1.getDenominator(); newDenom = rational1.getDenominator()* rational2.getDenominator(); } // end of else return new Rational2(newNum, newDenom); } public static Rational2 multiply(Rational2 rational1, Rational2 rational2) { int newNum = rational1.getNumerator() * rational2.getNumerator(); int newDenom= rational1.getDenominator() * rational2.getDenominator(); return new Rational2(newNum, newDenom); } public static Rational2 divide(Rational2 rational1, Rational2 rational2) { Rational2 newRational22 = new Rational2(rational2.getDenominator(), rational2.getNumerator()); return Rational2.multiply(rational1, newRational22); } public Rational2 add(Rational2 rational2) { int newNum, newDenom; if ( this._denominator == rational2._denominator ) { newNum = this._numerator + rational2.getNumerator(); newDenom = this.getDenominator(); } // end of if () else { newNum = this.getNumerator() * rational2.getDenominator() + rational2.getNumerator() * this.getDenominator(); newDenom = this.getDenominator() * rational2.getDenominator(); } // end of else return new Rational2(newNum, newDenom); } public Rational2 subtract(Rational2 rational2) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

{ int newNum, newDenom; if ( this._denominator == rational2._denominator ) { newNum = this._numerator - rational2.getNumerator(); newDenom = this.getDenominator(); } // end of if () else { newNum = this.getNumerator() * rational2.getDenominator() - rational2.getNumerator() * this.getDenominator(); newDenom = this.getDenominator()* rational2.getDenominator(); } // end of else return new Rational2(newNum, newDenom); } public Rational2 multiply(Rational2 rational2) { int newNum = this.getNumerator() * rational2.getNumerator(); int newDenom= this.getDenominator() * rational2.getDenominator(); return new Rational2(newNum, newDenom); } public Rational2 divide(Rational2 rational2) { Rational2 newRational22 = new Rational2(rational2.getDenominator(), rational2.getNumerator()); return this.multiply(newRational22); } }// Rational2

/** * Question6Part2.java * * Created: Sun Dec 14 13:33:20 2003 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

public class Question6Part2 { public static void main(String[] args) { Rational2 rational1 = new Rational2(); System.out.println("Number is: " + rational1); Rational2 rational2 = new Rational2(5); System.out.println("Number is: " + rational2); Rational2 rational3 = new Rational2(1, 4); System.out.println("Number is: " + rational3); System.out.println("Rational1's numerator is: " + rational1.getNumerator()); System.out.println("Rational1's denominator is: " + rational1.getDenominator()); System.out.println("Changing rational1's numerator."); rational1.setNumerator(3); System.out.println("Rational1 is : " + rational1); System.out.println("Chaning rational1's denominator."); rational1.setDenominator(4); System.out.println("Rational1 is: " + rational1); System.out.println("rational1 is equal to rational2: " + rational1.equals(rational2)); Rational2 rational2copy = new Rational2(rational2.getNumerator(), rational2.getDenominator()); System.out.println("Rational2 is equal to a copy of rational2: " + rational2.equals(rational2copy)); Rational2 nonNormal = new Rational2(10, -25); System.out.println("A non-normalized number (10, -25)," + " should normalize before printing: " + nonNormal); System.out.println("Adding 1/4 and 3/4: " + Rational2.add(rational1, rational3)); System.out.println("Adding 3/4 and 5/1: " + Rational2.add(rational1, rational2));

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

System.out.println("Subtracting 3/4 - 1/4: " + Rational2.subtract(rational1, rational3)); System.out.println("Subtracting 5/1 - 3/4: " + Rational2.subtract(rational2, rational1)); System.out.println("Multiplying 1/4 * 3/4: " + Rational2.multiply(rational1, rational3)); System.out.println("Dividing 5/1 by 1/2: " + Rational2.divide(rational2, new Rational2(1,2))); System.out.println("Adding 1/4 and 3/4: " + rational1.add(rational3)); System.out.println("Adding 3/4 and 5/1: " + rational1.add(rational2)); System.out.println("Subtracting 3/4 - 1/4: " + rational1.subtract(rational3)); System.out.println("Subtracting 5/1 - 3/4: " + rational2.subtract(rational1)); System.out.println("Multiplying 1/4 * 3/4: " + rational1.multiply(rational3)); System.out.println("Dividing 5/1 by 1/2: " + rational2.divide(new Rational2(1,2))); } } // Question6Part2

/** * Rational2Alternate.java * * * Created: Sun Dec 14 13:19:23 2003 * * @author Adrienne Decker * @version */ public class Rational2Alternate { private int _numerator; private int _denominator;

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

public Rational2Alternate () { _numerator = 0; _denominator = 1; } public Rational2Alternate(int numerator, int denominator) { _numerator = numerator; _denominator = denominator; } public Rational2Alternate (int wholeNumber) { _numerator = wholeNumber; _denominator = 1; } public int getNumerator() { return _numerator; } public int getDenominator() { return _denominator; } public void setNumerator(int numerator) { _numerator = numerator; } public void setDenominator(int denominator) { if ( denominator == 0 ) { System.out.println("Fatal error."); System.exit(1); } // end of if () _denominator = denominator; } public boolean equals(Rational2Alternate other) { if ( other == null ) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

{ return false; } // end of if () else { this.normalize(); other.normalize(); return _numerator * other._denominator == _denominator * other._numerator; } // end of else } public String toString() { this.normalize(); return "" + _numerator + "/" + _denominator; } public void normalize() { if ( _denominator < 0 ) { _denominator = -_denominator; _numerator = -_numerator; } // end of if () } public static Rational2Alternate add(Rational2Alternate rational1, Rational2Alternate rational2) { int newNum, newDenom; if ( rational1._denominator == rational2._denominator ) { newNum = rational1._numerator + rational2.getNumerator(); newDenom = rational1.getDenominator(); } // end of if () else { newNum = rational1.getNumerator() * rational2.getDenominator() + rational2.getNumerator() * rational1.getDenominator(); newDenom = rational1.getDenominator() * rational2.getDenominator(); } // end of else return new Rational2Alternate(newNum, newDenom); }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

public static Rational2Alternate subtract(Rational2Alternate rational1, Rational2Alternate rational2) { int newNum, newDenom; if ( rational1._denominator == rational2._denominator ) { newNum = rational1._numerator - rational2.getNumerator(); newDenom = rational1.getDenominator(); } // end of if () else { newNum = rational1.getNumerator() * rational2.getDenominator() - rational2.getNumerator() * rational1.getDenominator(); newDenom = rational1.getDenominator()* rational2.getDenominator(); } // end of else return new Rational2Alternate(newNum, newDenom); } public static Rational2Alternate multiply(Rational2Alternate rational1, Rational2Alternate rational2) { int newNum = rational1.getNumerator() * rational2.getNumerator(); int newDenom= rational1.getDenominator() * rational2.getDenominator(); return new Rational2Alternate(newNum, newDenom); } public static Rational2Alternate divide(Rational2Alternate rational1, Rational2Alternate rational2) { Rational2Alternate newRational22 = new Rational2Alternate(rational2.getDenominator(), rational2.getNumerator()); return Rational2Alternate.multiply(rational1, newRational22); } public void add(Rational2Alternate rational2) { int newNum, newDenom; if ( this._denominator == rational2._denominator ) { newNum = this._numerator + rational2.getNumerator(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

newDenom = this.getDenominator(); } // end of if () else { newNum = this.getNumerator() * rational2.getDenominator() + rational2.getNumerator() * this.getDenominator(); newDenom = this.getDenominator() * rational2.getDenominator(); } // end of else _numerator = newNum; _denominator = newDenom; } public void subtract(Rational2Alternate rational2) { int newNum, newDenom; if ( this._denominator == rational2._denominator ) { newNum = this._numerator - rational2.getNumerator(); newDenom = this.getDenominator(); } // end of if () else { newNum = this.getNumerator() * rational2.getDenominator() - rational2.getNumerator() * this.getDenominator(); newDenom = this.getDenominator()* rational2.getDenominator(); } // end of else _numerator = newNum; _denominator = newDenom; } public void multiply(Rational2Alternate rational2) { int newNum = this.getNumerator() * rational2.getNumerator(); int newDenom= this.getDenominator() * rational2.getDenominator(); _numerator = newNum; _denominator = newDenom; } public void divide(Rational2Alternate rational2) { Rational2Alternate newRational22 = Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

new Rational2Alternate(rational2.getDenominator(), rational2.getNumerator()); this.multiply(newRational22); } }// Rational2Alternate

/** * Question6Part2Alternate.java * * Created: Sun Dec 14 13:33:20 2003 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ public class Question6Part2Alternate { public static void main(String[] args) { Rational2Alternate rational1 = new Rational2Alternate(); System.out.println("Number is: " + rational1); Rational2Alternate rational2 = new Rational2Alternate(5); System.out.println("Number is: " + rational2); Rational2Alternate rational3 = new Rational2Alternate(1, 4); System.out.println("Number is: " + rational3); System.out.println("Rational1's numerator is: " + rational1.getNumerator()); System.out.println("Rational1's denominator is: " + rational1.getDenominator()); System.out.println("Changing rational1's numerator."); rational1.setNumerator(3); System.out.println("Rational1 is : " + rational1); System.out.println("Chaning rational1's denominator."); rational1.setDenominator(4); System.out.println("Rational1 is: " + rational1); System.out.println("rational1 is equal to rational2: " Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

+ rational1.equals(rational2)); Rational2Alternate rational2copy = new Rational2Alternate(rational2.getNumerator(), rational2.getDenominator()); System.out.println("Rational2 is equal to a copy of rational2: " + rational2.equals(rational2copy)); Rational2Alternate nonNormal = new Rational2Alternate(10, -25); System.out.println("A non-normalized number (10, -25)," + " should normalize before printing: " + nonNormal); System.out.println("Adding 1/4 and 3/4: " + Rational2Alternate.add(rational1, rational3)); System.out.println("Adding 3/4 and 5/1: " + Rational2Alternate.add(rational1, rational2)); System.out.println("Subtracting 3/4 - 1/4: " + Rational2Alternate.subtract(rational1, rational3)); System.out.println("Subtracting 5/1 - 3/4: " + Rational2Alternate.subtract(rational2, rational1)); System.out.println("Multiplying 1/4 * 3/4: " + Rational2Alternate.multiply(rational1, rational3)); System.out.println("Dividing 5/1 by 1/2: " + Rational2Alternate.divide(rational2, new Rational2Alternate(1,2))); rational1.add(rational3); System.out.println("Adding 1/4 and 3/4: " + rational1); rational2.add(new Rational2Alternate(3,4)); System.out.println("Adding 3/4 and 5/1: " + rational2); rational1.setNumerator(3); rational1.setDenominator(4); rational1.subtract(rational3); System.out.println("Subtracting 3/4 - 1/4: " + rational1); rational2.setNumerator(5); rational2.setDenominator(1); rational2.subtract(new Rational2Alternate(3,4)); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

System.out.println("Subtracting 5/1 - 3/4: " + rational2); rational3 = new Rational2Alternate(1,4); rational1 = new Rational2Alternate(3,4); rational3.multiply(rational1); System.out.println("Multiplying 1/4 * 3/4: " + rational3); rational2.setNumerator(5); rational2.setDenominator(1); rational2.divide(new Rational2Alternate(1,2)); System.out.println("Dividing 5/1 by 1/2: " + rational2); } } // Question6Part2Alternate 7. /** * PhoneBilling.java * * This program instantiates multiple instances of LocalCall and * STDCall classes that are used to track local and STD call details * respectively. The program displays the call details like call * duration, price, discounted call details for both local and STD * calls. * * Created: Jan 31, 2016 * * @author * @version 1 */ public class PhoneBilling { public static void main(String[] args) { LocalCall call1 = new LocalCall(245689, 289754, 435); LocalCall call2 = new LocalCall(256809, 276754, 4055); LocalCall call3 = new LocalCall(268001, 211022, 1100); LocalCall call4 = new LocalCall(245639, 269820, 55); LocalCall call5 = new LocalCall(289897, 235688, 235); System.out.println( "Source Number\tDestination Number\t" + "Call Duration\tCurrent Call Price"); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

call1.displayBill(); call2.displayBill(); call3.displayBill(); call4.displayBill(); call5.displayBill(); System.out.println( "Total Local Call Billing Price : " + LocalCall.getTotalCallPrice()); System.out.println("Total Discounted Local Call " + "Billing Price : " + LocalCall.discountCall()); System.out.println( "STD\tSource Number\tDest STD\tDest" + " Number\tDuration\tCall Price"); STDCall stdCall1 = new STDCall(11, 741689, 32, 589734, 435); STDCall stdCall2 = new STDCall(11, 751809, 12, 676744, 4055); STDCall stdCall3 = new STDCall(91, 861001, 22, 711052, 1100); STDCall stdCall4 = new STDCall(34, 941639, 56, 898255, 55); STDCall stdCall5 = new STDCall(56, 684897, 34, 835666, 235); stdCall1.displayBill(); stdCall2.displayBill(); stdCall3.displayBill(); stdCall4.displayBill(); stdCall5.displayBill(); System.out .println("Total STD Call Billing Price : " + STDCall.getTotalCallPrice()); System.out.println( "Total Discounted STD Call Billing Price : " + STDCall.discountCall()); } } /** * LocalCall class that stores source phone number, destination phone * number, call duration and call price. It also stores the total call * duration and total call price across all local calls. * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

*/ class LocalCall { int sourceNumber; int destNumber; int callDuration; static double totalCallDuration; double currentCallPrice; static double totalCallPrice; /** * Instantiates the class with call details * * @param sNumber * Source phone number * @param dNumber * Destination phone number * @param cDuration * Call duration in seconds */ public LocalCall(int sNumber, int dNumber, int cDuration) { sourceNumber = sNumber; destNumber = dNumber; callDuration = cDuration; totalCallDuration += callDuration; if (callDuration <= 60) currentCallPrice = 0.20; else if (callDuration > 60 && callDuration <= 120) currentCallPrice = 0.15; else currentCallPrice = 0.10; totalCallPrice += currentCallPrice; } // Displays the bill for the last call public void displayBill() { System.out.println(sourceNumber + "\t\t" + destNumber + "\t\t\t" + callDuration + "\t\t" + currentCallPrice); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

// Returns the price for the last call public static double getTotalCallPrice() { return (totalCallPrice); } // Performs a call with discounted price public static double discountCall() { double discountedPrice = 0.0, discountRate = 0.0; if (totalCallDuration > 600 && totalCallDuration <= 1200) discountRate = 0.05; if (totalCallDuration > 1200) discountRate = 0.07; discountedPrice = totalCallPrice - (totalCallPrice * discountRate); return (discountedPrice); } } /** * STDCall class that stores source phone number, source STD code, * destination phone number, destination STD code, call duration and * call price. It also stores the total call duration and total call * price across all STD calls. * */ class STDCall { int sourceNumber; int sourceSTDCode; int destNumber; int destSTDCode; int callDuration; static double totalCallDuration; double currentCallPrice; static double totalCallPrice; /** * Instantiates the STDCall class with required details * * @param sSTDCode * STD Code of the source phone number Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

* @param sNumber * Source phone number * @param dSTDCode * STD Code of the destination phone number * @param dNumber * Destination Phone Number * @param cDuration * Call duration in seconds */ public STDCall(int sSTDCode, int sNumber, int dSTDCode, int dNumber, int cDuration) { sourceNumber = sNumber; sourceSTDCode = sSTDCode; destNumber = dNumber; destSTDCode = dSTDCode; callDuration = cDuration; totalCallDuration += callDuration; if (callDuration <= 60) currentCallPrice = 0.60; else if (callDuration > 60 && callDuration <= 120) currentCallPrice = 0.40; else currentCallPrice = 0.20; totalCallPrice += currentCallPrice; } public void displayBill() { System.out.println( sourceSTDCode + "\t" + sourceNumber + "\t\t" + destSTDCode + "\t\t"+destNumber + "\t\t" + callDuration + "\t\t" + currentCallPrice); } public static double getTotalCallPrice() { return (totalCallPrice); } public static double discountCall() { double discountedPrice = 0.0, discountRate = 0.0; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

if (totalCallDuration > 600 && totalCallDuration <= 1200) discountRate = 0.08; if (totalCallDuration > 1200) discountRate = 0.10; discountedPrice = totalCallPrice - (totalCallPrice * discountRate); return (discountedPrice); } } 8. /** * Question 8 * * Modification to the PizzaOrder class. * Requires the Pizza class from PP 4.11. * * Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ public class PizzaOrder { private Pizza pizza1, pizza2, pizza3; private int numPizzas; public PizzaOrder() { numPizzas = 0; pizza1 = null; pizza2 = null; pizza3 = null; } // Copy constructor public PizzaOrder(PizzaOrder order) { numPizzas = order.numPizzas; pizza1 = null; pizza2 = null; pizza3 = null; // Make copies of the Pizza objects Pizza orig = order.getPizza1(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

if (orig != null) { pizza1 = new Pizza(orig.getSize(), orig.getNumCheeseToppings(), orig.getNumHamToppings(), orig.getNumPepperoniToppings()); } orig = order.getPizza2(); if (orig != null) { pizza2 = new Pizza(orig.getSize(), orig.getNumCheeseToppings(), orig.getNumHamToppings(), orig.getNumPepperoniToppings()); } orig = order.getPizza3(); if (orig != null) { pizza3 = new Pizza(orig.getSize(), orig.getNumCheeseToppings(), orig.getNumHamToppings(), orig.getNumPepperoniToppings()); } } public void setNumPizzas(int num) { numPizzas = num; } public int getNumPizzas() { return numPizzas; } public void setPizza1(Pizza pizza) { pizza1 = pizza; } public void setPizza2(Pizza pizza) { pizza2 = pizza; } public void setPizza3(Pizza pizza) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

{ pizza3 = pizza; } public Pizza getPizza1() { if (numPizzas > 0) return pizza1; else return null; } public Pizza getPizza2() { if (numPizzas > 1) return pizza2; else return null; } public Pizza getPizza3() { if (numPizzas > 2) return pizza3; else return null; } public double calcTotal() { double total = 0; if (numPizzas >= 1) total += pizza1.calcCost(); if (numPizzas >= 2) total += pizza2.calcCost(); if (numPizzas >= 3) total += pizza3.calcCost(); return total; } // Sample main public static void main(String[] args) { Pizza pizza1 = new Pizza("Large",1,1,0); Pizza pizza2 = new Pizza("Medium",2,0,2); PizzaOrder order1 = new PizzaOrder(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

order1.setNumPizzas(2); order1.setPizza1(pizza1); order1.setPizza2(pizza2); double total = order1.calcTotal(); // Should be 38 System.out.println("Total of original order: " + total); // Copy the order PizzaOrder order2 = new PizzaOrder(order1); // Change one topping to new order order2.getPizza1().setNumCheeseToppings(3); total = order2.calcTotal(); // total should be 22 + 20 = 44 double origTotal = order1.calcTotal(); // origTotal should still be 38 System.out.println("Total of copied and " + "modified order: " + total); System.out.println("Original total unchanged at: " + origTotal); } } // Question 8

9. /** Question 9 Class for a person with a name and dates for birth and death. Class invariant: A Person always has a date of birth, and if the Person has a date of death, then the date of death is equal to or later than the date of birth. Generate javadoc with: > javadoc -author -version Person.java @author Kenrick Mock @version 1 */ public class Person { private String name; private Date born; private Date died;//null indicates still alive.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

/** Person constructor. @param initialName name of the person @param birthDate date of birth @param deathDate date of death */ public Person(String initialName, Date birthDate, Date deathDate) { if (consistent(birthDate, deathDate)) { name = initialName; born = new Date(birthDate); if (deathDate == null) died = null; else died = new Date(deathDate); } else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } /** Person copy constructor. @param original Person to copy from */ public Person(Person original) { if (original == null) { System.out.println("Fatal error."); System.exit(0); } name = original.name; born = new Date(original.born); if (original.died == null) died = null; else died = new Date(original.died); } /** Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

Sets a new name, birth, and death date. @param newName name of the person @param birthDate date of birth @param deathDate date of death */ public void set(String newName, Date birthDate, Date deathDate) { if (consistent(birthDate, deathDate)) { name = newName; born = new Date(birthDate); if (deathDate == null) died = null; else died = new Date(deathDate); } else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } /** Returns the person's details encoded in a String. @return String containing the person's details */ public String toString( ) { String diedString; if (died == null) diedString = ""; //Empty string else diedString = died.toString( ); return (name + ", " + born + "-" + diedString); } /** Checks if this person object equals another. Two people are equal if their names are the same and their birth/death dates match. @param otherPerson Person to compare with @return true or false depending upon equality */ public boolean equals(Person otherPerson) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

{ if (otherPerson == null) return false; else return (name.equals(otherPerson.name) && born.equals(otherPerson.born) && datesMatch(died, otherPerson.died) ); } /** To match date1 and date2 must either be the same date or both be null. */ private static boolean datesMatch(Date date1, Date date2) { if (date1 == null) return (date2 == null); else if (date2 == null) //&& date1 != null return false; else // both dates are not null. return(date1.equals(date2)); } /** Precondition: newDate is a consistent date of birth. Postcondition: Date of birth of the calling object is newDate. @param newDate the new birth date */ public void setBirthDate(Date newDate) { if (consistent(newDate, died)) born = new Date(newDate); else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } /** Precondition: newDate is a consistent date of death. Postcondition: Date of death of the calling object is newDate. @param newDate the new death date */ public void setDeathDate(Date newDate) {

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

if (!consistent(born, newDate)) { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } if (newDate == null) died = null; else died = new Date(newDate); } /** Change the person's name. @param newName the new name */ public void setName(String newName) { name = newName; } /** Precondition: The date of birth has been set, and changing the year part of the date of birth will give a consistent date of birth. Postcondition: The year of birth is (changed to) newYear. @param newYear the new birth year */ public void setBirthYear(int newYear) { if (born == null) //Precondition is violated { System.out.println("Fata; Error. Aborting."); System.exit(0); } born.setYear(newYear); if (!consistent(born, died)) { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } /** Precondition: The date of death has been set, and changing the year part of the date of death will give a consistent date of death. Postcondition: The year of death is (changed to) newYear. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

@param newYear the new death year */ public void setDeathYear(int newYear) { if (died == null) //Precondition is violated { System.out.println("Fata; Error. Aborting."); System.exit(0); } died.setYear(newYear); if (!consistent(born, died)) { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } /** Retrieves the person's name. @return the person's name */ public String getName( ) { return name; } /** Retrieves the person's birth date. @return the person's birth date */ public Date getBirthDate( ) { return new Date(born); } /** Retrieves the person's death date. @return the person's death date */ public Date getDeathDate( ) { if (died == null) return null; else return new Date(died); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

/** To be consistent, birthDate must not be null. If there is no date of death (deathDate == null), that is consistent with any birthDate. Otherwise, the birthDate must come before or be equal to the deathDate. */ private static boolean consistent(Date birthDate, Date deathDate) { if (birthDate == null) return false; else if (deathDate == null) return true; else return (birthDate.precedes(deathDate ) || birthDate.equals(deathDate )); } } // Question 9

// Question 10 File: produce.txt Broccoli Tomato Kiwi Kale Tomatillo /** * Question 10 * * Box of Produce class. Loop to create multiple boxes * and a static variable for including salsa verde recipes. * * Created: Fri Apr 27 2012 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Random; public class BoxOfProduce Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

{ private String bundle1,bundle2,bundle3; private boolean hasSalsaFlyer; private int tomatilloCount; // Count # of tomatillos // Static for 5 initial salsa flyers private static int numSalsaFlyers = 5; public BoxOfProduce() { bundle1 = ""; bundle2 = ""; bundle3 = ""; hasSalsaFlyer = false; } public BoxOfProduce(String b1, String b2, String b3) { bundle1 = b1; bundle2 = b2; bundle3 = b3; hasSalsaFlyer = false; } public void setBundle1(String b1) { // Check if we are removing tomatillos if (bundle1.equalsIgnoreCase("tomatillo")) tomatilloCount--; bundle1 = b1; // Check if we just added tomatillos if (b1.equalsIgnoreCase("tomatillo")) tomatilloCount++; // If there are flyers and we haven't already put // one in the box, and tomatillos are in the // box, then add the flyer if (!hasSalsaFlyer && (tomatilloCount>0) && numSalsaFlyers > 0) { hasSalsaFlyer = true; numSalsaFlyers--; } } public String getBundle1() { return bundle1; }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

public void setBundle2(String b2) { // Check if we are removing tomatillos if (bundle2.equalsIgnoreCase("tomatillo")) tomatilloCount--; bundle2 = b2; // Check if we just added tomatillos if (b2.equalsIgnoreCase("tomatillo")) tomatilloCount++; // If there are flyers and we haven't already put // one in the box, and tomatillos are in the // box, then add the flyer if (!hasSalsaFlyer && (tomatilloCount>0) && numSalsaFlyers > 0) { hasSalsaFlyer = true; numSalsaFlyers--; } } public String getBundle2() { return bundle2; } public void setBundle3(String b3) { // Check if we are removing tomatillos if (bundle3.equalsIgnoreCase("tomatillo")) tomatilloCount--; bundle3 = b3; // Check if we just added tomatillos if (b3.equalsIgnoreCase("tomatillo")) tomatilloCount++; // If there are flyers and we haven't already put // one in the box, and tomatillos are in the // box, then add the flyer if (!hasSalsaFlyer && (tomatilloCount>0) && numSalsaFlyers > 0) { hasSalsaFlyer = true; numSalsaFlyers--; } } public String getBundle3() { return bundle3; }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

public String toString() { if (hasSalsaFlyer) return "The box contains: " + bundle1 + ", " + bundle2 + ", " + bundle3 + ", salsa verde flyer"; else return "The box contains: " + bundle1 + ", " + bundle2 + ", " + bundle3; } public static void main(String[] args) { Scanner kbd = new Scanner(System.in); String addMoreBoxes; do { // Create a Box BoxOfProduce box = new BoxOfProduce(); // Pick three random numbers from 0 to 4 for the 5 possible food choices Random rnd = new Random(); int num1, num2, num3; num1 = rnd.nextInt(5); num2 = rnd.nextInt(5); num3 = rnd.nextInt(5); int lineRead = 0; Scanner fileIn = null; // Initializes fileIn to an empty object try { // Attempt to open the file fileIn = new Scanner( new FileInputStream("produce.txt")); } catch (FileNotFoundException e) { // If the file could not be found, this code is executed // and then the program exits System.out.println("File not found."); System.exit(0); } // Read from the file and if the line read in matches one of the // random numbers then set the corresponding bundle while (fileIn.hasNext()) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

{ String food = fileIn.next(); if (lineRead == num1) box.setBundle1(food); if (lineRead == num2) box.setBundle2(food); if (lineRead == num3) box.setBundle3(food); lineRead++; } fileIn.close(); // Show the box contents to the user and allow substitutions String selection = ""; do { System.out.println(box.toString()); System.out.println("Enter '1' to change bundle 1."); System.out.println("Enter '2' to change bundle 2."); System.out.println("Enter '3' to change bundle 3."); System.out.println("Enter 'q' to quit."); selection = kbd.next(); kbd.nextLine(); if (selection.equals("1")) { System.out.println("Enter item to substitute."); String item = kbd.nextLine(); box.setBundle1(item); } else if (selection.equals("2")) { System.out.println("Enter item to substitute."); String item = kbd.nextLine(); box.setBundle2(item); } else if (selection.equals("3")) { System.out.println("Enter item to substitute."); String item = kbd.nextLine(); box.setBundle3(item); } } while (!selection.equals("q")); System.out.println("Final Contents:"); System.out.println(box.toString());

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

System.out.println("Add another box (y/n)?"); addMoreBoxes = kbd.next(); kbd.nextLine(); } while (addMoreBoxes.equals("y")); } } // Question 10

11. package PackageTest; /** * Main.java * * This file goes into a folder named "PackageTest". * Compile from the parent folder with: * javac PackageTest/Main.java * This will compile Main.java, Money.java, and Rational.java. * * Run it from the parent folder with: * java PackageTest/Main * * Created: Apr 15 2015 * * @author Kenrick Mock * @version 1 * */

import MyMath.Rational; import Finance.Money; public class Main { public static void main(String[] args) { // Test the Rational class Rational rational1 = new Rational(); System.out.println("Number is: " + rational1); Rational rational2 = new Rational(5); System.out.println("Number is: " + rational2); Rational rational3 = new Rational(1, 4); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

System.out.println("Number is: " + rational3); System.out.println("Rational1's numerator is: " + rational1.getNumerator()); System.out.println("Rational1's denominator is: " + rational1.getDenominator()); // Test the Money class Money money3 = new Money(10, 99); System.out.println("Money is: " + money3); } }

package Finance; import java.text.DecimalFormat; /** * Money.java * * Place in a folder named Finance and compile from the parent folder * (see comments for Main.java) * * Created: Apr 15 2015 * * @author Kenrick Mock * @version 1 * */ public class Money { private int _dollars; private int _cents; public Money () { _dollars = 0; _cents = 0; } public Money(int dollars, int cents) { _dollars = dollars; _cents = cents; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

} public Money(int dollars) { _dollars = dollars; _cents = 0; } public int getDollars() { return _dollars; } public int getCents() { return _cents; } public void setDollars(int dollars) { _dollars = dollars; } public void setCents(int cents) { _cents = cents; } public boolean equals(Money other) { if ( other == null ) { return false; } // end of if () else { return _dollars == other._dollars && _cents == other._cents; } // end of else } public String toString() { DecimalFormat decimal = new DecimalFormat("#.00"); double cents = (double)_cents/100; return "$" + _dollars + decimal.format(cents); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

public static Money add(Money money1, Money money2) { int newDollars = money1.getDollars() + money2.getDollars(); int newCents = money1.getCents() + money2.getCents(); if ( newCents >= 100 ) { newDollars++; newCents -= 100; } // end of if () return new Money(newDollars, newCents); } public static Money subtract(Money money1, Money money2) { int newDollars = money1.getDollars() - money2.getDollars(); int newCents = money1.getCents() - money2.getCents(); if ( newCents < 0 ) { newDollars--; newCents += 100; } // end of if () return new Money(newDollars, newCents); } }// Money

package MyMath; /** * Rational.java * * Place in a folder named MyMath and compile from the parent folder * (see comments for Main.java) * * Created: Sun Dec 14 13:19:23 2003 * * @author Adrienne Decker * @version 1 * */ public class Rational { private int _numerator; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

private int _denominator; public Rational () { _numerator = 0; _denominator = 1; } public Rational(int numerator, int denominator) { _numerator = numerator; _denominator = denominator; } public Rational (int wholeNumber) { _numerator = wholeNumber; _denominator = 1; } public int getNumerator() { return _numerator; } public int getDenominator() { return _denominator; } public void setNumerator(int numerator) { _numerator = numerator; } public void setDenominator(int denominator) { if ( denominator == 0 ) { System.out.println("Fatal error."); System.exit(1); } // end of if () _denominator = denominator; } public boolean equals(Rational other) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

{ if ( other == null ) { return false; } // end of if () else { this.normalize(); other.normalize(); return _numerator * other._denominator == _denominator * other._numerator; } // end of else } public String toString() { this.normalize(); return "" + _numerator + "/" + _denominator; } public void normalize() { if ( _denominator < 0 ) { _denominator = -_denominator; _numerator = -_numerator; } // end of if () } public static Rational add(Rational rational1, Rational rational2) { int newNum, newDenom; if ( rational1._denominator == rational2._denominator ) { newNum = rational1._numerator + rational2.getNumerator(); newDenom = rational1.getDenominator(); } // end of if () else { newNum = rational1.getNumerator() * rational2.getDenominator() + rational2.getNumerator() * rational1.getDenominator(); newDenom = rational1.getDenominator() * rational2.getDenominator(); } // end of else return new Rational(newNum, newDenom); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 5, Instructor’s Manual

public static Rational subtract(Rational rational1, Rational rational2) { int newNum, newDenom; if ( rational1._denominator == rational2._denominator ) { newNum = rational1._numerator - rational2.getNumerator(); newDenom = rational1.getDenominator(); } // end of if () else { newNum = rational1.getNumerator() * rational2.getDenominator() - rational2.getNumerator() * rational1.getDenominator(); newDenom = rational1.getDenominator()* rational2.getDenominator(); } // end of else return new Rational(newNum, newDenom); } public static Rational multiply(Rational rational1, Rational rational2) { int newNum = rational1.getNumerator() * rational2.getNumerator(); int newDenom= rational1.getDenominator() * rational2.getDenominator(); return new Rational(newNum, newDenom); } public static Rational divide(Rational rational1, Rational rational2) { Rational newRational2 = new Rational(rational2.getDenominator(), rational2.getNumerator()); return Rational.multiply(rational1, newRational2); } }// Rational

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

Chapter 6

Arrays Key Terms Array indexed variable subscripted variable element index subscript length size base type square brackets [] illegal array index automatic initialization indexed variable arguments entire array parameters length of array arguments assignment with arrays == with arrays partially filled array for-each loop vararg specification ellipsis enumerated type array declarations indexed variables A multidimensional array is an array of arrays Ragged arrays array arguments returning an array

Brief Outline 6.1 Introduction to Arrays Creating and Accessing Arrays The length Instance Variable Initializing Arrays 6.2 Arrays and References Arrays are Objects Arrays Parameters Arguments for the Method main Methods that Return an Array 6.3 Programming with Arrays Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

Partially Filled Arrays The “for each” Loop Methods with a Variable Number of Parameters Privacy Leaks with Array Instance Variables A Preview of Vectors Enumerated Types 6.4 Multidimensional Arrays Multidimensional Array Basics Using the length Instance Variable Ragged Arrays Multidimensional Array Parameters and Returned Values

Teaching Suggestions This chapter discusses arrays as a means of storing information. This chapter covers both single dimensional and multidimensional arrays. The first section discusses the array basics, including how to create an array, access an element within an array, and finding an array’s length. The chapter then goes on to show how arrays can be used in a program, both as variables and parameters. Finally, the use of multidimensional arrays is discussed, along with how have more than one dimension changes how we use an array. The chapter also introduces many features that are new to Java 5. The first of these is the foreach loop, which provides students an easier way for accessing all of the elements of an array. It actually relies on a java.util.Iterator, but instructors do not have to explain this concept in order to explain the use of the for-each loop. The for-each loop relieves many of the common off-byone errors associated with students iterating over an array using the indices. The second new feature of Java 5 introduced is the ability for a method to have variable length arguments. If the programmer creates a method with a variable argument list, the method can be called with zero or more arguments of the type specified as being variable. These arguments are stored in an array and are accessible from within the method. The last new feature of Java 5 introduced in this chapter is Enumerated Types. This feature that is new to Java is not new to many other programming languages. This feature allows the user to create their own type with their own values. Common examples of the use of this feature include the creation of a type for the days of the week, the months of the year or the suits for a deck of cards. Key Points Declaring and Creating an Array. You must give the type of things that will be contained in an array as well as the size of the array when you declare and create the array. Sizes must be integers that are non-negative. An array can hold primitive data, or objects with no change in the syntax for declaring an creating an array.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

Arrays are Objects. This is a topic that some may not agree with. There is no Array.java class built into Java, so some instructors may prefer to address this topic at a different time. However, as the book suggests, treating arrays more like objects than primitives will be how the book handles these entities. Array Types are Reference Types. Like an object, the variable of an array is a reference to where the array is stored in memory. Array Indexed Variables as Arguments. If you are calling a method and need to pass in a parameter to the method call, you can most certainly use on element from an array that is present in the program. Array Parameters and Array Arguments. You can pass in an entire array as an argument to a method. If this array is changed by the method, then the changes will be made to the array, just as changes to an object stay with the object after the method is complete. The Method main has an Array Parameter. Notice that in the method signature for main, the parameter that is passed in is in fact an array. Returning an Array. You can return an array from a method in much the same way as you returned any value. Array Type Names. You must specify the type of the array whenever you create it, use it as a parameter or a return type. For-each loops for arrays. This feature is new in Java 5 and can be used to simplify the iteration over the elements in an array. Method with a Variable Number of Parameters. This is another new feature in Java 5, whereby the programmer can specify that the method will take a variable number of parameters that will be stored in an array to be used within the method. Enumerated Type. An enumerated type is one that is defined by the user. The values of the enumerated type can be considered like constants. This is a new feature of Java 5 that is available in many other programming languages to allow the user to create their own types. The Method values. This method is used in conjunction with enumerated types to retrieve an array that contains a list of all the values of the enumerated type. Declaring and Creating a Multidimensional Array. The method for creating a multidimensional array is not much different than a single dimensional array. You must simply tell for each dimension the size. Most common is probably a two dimensional array with what is referred to commonly as rows and columns for the array.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

Tips Use for Loops with Arrays. This tip shows that it is probably easiest to use a for loop with an array. We can use zero as the start and the length of the array as the stop and easily move through all of the indices contained in the array. Accessor Methods Need not Simply Return Instance Variables. Sometimes one does not always need access to an instance variable. In the case of an array instance variable, one might only need access to an element at a particular index of the instance variable array. So, you can create an accessor that allows the user access to that part of the array. Enumerated Types in switch Statements. If you create an enumerated type definition, the values in the enumerated type can actually be used inside a switch statement.

Pitfalls Array Indices Always Start with Zero. This is a stumbling block for many beginning students that want to number the first spot in an array as 1. However, the first space in an array is actually at index zero. Array Index Out of Bounds. One feature of Java is that it does not allow the programmer to access an array index that is outside of the bounds of an array. If a mistake like this is made in the program, the program will throw an ArrayIndexOutOfBoundsException and halt execution. It is then the programmer’s job to go back into the code and find out why the program is trying to access an array index that is not in the bounds of the array. An Array of Characters is not a String. Unlike other languages, a String object is not an array of characters. You can create an array of char’s in Java, but this is not equivalent to a String and one can not be assigned to a variable of the other type. Arrays with a Class Base Type. When an array holds objects with a class type and is initially created, it does not create n instances of the object it holds. Instead, it creates the space needed to hold n of those objects and expects the objects to be created elsewhere and inserted into the array. If you do not create objects for each of the spaces in the array, that space will be empty and trying to access it will throw a NullPointerException. Use of = and == with Arrays. You can assign arrays to variables using the = operator. However, as with objects, you will be assigning a reference. If two references point to the same array, and you change that array, both references will reflect that change. Also, as with objects, == does not test to see if two arrays have the same contents, but rather if the two arrays are stored at the same place in memory. If you need to test for equality of arrays, then you need to write code that explicitly looks at each element in both arrays to see that they are the same.

Examples A Class for Partially Filled Arrays. This class creates a wrapper around an array so that the array that is stored has no gaps or empty array spaces. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

A String Processing Example. This example uses material from the section on methods with a variable number of parameters. Therefore, it is optional and should not be covered unless you have covered the preceding section on that topic. This program provides the ability for the caller to input a sentence and a variable amount of substrings that the caller wants removed from the first string. Sorting an Array. This example uses the partially filled array class that has been written before and Selection sort to sort the elements of the array from smallest to largest. Instructors that do not want to discuss sorting at this point in a course can leave this example out and come back to it at a more appropriate time. A Grade Book Class. This class uses a two-dimensional array to model a gradebook for students. Programming Projects Answers 1. /** * Parcel.java The class Parcel is used to determine the stamping and * handling charges for 5 parcels in a courier company based on their * weight and the destination to which they will be delivered. * * Created: Jan 31, 2016 * * @author * @version 1 */ import java.util.Scanner; public class Parcel { double weight[] = new double[5]; int noOfStamps[] = new int[5]; char locationType[] = new char[5]; double handelingCharges[] = new double[5]; double totalCost[] = new double[5]; double overAllCost; public void inputData() { Scanner keyboard = new Scanner(System.in); for (int i = 0; i < weight.length; i++) { System.out.print("Enter the weight for parcel no " + (i + 1) + " in kg :"); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

weight[i] = keyboard.nextDouble(); System.out.print("Enter the location type " + "(N for National/L for Local :"); locationType[i] = keyboard.next().charAt(0); } } /** * Calculates and prints the number of stamps required and * handling charges applicable for each parcel. */ public void calculate() { for (int i = 0; i < weight.length; i++) { if (weight[i] <= 0.300) noOfStamps[i] = 1; else if (weight[i] > 0.300 && weight[i] < 0.800) noOfStamps[i] = 2; else noOfStamps[i] = 5; if (locationType[i] == 'N' || locationType[i] == 'n') handelingCharges[i] = 40; if (locationType[i] == 'L' || locationType[i] == 'l') handelingCharges[i] = 20; totalCost[i] = handelingCharges[i] + noOfStamps[i] * 2; overAllCost += totalCost[i]; } } /** * Display the details of all the 5 parcels */ public void display() { System.out.println("\nS.No Weight Location Cost"); for (int i = 0; i < weight.length; i++) System.out.println((i + 1) + "\t" + weight[i] + "\t" + locationType[i] + "\t" + totalCost[i]); System.out.println("\n\nOverall cost =" + overAllCost); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

/** * main method */ public static void main(String[] args) { Parcel p1 = new Parcel(); p1.inputData(); p1.calculate(); p1.display(); } } 2. /** * Question2MemoryGame.java * * This program implements a memory matching game. * * It uses a 2D array to store the cards (pairs of numbers 1-8) * and randomly shuffles them through repeated swaps. It uses a * second 2D array to record whether or not a card is face up or * face down. * * Created: Fri Mar 18 2005 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; public class Question2MemoryGame { public static final int LENGTH = 4; public static final int NUM_SWAPS = 10000; private int[][] cards; private boolean[][] faceup;

// Number for each card // If a card is face up or not

/** * Default constructor; Initialize array of cards. * Place pair of numbers in the 2D array and then * randomly shuffle them. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

*/ public Question2MemoryGame() { cards = new int[LENGTH][LENGTH]; // A better design would create a class faceup = new boolean[LENGTH][LENGTH]; // encapsulating both cards and faceup // Initialize faceup boolean array for (int y=0; y<LENGTH; y++) for (int x=0; x<LENGTH;x++) { faceup[x][y]=false; } int x1,y1,x2,y2; int temp; // Place pairs in known locations cards[0][0]=1; cards[0][1]=1; cards[0][2]=2; cards[0][3]=2; cards[1][0]=3; cards[1][1]=3; cards[1][2]=4; cards[1][3]=4; cards[2][0]=5; cards[2][1]=5; cards[2][2]=6; cards[2][3]=6; cards[3][0]=7; cards[3][1]=7; cards[3][2]=8; cards[3][3]=8; // Randomly swap pairs 10000 times to shuffle for (int i=0; i<NUM_SWAPS; i++) { x1 = (int) (Math.random() * LENGTH); y1 = (int) (Math.random() * LENGTH); x2 = (int) (Math.random() * LENGTH); y2 = (int) (Math.random() * LENGTH); temp = cards[x1][y1]; cards[x1][y1]=cards[x2][y2]; cards[x2][y2] = temp; } } /** * ShowCards * Generates a display on the screen. If faceup=false, * an * is output, otherwise the card in that slot is output. */ public void ShowCards() { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

int x,y; System.out.println(" 1 2 3 4"); System.out.println(" ========="); for (y=0; y < LENGTH; y++) { System.out.print(y+1 + " | "); for (x=0; x< LENGTH; x++) { if (faceup[x][y]) { System.out.print(cards[x][y] + " "); } else { System.out.print("* "); } } System.out.println("|"); } System.out.println(" ========="); } /** * Checks to see if two cards match. * * @param x1 x coordinate of card 1 * @param y1 y coordinate of card 1 * @param x2 x coordinate of card 2 * @param y2 y coordinate of card 2 * * @return boolean true if the cards match, false if they do not. */ public boolean CheckMatch(int x1, int y1, int x2, int y2) { Scanner scan = new Scanner(System.in); int temp; String s; // Check if we found a match if (cards[x1][y1]==cards[x2][y2]) { System.out.println("Match found!"); faceup[x1][y1]=true; faceup[x2][y2]=true; return true; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

} else { // No match, but temporarily show the cards faceup[x1][y1]=true; faceup[x2][y2]=true; ShowCards(); System.out.println("Hit enter to continue."); s = scan.nextLine(); // Hide the revealed board by scrolling it off faceup[x1][y1]=false; faceup[x2][y2]=false; for (temp=0; temp<30; temp++) { System.out.println(); } } return false; }

/** * main method */ public static void main(String[] args) { // Variable declarations Question2MemoryGame game = new Question2MemoryGame(); int temp; int x1,y1,x2,y2; int pairsleft = 8; Scanner scan = new Scanner(System.in); System.out.println("Find all the matching pairs on the board."); // Main loop, show the board while (pairsleft > 0) { game.ShowCards(); System.out.println("Enter an x and y position of the first card to flip."); x1 = scan.nextInt(); y1 = scan.nextInt(); System.out.println("Enter an x and y position of the second card to flip."); x2 = scan.nextInt(); y2 = scan.nextInt(); // Subtract one from the input, since our arrays start at 0 Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

// but the board displays start at 1 x1--; y1--; x2--; y2--; if (game.CheckMatch(x1,y1,x2,y2)) pairsleft--; } System.out.println("You found all the matching pairs! Game over."); game.ShowCards(); } } // Question2MemoryGame

3. /** * AverageSalary.java * * The program reads the salary of an employee for all the months in * a calendar year and computes the deviation from the average salary * for each month and prints the output in a nicely formatted table. * * Created: Jan 31, 2016 * * @author * @version 1 */ import java.util.Scanner; public class AverageSalary { public static void main(String[] args) { Employee emp = new Employee(); emp.inputData(); emp.printDeviation(); } } /** * Employee class that stores salary of the employee for 12 * months and average salary */ class Employee { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

double monthlySalary[] = new double[12]; double averageSalary; String months[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; //read salary for each calendar month public void inputData() { double totalSalary = 0; Scanner keyboard = new Scanner(System.in); for (int i = 0; i < monthlySalary.length; i++) { System.out.print("Enter the salary of " + months[i] + " : "); monthlySalary[i] = keyboard.nextDouble(); totalSalary += monthlySalary[i]; } averageSalary = totalSalary / 12; } //print the deviation of every month's salary from average salary public void printDeviation() { System.out.println("Month Name Salary Deviation from average"); for (int i = 0; i < monthlySalary.length; i++) { System.out.printf("%-15s", months[i]); System.out.printf("%8.2f", monthlySalary[i]); System.out.printf("%8.2f\n",(monthlySalary[i]- averageSalary)); } } } 4. /** * ArrayDeleteElement.java * * Class that contains a static method to remove negative elements in * the partial array that is passed as an argument and shifts the next * element to the newly available position after removing the negative * element. * * Created: Feb 1, 2016 * * @author Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

* @version 1 */ public class ArrayDeleteElement { //static method to remove negative elements from the array public static int removeElements(int arr[], int len) { for (int i = 0; i < len; i++) { if (arr[i] < 0) { for (int j = i; j < len - 1; j++) arr[j] = arr[j + 1]; len--; } } for (int i = len; i < arr.length; i++) arr[i] = 1101; return (len); } public static void main(String[] args) { int arrNum[] = new int[8]; arrNum[0] = 10; arrNum[1] = -15; arrNum[2] = 25; arrNum[3] = 30; arrNum[4] = -25; arrNum[5] = 25; arrNum[6] = 30; arrNum[7] = -25; int length = 8; System.out.println("\nExisting Array Elements :"); for (int i = 0; i < arrNum.length; i++) System.out.print(arrNum[i] + ","); length = ArrayDeleteElement.removeElements(arrNum, length); System.out.println("\nArray Elements after removing " + "negative elements:"); for (int i = 0; i < arrNum.length; i++) System.out.print(arrNum[i] + ","); } } 5. /** * Counter.java * * This program defines a class that can be used to read two integer Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

* arrays and merge them in a two-dimensional array with the count of * each distinct element from the two input arrays. * * Created: Feb 1, 2016 * * @author * @version 1 */ import java.util.Scanner; public class Counter { int firstArray[] = new int[5]; int secondArray[] = new int[5]; int countData[][] = new int[10][2]; public void intputData() { Scanner keyboard = new Scanner(System.in); System.out.println("Input " + firstArray.length + " elemets of First Array"); for (int i = 0; i < firstArray.length; i++) { firstArray[i] = keyboard.nextInt(); } System.out.println("Input " + secondArray.length + " elemets of Second Array"); for (int i = 0; i < secondArray.length; i++) { secondArray[i] = keyboard.nextInt(); } } /** * This method merges the elements from both the input arrays in a * way that the first column in the resultant two dimensional * array contains the distinct elements and the second column * contains the count of each element's occurrences. */ public void count() { int i, j, k = 0; boolean found = false; for (i = 0; i < firstArray.length; i++) { found = false; for (j = 0; j < k; j++) { if (firstArray[i] == countData[j][0]) { countData[j][1]++; found = true; } } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

if (!found) { countData[k][0] = firstArray[i]; countData[k][1]++; k++; } } for (i = 0; i < secondArray.length; i++) { found = false; for (j = 0; j < k; j++) { if (secondArray[i] == countData[j][0]) { countData[j][1]++; found = true; } } if (!found) { countData[k][0] = secondArray[i]; countData[k][1]++; k++; } } System.out.println("\n Element Count"); for (i = 0; i < k; i++) { System.out.println(countData[i][0] + "\t" + countData[i][1]); } } public static void main(String args[]) { Counter c1 = new Counter(); c1.intputData(); c1.count(); } } 6. /** * Question6.java * * Created: Fri Jan 09 20:06:18 2004 * Modified: Fri Mar 18 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

import java.util.Scanner; public class Question6 { private static int[][] _numbers = new int[50][2]; private static int _position = 0; public static void insertIntoArray(int num) { boolean found = false; for ( int i = 0; i < _position; i++ ) { if ( _numbers[i][0] == num ) { _numbers[i][1]++; found = true; } // end of if () } // end of for () if ( !found ) { _numbers[_position][0] = num; _numbers[_position][1] = 1; _position++; } // end of if () } /** * Adapted from Display 6.11 of the textbook */ public static void selectionSort() { int index, indexOfNextSmallest; for (index = 0; index < _position -1; index++) { indexOfNextSmallest = indexOfSmallest(index); int temp = _numbers[index][0]; _numbers[index][0] = _numbers[indexOfNextSmallest][0]; _numbers[indexOfNextSmallest][0] = temp; temp = _numbers[index][1]; _numbers[index][1] = _numbers[indexOfNextSmallest][1]; _numbers[indexOfNextSmallest][1] = temp; } } private static int indexOfSmallest(int start) { int min=_numbers[start][0]; int indexOfMin = start; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

int index; for (index=start+1; index<_position; index++) { if (_numbers[index][0]<min) { min=_numbers[index][0]; indexOfMin = index; } } return indexOfMin; } public static void printOutput() { selectionSort(); System.out.println("N\t\tCount"); for ( int i = _position - 1; i >= 0; i-- ) { System.out.println(_numbers[i][0] + "\t\t" + _numbers[i][1]); } // end of for () } public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("How many numbers to enter? (At most 50)"); int numToEnter = keyboard.nextInt(); System.out.println("Enter each of the " + numToEnter + " numbers."); for ( int i = 0; i < numToEnter; i++) { int num = keyboard.nextInt(); insertIntoArray(num); } // end of for () printOutput(); } } // Question6 7. /** * ArrayNumber.java * * * Created: Wed Jan 14 20:56:39 2004 * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

* @author Adrienne Decker * @version */ public class ArrayNumber { private int[] _digits; private int _positionOfFirstDigit; private int _max; public ArrayNumber (String num, int max) { _max = max; _digits = new int[_max]; if ( num.length() > max ) { System.err.println("Number too long. Integer overflow."); System.exit(1); } // end of if () _positionOfFirstDigit = num.length() - 1; int pos = num.length() - 1; for ( int i = 0; i < num.length(); i++ ) { boolean validDigit = this.checkDigit(num.charAt(pos)); if ( !validDigit ) { System.err.println("Not a valid number."); System.exit(1); } // end of if () else { int digit = Integer.parseInt("" + num.charAt(pos)); _digits[i] = digit; pos--; } } // end of for () } public int getNumberAtPosition( int index ) { return _digits[index]; } public int getPositionOfFirstDigit() { return _positionOfFirstDigit; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

} public void putNumAtPos(int num, int pos) { _digits[pos] = num; } public void setPositionOfFirstDigit(int pos) { _positionOfFirstDigit = pos; } public ArrayNumber add(ArrayNumber other) { ArrayNumber result = new ArrayNumber("0", _max); result.setPositionOfFirstDigit(-1); for ( int i = 0; i < _max; i++) { int sum = _digits[i] + other.getNumberAtPosition(i); if ( sum <= 9) { result.putNumAtPos(sum, i); result.setPositionOfFirstDigit (result.getPositionOfFirstDigit() + 1); } // end of if () else { result.putNumAtPos(sum % 10, i); result.setPositionOfFirstDigit (result.getPositionOfFirstDigit() + 1); int nextNum = this.getNumberAtPosition(i + 1); nextNum++; this.putNumAtPos( nextNum, i + 1); } // end of else } // end of for () result.removeLeadingZeros(); result.checkFirstDigit(); return result; } public String toString() { String result = ""; for ( int i = _positionOfFirstDigit; i >= 0; i-- ) { result += _digits[i]; } // end of for () Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

return result; } private boolean checkDigit(char digit) { return (digit == '0' || digit == '1' || digit == '2' || digit == '3' || digit == '4' || digit == '5' || digit == '6' || digit == '7' || digit == '8' || digit == '9'); } private void removeLeadingZeros() { for ( int i = _max - 1; i >= 0; i--) { int check = _digits[i]; if ( check == 0 ) { _positionOfFirstDigit--; } // end of if () else { break; } // end of else } // end of for () } private void checkFirstDigit() { int num = _digits[_positionOfFirstDigit]; if ( num > 9 ) { _digits[_positionOfFirstDigit] = num % 10; _positionOfFirstDigit++; num = num / 10; _digits[_positionOfFirstDigit] = num; } // end of if () }

}// ArrayNumber /** * Question7.java * * Created: Fri Jan 09 20:06:23 2004 * Modified: Fri Mar 18 2005, Kenrick Mock * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

* @author Adrienne Decker * @version 2 */ import java.util.Scanner; public class Question7 { public static final int MAX_LENGTH = 20; public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); while ( true ) { System.out.println("Enter first number to add " + "(max length " + MAX_LENGTH + " digits):"); String number = keyboard.nextLine(); ArrayNumber first = new ArrayNumber(number, MAX_LENGTH); System.out.println("Enter second number to add " + "(max length " + MAX_LENGTH + " digits): "); number = keyboard.nextLine(); ArrayNumber second = new ArrayNumber(number, MAX_LENGTH); System.out.println("Sum is: " + first.add(second)); System.out.println("Enter 'Q' to quit, any other key to continue."); String s = keyboard.nextLine(); if ( s.charAt(0) == 'Q' || s.charAt(0) == 'q' ) { break; } // end of if () } } } // Question7

8. public class BubbleSort { /**Based on SelectionSort given in Chapter 6 **/ /** Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

Precondition: numberUsed <= a.length; The first numberUsed indexed variables have values. Action: Sorts a so that a[0] <= a[1] <= ... <= a[numberUsed - 1]. */ public static void sort(int[] a, int numberUsed) { int index; for ( int i = 0; i < numberUsed; i++ ) { for ( index = 0; index < a.length - 1; index++ ) { if ( a[index] > a[index + 1]) { interchange(index, index + 1, a); } // end of if () } // end of for () } // end of for () } /** Precondition: i and j are legal indices for the array a. Postcondition: Values of a[i] and a[j] have been interchanged. */ private static void interchange(int i, int j, int[] a) { int temp1; temp1 = a[i]; a[i] = a[j]; a[j] = temp1; } } // BubbleSort /** * Question8.java * * * Created: Fri Jan 09 20:06:28 2004 * * @author Adrienne Decker * @version */ public class Question8 { public static void printOutArray(int[] array) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

for ( int i = 0; i < array.length; i++) { System.out.println(array[i]); } // end of for () } public static void main(String[] args) { int[] array = {3,4,5,6}; BubbleSort.sort(array, array.length); printOutArray(array); int[] array2 = {6,5,4,3}; BubbleSort.sort(array2, array2.length); printOutArray(array2); int[] array3 = {3,5,4,7,5,6}; BubbleSort.sort(array3, array3.length); printOutArray(array3); } } // Question8

9. /** Class for a partially filled array of doubles. The class enforces the following invariant: All elements are at the beginning of the array in locations 0, 1, 2, and so forth up to a highest index with no gaps. */ public class PartiallyFilledArray { private int maxNumberElements; //Same as a.length private double[] a; private int numberUsed; //Number of indices currently in use /** Sets the maximum number of allowable elements to 10. */ PartiallyFilledArray( ) { maxNumberElements = 10; a = new double[maxNumberElements]; numberUsed = 0; } /** Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

Precondition arraySize > 0. */ PartiallyFilledArray(int arraySize) { if (arraySize <= 0) { System.out.println("Error Array size zero or negative."); System.exit(0); } maxNumberElements = arraySize; a = new double[maxNumberElements]; numberUsed = 0; }

PartiallyFilledArray(PartiallyFilledArray original) { if (original == null) { System.out.println("Fatal Error: aborting program."); System.exit(0); } maxNumberElements = original.maxNumberElements; numberUsed = original.numberUsed; a = new double[maxNumberElements]; for (int i = 0; i < numberUsed; i++) a[i] = original.a[i]; } /** Adds newElement to the first unused array position. */ public void add(double newElement) { if (numberUsed >= a.length) { this.resize(); } a[numberUsed] = newElement; numberUsed++; }

public void resize() { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

int size = a.length; size *= 2; double[] newA = new double[size]; maxNumberElements = size; for ( int i = 0; i < a.length; i++ ) { newA[i] = a[i]; } // end of for () a = newA; } public double getElement(int index) { if (index < 0 || index >= numberUsed) { System.out.println("Error:Illegal or unused index."); System.exit(0); } return a[index]; } /** index must be an index in use or the first unused index. */ public void resetElement(int index, double newValue) { if (index < 0 || index >= maxNumberElements) { System.out.println("Error:Illegal index."); System.exit(0); } else if (index > numberUsed) { System.out.println( "Error: Changing an index that is too large."); System.exit(0); } else a[index] = newValue; } public void deleteLast( ) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

if (empty( )) { System.out.println("Error:Deleting from an empty array."); System.exit(0); } else numberUsed--; } /** Deletes the element in position index. Moves down all elements with indices higher than the deleted element. */ public void delete(int index) { if (index < 0 || index >= numberUsed) { System.out.println("Error:Illegal or unused index."); System.exit(0); } for (int i = index; i < numberUsed; i++) a[i] = a[i + 1]; numberUsed--; } public boolean empty( ) { return (numberUsed == 0); } public boolean full( ) { return (numberUsed == maxNumberElements); } public int getMaxCapacity( ) { return maxNumberElements; } public int getNumberOfElements( ) { return numberUsed; } } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

/** * Question9.java * * * Created: Fri Jan 09 20:06:35 2004 * * @author Adrienne Decker * @version */ public class Question9 { public static void main(String[] args) { System.out.println("Creating an array with ten elements."); PartiallyFilledArray pfa = new PartiallyFilledArray(); for ( int i = 0; i < 10; i++ ) { pfa.add(3.56); } // end of for () System.out.println("Max Cap: " + pfa.getMaxCapacity()); System.out.println("Number used: " + pfa.getNumberOfElements()); for ( int i = 0; i < pfa.getNumberOfElements(); i++ ) { System.out.print(pfa.getElement(i) + " "); } // end of for () System.out.println(); System.out.println("Let's insert one more number."); pfa.add(4.5); System.out.println("Max Cap: " + pfa.getMaxCapacity()); System.out.println("Number used: " + pfa.getNumberOfElements()); for ( int i = 0; i < pfa.getNumberOfElements(); i++ ) { System.out.print(pfa.getElement(i) + " "); } // end of for () System.out.println();

} } // Question9

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

10. /** * Game.java * * The program lets the user play a simple game of grid using two * dimensional arrays. In a grid of NxN elements marked with symbol * '*', user's initial position is randomly picked and showed using * the symbol '$'. * The user then picks the movement direction and the * program replaces the user's previous position with '$' symbol and * new position is marked as 'N' * * Created: Feb 1, 2016 * * @author * @version 1 */ import java.util.Scanner; import java.util.Random; public class Game { public static void main(String[] args) { char[][] gridArray = new char[3][3]; int randomRow; int randomCol; String moveSelect; boolean validInput = true; int min = 0; int max = 2; /* * Generates random number to place the initial position of * the user in the grid */ Random tRNG = new Random(); randomRow = tRNG.nextInt(max - min + 1) + min; randomCol = tRNG.nextInt(max - min + 1) + min; gridArray[randomRow][randomCol] = '$';

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

for (int i = 0; i < gridArray.length; i++) { for (int j = 0; j < gridArray.length; j++) { if (gridArray[i][j] != gridArray[randomRow][randomCol]) { gridArray[i][j] = '*'; } System.out.print(gridArray[i][j]); } System.out.println(""); } do { System.out.println("Enter choice U-Up " + "L-Left D-Down or R-Right E-Exit"); Scanner keyboard = new Scanner(System.in); moveSelect = keyboard.nextLine(); if (moveSelect.equals("D") || moveSelect.equals("d")) { if (randomRow + 1 > max) System.out.println("Invalid Entry. Try again."); else { gridArray[randomRow + 1][randomCol] = 'N'; gridArray[randomRow][randomCol] = '$'; validInput = true; } } else if (moveSelect.equals("L") || moveSelect.equals("l")) { if (randomCol - 1 < min) System.out.println("Invalid Entry. Try again."); else { gridArray[randomRow][randomCol - 1] = 'N'; gridArray[randomRow][randomCol] = '$'; validInput = true; } } else if (moveSelect.equals("U") || moveSelect.equals("u")) { if (randomRow - 1 < min) System.out.println("Invalid Entry. Try again."); else { gridArray[randomRow - 1][randomCol] = 'N'; gridArray[randomRow][randomCol] = '$'; validInput = true; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

} else if (moveSelect.equals("R") || moveSelect.equals("r")) { if (randomCol + 1 > max) System.out.println("Invalid Entry. Try again."); else { gridArray[randomRow][randomCol + 1] = 'N'; gridArray[randomRow][randomCol] = '$'; validInput = true; } } else if (moveSelect.equals("E") || moveSelect.equals("e")) { validInput = false; } else { System.out.println("Invalid Entry. Try again."); } for (int i = 0; i < gridArray.length; i++) { for (int j = 0; j < gridArray.length; j++) { System.out.print(gridArray[i][j]); } System.out.println(""); } } while (validInput == true); } } 11. /** * SeatingAssignment.java * * * Created: Thu Jan 15 21:39:55 2004 * * @author Adrienne Decker * @version */ public class SeatingAssignment { private char[][] _seats; private int _seatsLeft; public SeatingAssignment () { _seats = new char[7][5]; _seatsLeft = 28; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

_seats[0][0] = '1'; _seats[1][0] = '2'; _seats[2][0] = '3'; _seats[3][0] = '4'; _seats[4][0] = '5'; _seats[5][0] = '6'; _seats[6][0] = '7';

for (int i = 0; i < _seats.length; i++ ) { for ( int j = 1; j < _seats[0].length; j++ ) { if ( j == 1 ) { _seats[i][j] = 'A'; } // end of if () if ( j == 2 ) { _seats[i][j] = 'B'; } // end of if () if ( j == 3 ) { _seats[i][j] = 'C'; } // end of if () if ( j == 4 ) { _seats[i][j] = 'D'; } // end of if () } // end of for () } // end of for () } public boolean assignSeat(String seat) { if ( _seatsLeft == 0 ) { return false; } // end of if () char row = seat.charAt(0); boolean validRow = this.checkRow(row); char letter = seat.charAt(1); boolean validSeat = this.checkSeat(letter); if ( !validRow || !validSeat ) { System.err.println("Invalid seat location."); System.exit(1); } // end of if () for ( int i = 0; i < _seats.length; i++ ) { if ( row == _seats[i][0] ) { for ( int j = 0; j < _seats[i].length; j++ ) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

if ( letter == _seats[i][j] ) { _seats[i][j] = 'X'; _seatsLeft--; return true; } // end of if () } // end of for () } // end of if () } // end of for () System.out.println("Seat already assigned."); return true; } public String toString() { String result = ""; for ( int i = 0; i < _seats.length; i++ ) { for ( int j = 0; j < _seats[0].length; j++ ) { if ( (j > 0 && j < 2) || (j > 2) ) { result += _seats[i][j]; } // end of if () else if ( j == 2 ) { result += _seats[i][j] + " "; } // end of else if () else { result += _seats[i][j] + " "; } // end of else } // end of for () result += "\n"; } // end of for () return result; } private boolean checkRow(char row) { return (row == '1' || row == '2' || row == '3' || row =='4' || row == '5' || row == '6' || row == '7'); } private boolean checkSeat(char seat) { return (seat == 'A' || seat == 'B' || seat == 'C' || seat == 'D'); } }// SeatingAssignment Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

/** * Question11.java * * Created: Fri Jan 09 20:06:45 2004 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ import java.util.Scanner; public class Question11 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); SeatingAssignment sa = new SeatingAssignment(); System.out.println("You will be selecting seats for this airplane."); System.out.println(sa); System.out.println("You will input the seat selection using " + "the row number and then the seat letter " + "(ex - 3B)"); while ( true ) { System.out.println("Please enter the seat number or Q to quit."); String input = keyboard.nextLine(); if (input.charAt(0) == 'Q' || input.charAt(0) == 'q'){ break; } boolean seatAssigned = sa.assignSeat(input); if ( !seatAssigned ) { System.out.println("All seats assigned."); break; } // end of if () System.out.println(sa); } // end of while () } } // Question11 Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

12. /** * Question 12 * * Trivia game with 5 hard-coded questions. Uses three arrays, * one for the question, one for the answer, and one for * the point value. * * Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; public class TriviaGame { private String[] questions, answers; // Q's and A's private int[] values; // Point value private int score = 0; // Overall score private int questionNum = 0; // Track if question 0 - 4 private static int NUMQUESTIONS = 5; public TriviaGame() // Constructor { questions = new String[NUMQUESTIONS]; answers = new String[NUMQUESTIONS]; values = new int[NUMQUESTIONS]; // Manually copy in questions, answers, and values questions[0] = "The first Pokemon that Ash receives from Professor Oak"; answers[0] = "pikachu"; values[0] = 1; questions[1] = "Erling Kagge skiied into here alone on January 7, 1993"; answers[1] = "south pole"; values[1] = 2; questions[2] = "1997 British band that produced 'Tub Thumper'"; answers[2] = "chumbawumba"; values[2] = 2; questions[3] = "Who is the tallest person on record (8 ft. 11 in) that has lived?"; answers[3] = "Robert Wadlow"; values[3] = 3; questions[4] = "PT Barnum said 'This way to the _______' to attract people to the exit."; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

answers[4] = "egress"; values[4] = 1; } // Returns false if there are no more questions to ask. // Otherwise it asks the next question, gets an answer // from the user, and displays if the user was correct or not. public boolean askNextQuestion() { if (questionNum >= questions.length) { return false; } // Show the current question System.out.println(); System.out.println("Question " + (questionNum + 1)); System.out.println(questions[questionNum]); Scanner kbd = new Scanner(System.in); String guess = kbd.nextLine(); // Check if the answer is correct or not guess = guess.toLowerCase(); String answer = answers[questionNum].toLowerCase(); if (guess.equals(answer)) { System.out.println("That is correct!"); score += values[questionNum]; } else { System.out.println("Wrong. The correct answer is " + answers[questionNum]); } // Go to next question questionNum++; return true; } // Displays current score public void showScore() { System.out.println("Your score is " + score); }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

// Main method public static void main(String[] args) { TriviaGame game = new TriviaGame(); while (game.askNextQuestion()) { game.showScore(); } System.out.println("Game over! Thanks for playing!"); } } // Question 12

13. /** * Question 13 * * Trivia game with 5 hard-coded questions. Uses a single array * of trivia objects. * * Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; public class TriviaGame { private Trivia[] trivia; private int score = 0; // Overall score private int questionNum = 0; // Track if question 0 - 4 private static int NUMQUESTIONS = 5; public TriviaGame() // Constructor { trivia = new Trivia[NUMQUESTIONS]; // Manually copy in questions, answers, and values // Note that we need to use NEW to create the instance of each // object to store in the array trivia[0] = new Trivia("The first Pokemon that Ash receives from Professor Oak", Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

"pikachu",1); trivia[1] = new Trivia("Erling Kagge skiied into here alone on January 7, 1993", "south pole", 2); trivia[2] = new Trivia("1997 British band that produced 'Tub Thumper'", "chumbawumba", 2); trivia[3] = new Trivia("Who is the tallest person on record (8 ft. 11 in) that has lived?", "Robert Wadlow", 3); trivia[4] = new Trivia("PT Barnum said 'This way to the _______' to attract people to the exit.", "egress", 1); } // Returns false if there are no more questions to ask. // Otherwise it asks the next question, gets an answer // from the user, and displays if the user was correct or not. public boolean askNextQuestion() { if (questionNum >= trivia.length) { return false; } // Show the current question System.out.println(); System.out.println("Question " + (questionNum + 1)); System.out.println(trivia[questionNum].getQuestion()); Scanner kbd = new Scanner(System.in); String guess = kbd.nextLine(); // Check if the answer is correct or not guess = guess.toLowerCase(); String answer = trivia[questionNum].getAnswer().toLowerCase(); if (guess.equals(answer)) { System.out.println("That is correct!"); score += trivia[questionNum].getValue(); } else { System.out.println("Wrong. The correct answer is " + trivia[questionNum].getAnswer()); } // Go to next question questionNum++; return true; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

} // Displays current score public void showScore() { System.out.println("Your score is " + score); }

// Main method public static void main(String[] args) { TriviaGame game = new TriviaGame(); while (game.askNextQuestion()) { game.showScore(); } System.out.println("Game over! Thanks for playing!"); } }

public class Trivia { private String question; private String answer; private int value; // Default constructor public Trivia() { question = ""; answer = ""; value = 0; } // Constructor to set the question, answer, and value public Trivia(String question, String answer, int value) { this.question = question; this.answer = answer; this.value = value; }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

// Accessor methods to retrieve the question, answer, value public String getQuestion() { return question; } public String getAnswer() { return answer; } public int getValue() { return value; } } // Question 13

14. /** * Question 14 * * Implementation of a randomized challenge-response system. * In these systems the user enters different information every * time based on a secret in response to a randomly generated * challenge. * * Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; public class Question14 { public static void main(String[] args) { // Actual password is 99508 int[] actual_password = {9, 9, 5, 0, 8}; // Array to hold randomly generated digits int[] random_nums = new int[10]; // Array to hold the digits entered by the user to authenticate int[] entered_digits = new int[actual_password.length]; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

// Randomly generate numbers from 1-3 for // for each digit for (int i=0; i < 10; i++) { random_nums[i] = (int) (Math.random() * 3) + 1; } // Output the challenge System.out.println("Welcome! To log in, enter the random digits from 1-3 that"); System.out.println("correspond to your PIN number."); System.out.println(); System.out.println("PIN digit: 0 1 2 3 4 5 6 7 8 9"); System.out.print("Random #: "); for (int i=0; i<10; i++) { System.out.print(random_nums[i] + " "); } System.out.println(); System.out.println(); // Input the user's entry Scanner keyboard = new Scanner(System.in); System.out.println("Enter code."); String s = keyboard.next(); // Extract the digits from the code and store in the entered_digits array for (int i=0; i<s.length(); i++) { // Convert char to corresponding digit entered_digits[i] = s.charAt(i) - '0'; } // At this point, if the user typed 12443 then // entered_digits[0] = 1, entered_digits[1] = 2, // entered_digits[2] = 4, // entered_digits[3] = 4, and entered_digits[4] = 3 /**** TO DO: fill in the parenthesis for the if statement so the isValid method is invoked, sending in the arrays actual_password, entered_digits, and random_nums as parameters ***/ if (isValid(actual_password, entered_digits, random_nums)) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

System.out.println("Correct! You may now proceed."); } else { System.out.println("Error, invalid password entered."); } } /**** This method returns true if a valid password response is entered, and false otherwise. For example, if: actual = {9,9,5,0,8} randnums = {1,2,3,1,2,3,1,2,3,1} then this returns true if: entered[0] == 1 (actual[0] = 9 -> randnums[9] -> 1) entered[1] == 1 (actual[1] = 9 -> randnums[9] -> 1) entered[2] == 3 (actual[2] = 5 -> randnums[5] -> 3) entered[3] == 1 (actual[3] = 0 -> randnums[0] -> 1) entered[4] == 3 (actual[4] = 8 -> randnums[8] -> 3) or in other words, the method should return false if any of the above are not equal. ****/ public static boolean isValid(int[] actual, int[] entered, int[] randnums) { for (int i = 0; i < entered.length; i++) { if (entered[i] != randnums[actual[i]]) return false; } return true; } } // Question 14

15. /** * Question 15 * * Modification to the PizzaOrder class. Uses an * array to store an arbitrary number of Pizza items. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

* Requires the Pizza class from PP 4.12. * * Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ public class PizzaOrder { private Pizza[] pizzas; public PizzaOrder() { pizzas = null; } public void setNumPizzas(int numPizzas) { // Allocate the array so it is large enough // to hold numPizzas pizzas = new Pizza[numPizzas]; } public void setPizza(int index, Pizza pizza) { if (pizzas != null && index >=0 && index < pizzas.length) { pizzas[index] = pizza; } } public double calcTotal() { double total = 0; if (pizzas != null) { for (int i = 0; i < pizzas.length; i++) { total += pizzas[i].calcCost(); } } return total; }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

// Sample main public static void main(String[] args) { Pizza pizza1 = new Pizza("Large",1,1,0); Pizza pizza2 = new Pizza("Medium",2,0,2); PizzaOrder order = new PizzaOrder(); order.setNumPizzas(2); // 2 pizzas in the order order.setPizza(0,pizza1); // Set first pizza order.setPizza(1,pizza2); // Set second pizza double total = order.calcTotal(); // Should be 18+20 = 38 System.out.println("The order total is " + total); } } // Question 15

Question 16: No solution provided Question 17: No solution provided Question 18: File: produce.txt Broccoli Tomato Kiwi Kale Tomatillo /** * Question 18 * * Box of Produce class. Array to remove limitation of a box of 3 items. * * Created: Fri Apr 27 2012 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Random; public class BoxOfProduce { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

// Max number of items in a box public static final int MAX_BUNDLES = 100; private int numBundles; private String[] bundle; public BoxOfProduce() { numBundles = 0; bundle = new String[MAX_BUNDLES]; } public BoxOfProduce(String b1, String b2, String b3) { numBundles = 3; bundle = new String[MAX_BUNDLES]; bundle[0] = b1; bundle[1] = b2; bundle[2] = b3; } public void addBundle(String b) { if (numBundles < MAX_BUNDLES) { bundle[numBundles] = b; numBundles++; } } public String getBundle(int index) { if ((index >=0) && (index < MAX_BUNDLES)) return bundle[index]; else return ""; } public void setBundle(String b, int index) { if ((index >=0) && (index < MAX_BUNDLES)) bundle[index] = b; } public String toString() { String s = "The box contains: "; for (int i = 0; i < numBundles; i++) s = s + ", (" + (i+1) + ")" + bundle[i]; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

return s; } public static void main(String[] args) { // Create a Box BoxOfProduce box = new BoxOfProduce(); // Pick three random numbers from 0 to 4 for the 5 possible food choices Random rnd = new Random(); int num1, num2, num3; num1 = rnd.nextInt(5); num2 = rnd.nextInt(5); num3 = rnd.nextInt(5); int lineRead = 0; Scanner fileIn = null; // Initializes fileIn to an empty object try { // Attempt to open the file fileIn = new Scanner( new FileInputStream("produce.txt")); } catch (FileNotFoundException e) { // If the file could not be found, this code is executed // and then the program exits System.out.println("File not found."); System.exit(0); } // Read from the file and if the line read in matches one of the // random numbers then set the corresponding bundle while (fileIn.hasNext()) { String food = fileIn.next(); if (lineRead == num1) box.addBundle(food); if (lineRead == num2) box.addBundle(food); if (lineRead == num3) box.addBundle(food); lineRead++; } fileIn.close();

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

// Show the box contents to the user and allow substitutions Scanner kbd = new Scanner(System.in); String selection = ""; do { System.out.println(box.toString()); System.out.println("Enter 'a' to add a new bundle."); System.out.println("Enter 'c' to change a bundle."); System.out.println("Enter 'q' to quit."); selection = kbd.next(); kbd.nextLine(); if (selection.equals("a")) { System.out.println("Enter item to add."); String item = kbd.nextLine(); box.addBundle(item); } else if (selection.equals("c")) { System.out.println("Enter index of item to change."); int i = kbd.nextInt(); kbd.nextLine(); System.out.println("Enter item to substitute."); String item = kbd.nextLine(); box.setBundle(item, i-1); // Index is 0 based so subtract 1 } } while (!selection.equals("q")); System.out.println("Final Contents:"); System.out.println(box.toString()); } } // Question 18 /** * Question19.java * * Find the words made from letters of another word * * Created: Fri Apr 27 2012 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; import java.io.FileInputStream; import java.io.FileNotFoundException;

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

class Question19 { // Return a histogram of letters from the string private static int[] histogram(String s) { s = s.toLowerCase(); int[] histogram = new int[26]; for (int i = 0; i < 26; i++) histogram[i] = 0; for (int i = 0; i < s.length(); i++) { int v = s.charAt(i) - 'a'; if ((v>=0) && (v<=25)) histogram[v]++; } return histogram; } // Returns true if histo1 is contained within histo2 private static boolean histoMatch(int histo1[], int histo2[]) { for (int i = 0; i < 26; i++) { if (histo1[i] > histo2[i]) return false; } return true; } public static void main(String[] args) { Scanner kbd = new Scanner(System.in); System.out.println("Enter a word."); String word = kbd.next(); int[] histoWord = histogram(word); Scanner fileIn = null; // Initializes fileIn to an empty object try { // Attempt to open the file fileIn = new Scanner( new FileInputStream("words.txt")); } catch (FileNotFoundException e) { // If the file could not be found, this code is executed Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

// and then the program exits System.out.println("File not found."); System.exit(0); }

while (fileIn.hasNext()) { String target = fileIn.next(); int[] histoTarget = histogram(target); if (histoMatch(histoTarget, histoWord)) System.out.println(target); } fileIn.close(); } } // Question 19

/** * Question20.java * * Top ten players and high scores * * Created: Wed May 20 2015 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; public class Question20 { /** * Arrays to hold player names and their scores */ private String[] names; private int[] scores; private int numPlayers = 0; // Keyboard private Scanner keyboard; /** * Constructor, initialize member variables */ Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

public Question20() { numPlayers = 0; names = new String[10]; scores = new int[10]; keyboard = new Scanner(System.in); } /** * addPlayer * Add a new player if there is room, otherwise output an error message */ public void addPlayer() { if (numPlayers >= 10) System.out.println("No more room, 10 scores already added."); else { System.out.println("Enter name:"); names[numPlayers] = keyboard.nextLine(); System.out.println("Enter score:"); scores[numPlayers] = keyboard.nextInt(); keyboard.nextLine(); // Discard newline numPlayers++; } } /** * printPlayers * Outputs player names and scores to the screen */ public void printPlayers() { System.out.printf("%10s %s","Score","Name\n"); for (int i = 0; i < numPlayers; i++) { System.out.printf("%10d %s\n",scores[i],names[i]); } } /** * lookupPlayer * Outputs player score given a name */ public void lookupPlayer() { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

System.out.println("Enter name to look up."); String target = keyboard.nextLine(); // Search for player name for (int i = 0; i < numPlayers; i++) { if (names[i].equalsIgnoreCase(target)) { System.out.println(target + "'s score = " + scores[i]); return; } } System.out.println("Name not found."); } /** * removePlayer * Removes a player from the array by copying the last name * and score to the index of the position to delete, * then decrement the number of players by one. * * This disrupts the ordering of the players, but in this * case it doesn't matter. */ public void removePlayer() { System.out.println("Enter name to remove."); String target = keyboard.nextLine(); // Search for player name for (int i = 0; i < numPlayers; i++) { if (names[i].equalsIgnoreCase(target)) { // Copy the last player to the index of // the player to remove. names[i] = names[numPlayers-1]; scores[i] = scores[numPlayers-1]; numPlayers--; System.out.println(target + " removed."); return; } } System.out.println("Name not found."); } public static void main(String[] args) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

{ Question20 highScores = new Question20(); String choice = ""; // Main menu do { System.out.println(); System.out.println(); System.out.println("Score Management System"); System.out.println("Choose:"); System.out.println(); System.out.println("A)dd new player"); System.out.println("P)rint all players"); System.out.println("L)ookup a player's score"); System.out.println("R)emove a player"); System.out.println("Q)uit"); System.out.println(); choice = highScores.keyboard.next(); highScores.keyboard.nextLine(); // Discard newline if (choice.equalsIgnoreCase("A")) highScores.addPlayer(); else if (choice.equalsIgnoreCase("P")) highScores.printPlayers(); else if (choice.equalsIgnoreCase("L")) highScores.lookupPlayer(); else if (choice.equalsIgnoreCase("R")) highScores.removePlayer(); System.out.println(); } while (!choice.equalsIgnoreCase("q")); } }

/** * Question21.java * * Top ten players and high scores using the Player class in an array * * Created: Wed May 20 2015 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner;

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

public class Question21 { /** * Single array of type Player to hold player name and score */ private Player[] players; private int numPlayers = 0; // Keyboard private Scanner keyboard; /** * Constructor, initialize member variables */ public Question21() { numPlayers = 0; players = new Player[10]; keyboard = new Scanner(System.in); } /** * addPlayer * Add a new player if there is room, otherwise output an error message */ public void addPlayer() { if (numPlayers >= 10) System.out.println("No more room, 10 scores already added."); else { System.out.println("Enter name:"); String name = keyboard.nextLine(); System.out.println("Enter score:"); int score = keyboard.nextInt(); keyboard.nextLine(); // Discard newline players[numPlayers] = new Player(name,score); numPlayers++; } } /** * printPlayers * Outputs player names and scores to the screen */ public void printPlayers() { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

System.out.printf("%10s %s","Score","Name\n"); for (int i = 0; i < numPlayers; i++) { System.out.printf("%10d %s\n", players[i].getScore(), players[i].getName()); } } /** * lookupPlayer * Outputs player score given a name */ public void lookupPlayer() { System.out.println("Enter name to look up."); String target = keyboard.nextLine(); // Search for player name for (int i = 0; i < numPlayers; i++) { if (players[i].getName().equalsIgnoreCase(target)) { System.out.println(target + "'s score = " + players[i].getScore()); return; } } System.out.println("Name not found."); } /** * removePlayer * Removes a player from the array by copying the last name * and score to the index of the position to delete, * then decrement the number of players by one. * * This disrupts the ordering of the players, but in this * case it doesn't matter. */ public void removePlayer() { System.out.println("Enter name to remove."); String target = keyboard.nextLine(); // Search for player name for (int i = 0; i < numPlayers; i++) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

if (players[i].getName().equalsIgnoreCase(target)) { // Copy the last player to the index of // the player to remove. players[i] = players[numPlayers-1]; numPlayers--; System.out.println(target + " removed."); return; } } System.out.println("Name not found."); } public static void main(String[] args) { Question21 highScores = new Question21(); String choice = ""; // Main menu do { System.out.println(); System.out.println(); System.out.println("Score Management System"); System.out.println("Choose:"); System.out.println(); System.out.println("A)dd new player"); System.out.println("P)rint all players"); System.out.println("L)ookup a player's score"); System.out.println("R)emove a player"); System.out.println("Q)uit"); System.out.println(); choice = highScores.keyboard.next(); highScores.keyboard.nextLine(); // Discard newline if (choice.equalsIgnoreCase("A")) highScores.addPlayer(); else if (choice.equalsIgnoreCase("P")) highScores.printPlayers(); else if (choice.equalsIgnoreCase("L")) highScores.lookupPlayer(); else if (choice.equalsIgnoreCase("R")) highScores.removePlayer(); System.out.println(); } while (!choice.equalsIgnoreCase("q")); } } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 6, Instructor’s Manual

/** * Player.java * * Class to store information about one player's name and score. * * Created: Wed May 20 2015 * * @author Kenrick Mock * @version 1 */ public class Player { private String name; private int score; public Player() { name=""; score=0; } public Player(String newName, int newScore) { name = newName; score = newScore; } public String getName() { return name; } public int getScore() { return score; } public void setName(String newName) { name = newName; } public void setScore(int newScore) { score = newScore; } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

Chapter 7

Inheritance Key Terms derived class base class extends subclass superclass inheritance parent class child class ancestor class descendent class overriding covariant return type super this “is a” relationship subclass and superclass “is a” relationship “has a” relationship composition super relationship Object class toString equals clone instanceOf

Brief Outline 7.1 Inheritance Basics Derived Classes Overriding a Method Definition Changing the Return Type of an Overridden Method Changing the Access Permissions of an Overridden Method The super Constructor The this Constructor 7.2 Encapsulation and Inheritance Protected and Package Access 7.3 Programming with Inheritance Access to a Redefined Base Method The Class Object The Right Way to Define equals Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

Teaching Suggestions This chapter discusses inheritance and how to effectively use inheritance to help us create bigger programs. The basic syntax and rules of inheritance are discussed first. Using the super constructor and method overriding are introduced here as well. The chapter also discusses which entities from a class are inherited and introduces protected and package access to variables and methods. The last section of the chapter talks about the class Object, which all classes inherit from by default in Java as well as the correct way to define the equals method.

Key Points Derived class (subclass). To create a subclass of an already defined class, you use the keyword extends in the class definition to indicate which class is the superclass for the class you are creating. Inherited Members. A subclass has access to all public entities (variables and methods) of the superclass. All static elements are inherited. This elements are then by virtue part of the subclass just as they were part of the superclass. Parent and Child Classes. Another name for the superclass/subclass relationship is parent and child classes. This can also be extended to ancestor/descendent class. Overriding a Method Definition. In a subclass, a method that has been inherited can be redefined. This process of redefining a method in a subclass is called method overriding. As with method overloading, the methods have the same names in both the superclass and subclass, but have the same parameter lists. The method bodies are in fact different in both classes. The final Modifier. The keyword final when introduced in the definition of a method or class indicates that the method or class may not be redefined using inheritance. Therefore, a final method can not be overridden in a sublclass and a final class can not be used as a superclass for any other class. Call to a Base Class Constructor. You can call the superclass’ constructor from the constructor of a subclass if you wish. You simply need to use the keyword super as a call to the superclass’ constructor. This call must be the first call made in the subclass’ constructor or the program will not compile. Call to another Constructor in the Same Class. You can also make calls to other constructors in the same class by using the keyword this as a call to the constructor. It is fairly common to have one constructor call another in a class.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

The protected Modifier. The last of the visibility modifiers is protected. Protected entitites in a class can be accessed from within the class, from within the class’ subclasses, or from any class within the same package. Package Access. If you do not indicate a visibility for an element of a class, it will receive package access whereby any other class in the package will have access to it. Invoking the Old Version of an Overridden Method? You actually can call the old method from the superclass from the overridden method in the subclass. You do this by using the keyword super and the name of the method. This will execute the superclass’ version of the method. You can then add in additional lines of code before/after the call to the superclass’ method. You can only do this from inside the overridden method. The Class Object. In Java, every class that is written that does not explicitly have a superclass defined will automatically have a superclass in Object. Therefore, every class that is written has its own type as well as the type Object associated with it. Tips An Object of a Derived Class has More Than One Type. Once a class is a subclass, its type is the class as well as the subclass. Even more than that, it also has the type of the superclass’ superclasses. This is a relationship commonly referred to as “is a”. We can say that subclass “is a” superclass. However, the reverse is not true. A superclass does not have the type of its subclasses. “is a” Versus “has a”. Using inheritance is an example of an “is a” relationship. However, we can also build classes out of other classes using composition, or a “has a” relationship. In the “has a” relationship, inheritance is not used, but rather one class has an instance variable whose type is that of another class. These two ideas are distinct. Whereas inheritance builds and changes a class by creating a subclass, composition creates a class out of other classes, building up a larger class out of component parts. Static Variables are Inherited. Static variables are not treated any differently during inheritance than non-static variables. getClass versus instanceof. This section is optional. The chapter discusses the real way that equals should be defined and shows the getClass method. There is also an operator in Java that is instanceOf which will return a Boolean indicating if one class is in fact an instance of the other. Using this operator causes a problem as outlined in the Tip section. The better solution for equals is to use the getClass method.

Pitfalls Overriding Versus Overloading. These two words look a lot alike and confuse students as to their difference often. It is important to remember that overriding can only occur when inheritance is present and does not change the signature of the method. Overloading, however, does change the signature of the method and does not require that their be inheritance. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

Subclass and Superclass. These terms are often used to describe derived class and base class respectively. Use of Private Instance Variables from the Base Class. It is important to note that subclasses do not inherit private instance variables or methods from the superclass. You can not directly access these elements of a superclass from the subclass if they are private in the superclass. This idea is repeated in the next pitfall box Private Methods are Effectively Not Inherited. Private Methods are Effectively Not Inherited. Even though private variables of the base class can be accessed using accessors and mutators, there is no mechanism for inheriting private methods. Forgetting about the Default Package. If a class is in your current directory and does not specify a package, it is in the default package and all classes in the default package have access to methods that have package access. A Restriction on Protected Access. This pitfall describes a unique situation and can be omitted without causing a gap in student’s understanding of protected/private/public/package access. You Cannot Use Multiple supers. More accurately, you cannot stack your super’s to get back to a method in an ancestor class. You can only access the method in the direct parent class when calling super. Examples An Enhanced String Tokenizer Class. This example relies on the material from Chapter 6 on arrays as well as the material from Chapter 4 on StringTokenizer. The example uses inheritance to create a better String Tokenizer that allows you to revisit tokens that you have already seen from the StringTokenizer. Programming Projects Answers 1. /** * PersonDetails.java * * This program demonstrates the inheritance by creating a class called * Person and extending it by two other classes Student and Teacher * Created: Feb 2, 2016 * * @author * @version 1 */ public class PersonDetails { public static void main(String[] args) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

Student s1 = new Student("John", "Mathew", "S110001", "UG", "Peter"); Student s2 = new Student("Wayne", "Parnell", "S110002", "PG", "Morkel"); s1.displayDetails(); s2.displayDetails(); Teacher t1 = new Teacher("Simon", "Harmer", "Java", 10500); Teacher t2 = new Teacher("David", "Miller", "C++", 20500); t1.displayDetails(); t2.displayDetails(); } } /** * Person class that contains first and last name of a person */ class Person { private String firstName; private String lastName; /** * Constructor that receives first and * last name of the Person * * @param fname * @param lname */ public Person(String fname, String lname) { this.firstName = fname; this.lastName = lname; } //Mutator and accessor methods public void setFirstName(String fname) { this.firstName = fname; } public void setLastName(String lname) { this.lastName = lname; } public String getFirstName() { return (firstName); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

} public String getLastName() { return (lastName); } /** * Displays the first and last name */ public void displayDetials() { System.out.println("First Name : " + firstName); System.out.println("Last Name : " + lastName); } } /** * Student class that extends the Person class * */ class Student extends Person { private String studentID; private String courseName; private String teacherName; /** * Constructor of the Student class * * @param fname * First name of the student * @param lname * Last name of the student * @param sid * Student ID * @param cname * Name of the course * @param tname * Name of the teacher */ public Student(String fname, String lname, String sid, String cname, String tname) { super(fname, lname); this.studentID = sid; this.courseName = cname; this.teacherName = tname; }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

/** * Displays the student details */ @Override public void displayDetials() { System.out.println("\nFirst Name : " + super.getFirstName()); System.out.println("Last Name : " + super.getLastName()); System.out.println("Student ID : " + studentID); System.out.println("Course Name : " + courseName); System.out.println("Teacher Name : " + teacherName); } } /** * Teacher class that extends Person class */ class Teacher extends Person { String subjectName; double salary; /** * Constructor to instantiate Teacher class * with its details * * @param fname * First name of the Teacher * @param lname * Last name of the teacher * @param sname * Name of the subject * @param salary * Teacher's salary */ public Teacher(String fname, String lname, String sname, double salary) { super(fname, lname); this.subjectName = sname; this.salary = salary; } /** Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

* Displays the Teacher details */ @Override public void displayDetials() { System.out.println("\nFirst Name : " + super.getFirstName()); System.out.println("Last Name : " + super.getLastName()); System.out.println("Subject Name : " + subjectName); System.out.println("Salary : " + salary); } } 2. /** * Messaging.java * * This program demonstrates the inheritance by creating two classes SMS * and Email by extending a base class called Message. Also, the * program lets you search for a word in the messages. * * Created: Feb 2, 2016 * * @author * @version 1 */ import java.util.Scanner; public class Messaging { /** * Checks whether the specified keyword exists in the specified * message object * * @param messageObject * Message object to look for the keyword in * @param keyword * Keyword to be searched * @return Returns true if keyword exists in message object. False * otherwise. */ public static boolean containsKeywords(Message messageObject, String keyword) { if (messageObject.toString().indexOf(keyword, 0) >= 0) return true; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

else return false; } public static void main(String[] args) { String keyword; SMS newSMS = new SMS(3156778, "How are you"); Email newMail = new Email("myemailid@tmail.com", "myfriendid@tmail.com", "Meeting", "meeting tomorrow at 10:00"); System.out.println("SMS Message is = " + newSMS.toString()); System.out.println("Email Message is = " + newMail.toString()); Scanner keyboard = new Scanner(System.in); System.out.print("Enter the keyword to search = "); keyword = keyboard.next(); if (Messaging.containsKeywords(newMail, "")) System.out.println("Word Found in the message"); else System.out.println("Word Not Found in the message"); } } /** * * Message class that stores a message text * */ class Message { private String text; //Accessor and mutator methods public String getText() { return (text); } public void setText(String newText) { this.text = newText; } @Override public String toString() { return (text); } } /** * * SMS class that extends Message class * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

*/ class SMS extends Message { private int recipientNo; /** * Constructor with recipient’s phone number and message * * @param rnumber * Recipient’s phone number * @param body * Message body */ public SMS(int rnumber, String body) { recipientNo = rnumber; setText(body); } //Accessor and mutator methods public int getReceiptNo() { return (recipientNo); } public void setRecipientNo(int newNo) { recipientNo = newNo; } /** * Returns recipient’s phone number and message * in a single string */ @Override public String toString() { return (recipientNo + ":" + getText()); } } /** * * Email class that extends Message class * */ class Email extends Message { private String sender; private String receiver; private String subject; /** * Constructor with sender and receiver's email address, * subject and message body Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

* * @param sender * Sender's email address * @param reciever * Receiver's email address * @param subject * Email subject * @param body * Email body */ public Email(String sender, String receiver, String subject, String body) { this.sender = sender; this.receiver = receiver; this.subject = subject; setText(body); } //Accessor and mutator methods public String getSender() { return (sender); } public void setSender(String sender) { this.sender = sender; } public String getReceiver() { return (receiver); } public void setReceiver(String receiver) { this.receiver = receiver; } public String getsubject() { return (subject); } public void setsubject(String subject) { this.subject = subject; } /** * Returns sender and recipient’s email address, * email subject and email body in a single string. */ @Override public String toString() { return (sender + ":" + receiver + ":" + subject + ":" + getText()); } } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

3. /** * Question3Alien.java * * This program introduces inheritance by rewriting a non-OO class * using a switch statement for types into one with derived classes * for the subtypes. A getDamage method returns the amount of * damage that an alien inflicts. This design is superior to the * old one since it is now independent to add a new type of Alien * to the game; we no longer need to change code in the Alien class. * * Created: Sat Mar 19 2005 * * @author Kenrick Mock * @version 1 */ class Alien { public static final int DEFAULT_DAMAGE = 0; private int health; // 0=dead, 100=full strength private String name; /** * Default constructor; Initialize name and health. */ public Alien() { health = 100; name = ""; } /** * Default constructor; Initialize variables to input parameters. * @param health Initial health * @param name Initial name */ public Alien(int health, String name) { this.health = health; this.name = name; } // ====================== // Various accessor and mutator methods // ====================== Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

public int getHealth() { return health; } public void setHealth(int health) { this.health = health; } public String getName() { return name; } public void setName(String name) { this.name = name; } /** * getDamage returns the amount of damage this alien inflicts. */ public int getDamage() { return DEFAULT_DAMAGE; } } // Alien

/** The SnakeAlien class extends the Alien class * since it is a sub-type of Alien. By doing this for * all the alien types, we can eliminate the "type" variable * in the original Alien class. */ class SnakeAlien extends Alien { public static final int SNAKE_DAMAGE = 10; /** * Constructors */ public SnakeAlien() { super(); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

public SnakeAlien(int health, String name) { super(health,name); } /** * getDamage returns the amount of damage this alien inflicts. */ public int getDamage() { return SNAKE_DAMAGE; } } // SnakeAlien

/** * Class for the Ogre Alien */ class OgreAlien extends Alien { public static final int OGRE_DAMAGE = 6; /** * Constructors */ public OgreAlien() { super(); } public OgreAlien(int health, String name) { super(health,name); } /** * getDamage returns the amount of damage this alien inflicts. */ public int getDamage() { return OGRE_DAMAGE; } } // OgreAlien /** * Class for the Marshmallow Alien */ Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

class MarshmallowAlien extends Alien { public static final int MARSHMALLOW_DAMAGE = 1; /** * Constructors */ public MarshmallowAlien() { super(); } public MarshmallowAlien(int health, String name) { super(health,name); } /** * getDamage returns the amount of damage this alien inflicts. */ public int getDamage() { return MARSHMALLOW_DAMAGE; } } // MarshmallowAlien /** * This class stores an array of Aliens that comprise a "pack" */ class AlienPack { private Alien[] aliens; public AlienPack(int numAliens) { aliens = new Alien[numAliens]; } public void addAlien(Alien newAlien, int index) { aliens[index] = newAlien; } public Alien[] getAliens() { return aliens; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

/** * To calculate the damage inflicted by all aliens in the pack * we can now simply iterate through each alien and call its * getDamage() method */ public int calculateDamage() { int damage = 0; for (int i=0; i < aliens.length; i++) { damage += aliens[i].getDamage(); } return damage; } } // AlienPack

class Question3Alien { // ====================== // main method. // In main we simply create a small pack and output its total damage (17). // ====================== public static void main(String[] args) { OgreAlien brutus = new OgreAlien(100,"brutus"); SnakeAlien slimy = new SnakeAlien(100,"slimy"); MarshmallowAlien puffy = new MarshmallowAlien(100,"puffy"); AlienPack pack = new AlienPack(3); // 3 aliens in the pack pack.addAlien(brutus, 0); pack.addAlien(slimy, 1); pack.addAlien(puffy, 2); System.out.println("Total pack damage = " + pack.calculateDamage()); } } // Question3Alien

4.

/** * Administrator.java * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

* Created: Sun Jan 11 19:42:37 2004 * Modified: Sat Mar 05 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ import java.util.Scanner; public class Administrator extends SalariedEmployee { private String _title; private String _area; private String _supervisorsName; public Administrator (){ super(); _title = "Admin"; _area = "Admin"; _supervisorsName = "None"; } public Administrator(String theName, Date theDate, double theSalary, String title, String area, String supervisorsName) { super(theName, theDate, theSalary); if ( title == "" || area == "" || supervisorsName == "" ) { System.out.println("Fatal Error: Empty string."); System.exit(0); } // end of if () _title = title; _area = area; _supervisorsName = supervisorsName; } public Administrator (Administrator other) { super(other); _title = other._title; _area = other._area; _supervisorsName = other._supervisorsName; } public String getTitle() { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

return _title; } public String getArea() { return _area; } public String getSupervisorsName() { return _supervisorsName; } public void setTitle(String title) { _title = title; } public void setArea(String area) { _area = area; } public void setSupervisorsName(String supervisorsName) { _supervisorsName = supervisorsName; } public void readAdminInfo() { Scanner keyboard = new Scanner(System.in); System.out.println("Enter the name of the administrator:"); String input = keyboard.nextLine(); this.setName(input); System.out.println("Enter the month as a number:"); int month = keyboard.nextInt(); System.out.println("Enter the day as a number:"); int day = keyboard.nextInt(); System.out.println("Enter the year as a number:"); int year = keyboard.nextInt();; Date date = new Date(month, day, year); this.setHireDate(date); System.out.println("Enter the Salary as a number:"); input = keyboard.nextLine(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

double salary = keyboard.nextDouble(); this.setSalary(salary); keyboard.nextLine(); // Clear newline left from nextDouble System.out.println("Enter the administrator's title:"); input = keyboard.nextLine(); this.setTitle(input); System.out.println("Enter the administrator's area:"); input = keyboard.nextLine(); this.setArea(input); System.out.println("Enter the administrator's supervisor:"); input = keyboard.nextLine(); this.setSupervisorsName(input); } public boolean equals(Object other) { if ( other == null ) { return false; } // end of if () else if ( this.getClass() != other.getClass() ) { return false; } // end of if () else { Administrator admin = (Administrator)other; return (this.getName().equals(admin.getName())) && (this.getHireDate().equals(admin.getHireDate())) && (this.getSalary() == admin.getSalary()) && (this.getTitle().equals(admin.getTitle())) && (this.getArea().equals(admin.getArea())) && (this.getSupervisorsName().equals(admin.getSupervisorsName())); } // end of else } public String toString() { String result = super.toString(); result += ", " + getTitle() + ", " + getArea() + ", supervised by " + getSupervisorsName(); return result; } }// Administrator Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

/** * Question4.java * * Created: Fri Jan 09 20:07:13 2004 * * @author Adrienne Decker * @version 2 */ public class Question4 { public static void main(String[] args) { Administrator admin1 = new Administrator(); System.out.println("admin1: " + admin1); Administrator admin2 = new Administrator("Bob", new Date(2, 3, 1999), 34000, "Vice President", "Human Resources", "Joe"); System.out.println("admin2: " + admin2); Administrator admin3 = new Administrator(admin2); System.out.println("admin3 copy of admin2: " + admin3); System.out.println("Get the title from admin2: " + admin2.getTitle()); System.out.println("Get the area from admin2: " + admin2.getArea()); System.out.println("Get the supervisors name from admin2: " + admin2.getSupervisorsName()); System.out.println("admin2 equal to admin3: " + admin2.equals(admin3)); System.out.println("admin1 equal to admin3: " + admin1.equals(admin3)); admin1.readAdminInfo(); System.out.println("admin1: " + admin1); } } // Question4

5. /** * Doctor.java Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

* * * Created: Sun Jan 11 21:19:40 2004 * * @author Adrienne Decker * @version */ public class Doctor extends SalariedEmployee { private String _specialty; private double _officeVisitFee; public Doctor () { super(); _specialty = "None"; _officeVisitFee = 0.0; } public Doctor(String theName, Date theDate, double theSalary, String specialty, double officeFee) { super(theName, theDate, theSalary); if ( specialty == null ) { System.out.println("Fatal error: Empty specialty."); System.exit(0); } // end of if () if ( officeFee < 0 ) { System.out.println("Fatal error: negative office visit fee."); System.exit(0); } // end of if () _specialty = specialty; _officeVisitFee = officeFee; } public Doctor(Doctor other) { super(other); _specialty = other._specialty; _officeVisitFee = other._officeVisitFee; } public String getSpecialty() { return _specialty; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

} public double getOfficeVisitFee() { return _officeVisitFee; } public void setSpecialty(String specialty) { _specialty = specialty; } public void setOfficeVisitFee(double fee) { _officeVisitFee = fee; } public boolean equals(Object other) { if ( other == null ) { return false; } // end of if () else if ( this.getClass() != other.getClass() ) { return false; } // end of if () else { Doctor doctor = (Doctor)other; return (this.getName().equals(doctor.getName())) && (this.getHireDate().equals(doctor.getHireDate())) && (this.getSalary() == doctor.getSalary()) && (this.getSpecialty().equals(doctor.getSpecialty())) && (this.getOfficeVisitFee() == doctor.getOfficeVisitFee()); } } public String toString() { String result = super.toString(); result += ", " + getSpecialty() + ", $" + getOfficeVisitFee() + " per office visit."; return result; } }// Doctor

/** * Question5.java Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

* * Created: Fri Jan 09 20:07:17 2004 * * @author Adrienne Decker * @version 2 */ public class Question5 { public static void main(String[] args) { Doctor doctor1 = new Doctor(); System.out.println("doctor1: " + doctor1); Doctor doctor2 = new Doctor("Bob", new Date(2, 3, 1999),34000, "Pediatrics", 5.0); System.out.println("doctor2: " + doctor2); Doctor doctor3 = new Doctor(doctor2); System.out.println("doctor3 copy of doctor2: " + doctor3); System.out.println("Get the specialty from doctor2: " + doctor2.getSpecialty()); System.out.println("Get the office visit fee from doctor2: " + doctor2.getOfficeVisitFee()); System.out.println("doctor2 equal to doctor3: " + doctor2.equals(doctor3)); System.out.println("doctor1 equal to doctor3: " + doctor1.equals(doctor3)); doctor1.setSpecialty("Dermatologist"); doctor1.setOfficeVisitFee(10.0); System.out.println("doctor1: " + doctor1); } } // Question5

6. /** * Vehicle.java * * * Created: Sun Jan 11 21:41:40 2004 * * @author Adrienne Decker * @version */

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

public class Vehicle { private String _manufacturer; private int _cylinders; private Person _owner; public Vehicle () { _manufacturer = "None"; _cylinders = 0; _owner = new Person(); } public Vehicle(String man, int cylinders, Person owner) { _manufacturer = man; _cylinders = cylinders; _owner = new Person(owner); } public Vehicle(Vehicle other) { _manufacturer = other._manufacturer; _cylinders = other._cylinders; _owner = new Person(other._owner); } public String getManufacturer() { return _manufacturer; } public int getCylinders() { return _cylinders; } public Person getOwner() { return new Person(_owner); } public void setManufacturer(String man) { _manufacturer = man; } public void setCylinders(int cylinders) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

_cylinders = cylinders; } public void setOwner(Person owner) { _owner = new Person(owner); } public String toString() { return _manufacturer + ", " + _cylinders + " cylinders, owned by " + _owner; } public boolean equals(Object other) { if ( other == null ) { return false; } // end of if () else if ( this.getClass() != other.getClass() ) { return false; } // end of if () else { Vehicle vehicle = (Vehicle)other; return (this.getManufacturer().equals(vehicle.getManufacturer())) && (this.getCylinders() == vehicle.getCylinders()) && (this.getOwner().equals(vehicle.getOwner())); } // end of else } }// Vehicle

/** * Truck.java * * * Created: Sun Jan 11 21:52:48 2004 * * @author Adrienne Decker * @version */ public class Truck extends Vehicle { private double _loadCapacity; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

private int _towingCapacity; public Truck () { super(); _loadCapacity = 0.0; _towingCapacity = 0; } public Truck(String manufacturer, int cylinders, Person owner, double load, int tow) { super(manufacturer, cylinders, owner); _loadCapacity = load; _towingCapacity = tow; } public Truck(Truck other) { super(other); _loadCapacity = other._loadCapacity; _towingCapacity = other._towingCapacity; } public double getLoadCap() { return _loadCapacity; } public int getTowingCap() { return _towingCapacity; } public void setLoadCap(double load) { _loadCapacity = load; } public void setTowingCap(int tow) { _towingCapacity = tow; } public String toString() { String result = super.toString(); result += ", load capacity " + _loadCapacity + ", towing capacity " + _towingCapacity; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

return result; } public boolean equals(Object other) { if ( other == null ) { return false; } // end of if () else if ( this.getClass() != other.getClass() ) { return false; } // end of if () else { Truck truck = (Truck)other; return (this.getManufacturer().equals(truck.getManufacturer())) && (this.getCylinders() == truck.getCylinders()) && (this.getOwner().equals(truck.getOwner())) && (this.getLoadCap() == truck.getLoadCap()) && (this.getTowingCap() == truck.getTowingCap()); } // end of else } }// Truck

/** * Person.java * * * Created: Sun Jan 11 21:35:37 2004 * * @author Adrienne Decker * @version */ public class Person { private String name; public Person () { name = ""; } public Person(String theName) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

name = theName; } public Person(Person theObject) { name = theObject.name; } public String getName() { return name; } public void setName(String theName) { name = theName; } public String toString() { return name; } public boolean equals(Object other) { if ( other == null ) { return false; } // end of if () else if ( this.getClass() != other.getClass() ) { return false; } // end of if () else { Person person = (Person)other; return (this.getName().equals(person.getName())); } // end of else } }// Person

/** * Question6.java * * Created: Fri Jan 09 20:07:22 2004 * * @author Adrienne Decker Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

* @version */ public class Question6 { public static void main(String[] args) { Person p1 = new Person(); System.out.println("p1: " + p1); p1.setName("Bob"); System.out.println("p1's name is: " + p1.getName() ); Person p2 = new Person("Joe"); System.out.println("p2: " + p2); Person p3 = new Person(p1); System.out.println("p3 equal to p1: " + p3.equals(p1)); System.out.println("p2 equal to p1: " + p2.equals(p1));

Vehicle v1 = new Vehicle(); System.out.println("v1: " + v1); v1.setManufacturer("Ford"); v1.setCylinders(4); v1.setOwner(new Person("Joe")); System.out.println("v1's manufacturer is: " + v1.getManufacturer() ); System.out.println("v1's cylinders: " + v1.getCylinders() ); System.out.println("v1's owner is: " + v1.getOwner() ); Vehicle v2 = new Vehicle("Chevy", 4, new Person("Betty")); System.out.println("v2: " + v2); Vehicle v3 = new Vehicle(v1); System.out.println("v3 equal to v1: " + v3.equals(v1)); System.out.println("v2 equal to v1: " + v2.equals(v1)); Truck t1 = new Truck(); System.out.println("t1: " + t1); t1.setLoadCap(54.36); t1.setTowingCap(10); System.out.println("t1's load capacity is: " + t1.getLoadCap() ); System.out.println("t1's towing capacity is: " + t1.getTowingCap() );

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

Truck t2 = new Truck("Chevy", 4, new Person("Betty"), 34.5, 65); System.out.println("t2: " + t2); Truck t3 = new Truck(t1); System.out.println("t3 equal to t1: " + t3.equals(t1)); System.out.println("t2 equal to t1: " + t2.equals(t1)); } } // Question6

7. /** * Patient.java * * * Created: Tue Jan 13 19:16:05 2004 * * @author Adrienne Decker * @version */ public class Patient extends Person { private Doctor _primaryDoctor; public Patient () { super(); _primaryDoctor = new Doctor(); } public Patient(String name, Doctor primary) { super(name); _primaryDoctor = primary; } public Patient (Patient other) { super(other); _primaryDoctor = new Doctor(other._primaryDoctor); } public Doctor getPrimary() Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

{ return new Doctor(_primaryDoctor); } public void setPrimary(Doctor doctor) { _primaryDoctor = new Doctor(doctor); } public boolean equals(Object other) { if ( other == null ) { return false; } // end of if () else if ( this.getClass() != other.getClass() ) { return false; } // end of if () else { Patient patient = (Patient)other; return (this.getName().equals(patient.getName())) && this.getPrimary().equals(patient.getPrimary()); } // end of else } public String toString() { String result = super.toString(); result += ", Primary: " + _primaryDoctor; return result; } }// Patient

/** * Billing.java * * * Created: Tue Jan 13 19:16:11 2004 * * @author Adrienne Decker * @version */ public class Billing { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

private Patient _patient; private Doctor _doctor; private double _amountDue; public Billing () { _patient = new Patient(); _doctor = new Doctor(); _amountDue = 0.0; } public Billing(Patient patient, Doctor doctor, double amount) { _patient = new Patient(patient); _doctor = new Doctor(doctor); _amountDue = amount; } public Billing(Billing other) { _patient = new Patient(other._patient); _doctor = new Doctor(other._doctor); _amountDue = other._amountDue; } public Patient getPatient() { return _patient; } public Doctor getDoctor() { return _doctor; } public double getAmountDue() { return _amountDue; } public void setPatient(Patient patient) { _patient = patient; } public void setDoctor(Doctor doctor) { _doctor = doctor; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

public void setAmountDue(double amount) { _amountDue = amount; } public boolean equals(Object other) { if ( other == null ) { return false; } // end of if () else if ( this.getClass() != other.getClass() ) { return false; } // end of if () else { Billing billing = (Billing)other; return (this.getPatient().equals(billing.getPatient())) && (this.getDoctor().equals(billing.getDoctor())) && (this.getAmountDue() == billing.getAmountDue()); } // end of else } public String toString() { return "Patient: " + _patient + "\nDoctor: " + _doctor + "\nAmount Due: $" + _amountDue; } }// Billing

/** * Question7Driver.java * * Created: Fri Jan 09 20:07:30 2004 * * @author Adrienne Decker * @version */ public class Question7Driver { public static void main(String[] args) { Patient p1 = new Patient(); System.out.println("p1: " + p1); p1.setPrimary(new Doctor("Bob", new Date(1,1,2000), 34000, "Podiatrist", 10.50)); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

System.out.println("p1's doctor is: " + p1.getPrimary() ); Patient p2 = new Patient("Joe", new Doctor("Bob", new Date(1,1,2000), 34000, "Podiatrist", 10.50)); System.out.println("p2: " + p2); Patient p3 = new Patient(p1); System.out.println("p3 equal to p1: " + p3.equals(p1)); System.out.println("p2 equal to p1: " + p2.equals(p1));

Billing b1 = new Billing(); System.out.println("b1: " + b1); Doctor d = new Doctor("Bob", new Date(1,1,2000), 34000,"Podiatrist", 10.50); b1.setDoctor(d); b1.setPatient(new Patient("Sally", d)); b1.setAmountDue(45.65); System.out.println("b1's doctor is: " + b1.getDoctor() ); System.out.println("b1's patient is: " + b1.getPatient()); System.out.println("b1's amount due is: " + b1.getAmountDue()); Billing b2 = new Billing(new Patient("Joe", d), d, 400.56); System.out.println("b2: " + b2); Billing b3 = new Billing(b1); System.out.println("b3 equal to b1: " + b3.equals(b1)); System.out.println("b2 equal to b1: " + b2.equals(b1)); } } // Question7Driver

/** * Question7.java * * * Created: Fri Jan 09 20:07:30 2004 * * @author Adrienne Decker * @version */ public class Question7 { public static void main(String[] args) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

Doctor d1 = new Doctor("Bob", new Date(1,1,2000), 34000, "Podiatrist", 10.50); Doctor d2 = new Doctor("Susan", new Date(7,22,1990), 450000, "Surgeon", 150.50); Patient p1 = new Patient("Fred", d1); Patient p2 = new Patient("Sally", d2); Billing b1 = new Billing(p1, d1, 21.00); Billing b2 = new Billing(p2, d2, 150.50); System.out.println("The total billing amount is: " + (b1.getAmountDue() + b2.getAmountDue())); } } // Question7

8. /** * Question 8 * * Modification of the solution to PP 4.10 to use * inheritance instead of the type variable. * */ /** Class for basic pet records: name, age, and weight. */ public class Pet { private String name; private int age;//in years private double weight;//in pounds public String toString( ) { return ("Name: " + name + " Age: " + age + " years" + "\nWeight: " + weight + " pounds"); } public Pet(String initialName, int initialAge, double initialWeight) { name = initialName; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

if ((initialAge < 0) || (initialWeight < 0)) { System.out.println("Error: Negative age or weight."); System.exit(0); } else { age = initialAge; weight = initialWeight; } } public void set(String newName, int newAge, double newWeight) { name = newName; if ((newAge < 0) || (newWeight < 0)) { System.out.println("Error: Negative age or weight."); System.exit(0); } else { age = newAge; weight = newWeight; } } public Pet(String initialName) { name = initialName; age = 0; weight = 0; } public void setName(String newName) { name = newName; } public Pet(int initialAge) { name = "No name yet."; weight = 0; if (initialAge < 0) { System.out.println("Error: Negative age."); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

System.exit(0); } else age = initialAge; } public void setAge(int newAge) { if (newAge < 0) { System.out.println("Error: Negative age."); System.exit(0); } else age = newAge; } public Pet(double initialWeight) { name = "No name yet"; age = 0; if (initialWeight < 0) { System.out.println("Error: Negative weight."); System.exit(0); } else weight = initialWeight; } public void setWeight(double newWeight) { if (newWeight < 0) { System.out.println("Error: Negative weight."); System.exit(0); } else weight = newWeight; } public Pet( ) { name = "No name yet."; age = 0; weight = 0; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

} public String getName( ) { return name; } public int getAge( ) { return age; } public double getWeight( ) { return weight; } // Overridden in subclass; // Would be better to define this abstract public double acepromazine() { return 0; } // Overriden in subclass; // Would be better to define this abstract public double carprofen() { return 0; } } public class Dog extends Pet { public Dog() { super(); } public Dog(String initialName, int initialAge, double initialWeight) { super(initialName, initialAge, initialWeight); } public String toString() Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

{ return "Type: Dog. " + super.toString(); } public double acepromazine() { return (getWeight() / 2.2) * (0.03 / 10); } public double carprofen() { return (getWeight() / 2.2) * (0.5 / 10); } }

public class Cat extends Pet { public Cat() { super(); } public Cat(String initialName, int initialAge, double initialWeight) { super(initialName, initialAge, initialWeight); } public String toString() { return "Type: Cat. " + super.toString(); } public double acepromazine() { return (getWeight() / 2.2) * (0.002 / 10); } public double carprofen() { return (getWeight() / 2.2) * (0.025 / 10); } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 7, Instructor’s Manual

import java.util.Scanner; public class PetDemo { public static void main(String[] args) { Pet usersPet = new Pet("Jane Doe"); System.out.println("My records on your pet are incomplete."); System.out.println("Here is what they currently say:"); System.out.println(usersPet); Scanner keyboard = new Scanner(System.in); System.out.println("Please enter the pet's name:"); String name = keyboard.nextLine( ); System.out.println("Please enter the pet's type (dog or cat):"); String type = keyboard.nextLine( ); System.out.println("Please enter the pet's age:"); int age = keyboard.nextInt( ); System.out.println("Please enter the pet's weight:"); double weight = keyboard.nextDouble( ); if (type.equals("dog")) { usersPet = new Dog(); } else if (type.equals("cat")) { usersPet = new Cat(); } usersPet.set(name, age, weight); System.out.println("My records now say:"); System.out.println(usersPet); System.out.printf("Dose of carprofen: %.4f\n", usersPet.carprofen()); System.out.printf("Dose of acepromazine: %.4f\n", usersPet.acepromazine()); } } // Question 8 Question 9: No solution provided

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

Chapter 8

Polymorphism and Abstract Classes Key Terms late binding binding early binding polymorphism final static binding upcasting downcasting instanceOf clone abstract method abstract cannot be private abstract class concrete class

Brief Outline 8.1 Polymorphism Late Binding The final Modifier Late Binding with toString Downcasting and Upcasting A First Look at the clone Method 8.2 Abstract Classes Abstract Classes

Teaching Suggestions This chapter discusses polymorphism. The concept of polymorphism is one that is sometimes hard for students to grasp. As indicated, this chapter does not require any information from Chapter 6 and could be taught before that. However, inheritance is required, so a possible reordering of topics could be Chapters 7 & 8 before Chapter 6. In this section, we also see the introduction of abstract classes. An abstract class is one that is at least partially undefined within the program. The programmer can not create an instance of an abstract class and these classes can be used as a basis of an inheritance hierarchy. When a class extends an abstract class, the subclass is required to give a definition to the abstract methods or be declared abstract. This is compiler enforced.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

These two topics in this chapter are somewhat disjoint and the instructor may choose to cover them at separate times as one does not need polymorphism to have an abstract class or have an abstract class to use polymorphism. Key Points Late Binding. Java uses late binding for all method calls, which is what makes polymorphism possible. This concept deals with how the machine actually handles the call to the method at the system level. Polymorphism. The main idea of polymorphism is the ability to associate many meanings to one method, making the method execute differently depending on in what context the method is called. The final Modifier. Adding final to a method definition means that a method can not be redefined in any subclass. If a class is declared final, it can not be used as a superclass. An Object Knows the Definitions of its Methods. The only methods that can be called on an object are those that are defined by its class type. The method that will get executed is the one that is defined by its object type. Abstract Method. An abstract method is one that is not defined in a particular class. The entire method signature is given with a semicolon where the method body should be. Also indicative of an abstract method is the keyword abstract in the method signature. Classes that subclass from a class with an abstract method are forced by the compiler to provide a definition for the abstract method. Abstract Class. As soon as a class has an abstract method, the entire class becomes abstract indicated by the keyword abstract in the class definition. Tips Checking to See if Downcasting is Legitimate. This tip is optional and omitting it will not hinder students trying to understand polymorphism. The discussion focuses on using the instanceof operator to see if downcasting makes sense in a particular case. An Abstract Class is a Type. Even though you cannot create an instance of an abstract class, you can still use it as a type of a variable or as a type for a parameter or return type. There is a tip in this section that reiterates this same idea.

Pitfalls No Late Binding for Static Methods. Java does not use late binding for private methods, methods that are final, or static methods. This is most important for static methods. When methods are static, Java uses static binding and the method’s execution is determined at compile time, which may or may not be what the programmer had originally intended.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

Downcasting. It is the programmer’s responsibility to use downcasting when necessary. However, if the programmer uses downcasting in the incorrect place, a run time error will usually be thrown. Sometimes the clone Method Return Type is Object. The clone method is inherited from the class Object and when you are writing a clone method in an object, you must give its return type as Object. If you give another return type, a compiler error will be thrown because you cannot use method overloading on a method by only changing the return type. Limitations of Copy Constructor. This pitfall is another optional section and talks about why the copy constructor is not always the best choice. In fact, the clone method is the preferred method for doing the copy constructor functionality in Java. Therefore, this discussion could be relevant for why clone should be used. Alternatively, an instructor could choose not to discuss a copy constructor, but rather just wait to discuss the clone method. You Cannot Create Instances of an Abstract Class. This pitfall is pretty self explanatory. The compiler will simply not allow this to happen.

Examples Sales Records. In this example we see how late binding is used when calling the bill method of the Sale class. It also introduces the idea that as software designers, we may not always have perfect information about a problem. We can not always see all the possible ways a program will be used when built and one way to possibly help our programs be more versatile is to harness the power of polymorphism.

Programming Projects Answers 1. /** * Question1AlienAbstract.java * * This program introduces inheritance by rewriting a non-OO class * using a switch statement for types into one with derived classes * for the subtypes. A getDamage method returns the amount of * damage that an alien inflicts. This design is superior to the * old one since it is now independent to add a new type of Alien * to the game; we no longer need to change code in the Alien class. * * In this version, the Alien class has been turned into an abstract * class. * * Created: Sat Mar 19 2005 * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

* @author Kenrick Mock * @version 1 */ abstract class Alien { private int health; // 0=dead, 100=full strength private String name; /** * Default constructor; Initialize name and health. */ public Alien() { health = 100; name = ""; } /** * Default constructor; Initialize variables to input parameters. * @param health Initial health * @param name Initial name */ public Alien(int health, String name) { this.health = health; this.name = name; } // ====================== // Various accessor and mutator methods // ====================== public int getHealth() { return health; } public void setHealth(int health) { this.health = health; } public String getName() { return name; }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

public void setName(String name) { this.name = name; } /** * getDamage returns the amount of damage this alien inflicts. */ public abstract int getDamage(); } // Alien /** The SnakeAlien class extends the Alien class * since it is a sub-type of Alien. By doing this for * all the alien types, we can eliminate the "type" variable * in the original Alien class. */ class SnakeAlien extends Alien { public static final int SNAKE_DAMAGE = 10; /** * Constructors */ public SnakeAlien() { super(); } public SnakeAlien(int health, String name) { super(health,name); } /** * getDamage returns the amount of damage this alien inflicts. */ public int getDamage() { return SNAKE_DAMAGE; } } // SnakeAlien

/** * Class for the Ogre Alien */ Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

class OgreAlien extends Alien { public static final int OGRE_DAMAGE = 6; /** * Constructors */ public OgreAlien() { super(); } public OgreAlien(int health, String name) { super(health,name); } /** * getDamage returns the amount of damage this alien inflicts. */ public int getDamage() { return OGRE_DAMAGE; } } // OgreAlien /** * Class for the Marshmallow Alien */ class MarshmallowAlien extends Alien { public static final int MARSHMALLOW_DAMAGE = 1; /** * Constructors */ public MarshmallowAlien() { super(); } public MarshmallowAlien(int health, String name) { super(health,name); } /** * getDamage returns the amount of damage this alien inflicts. */ Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

public int getDamage() { return MARSHMALLOW_DAMAGE; } } // MarshmallowAlien /** * This class stores an array of Aliens that comprise a "pack" */ class AlienPack { private Alien[] aliens; public AlienPack(int numAliens) { aliens = new Alien[numAliens]; } public void addAlien(Alien newAlien, int index) { aliens[index] = newAlien; } public Alien[] getAliens() { return aliens; } /** * To calculate the damage inflicted by all aliens in the pack * we can now simply iterate through each alien and call its * getDamage() method */ public int calculateDamage() { int damage = 0; for (int i=0; i < aliens.length; i++) { damage += aliens[i].getDamage(); } return damage; } } // AlienPack

class Question1AlienAbstract { /** ====================== * main method. * In main we simply create a small pack and output its total damage (17). * ====================== Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

*/ public static void main(String[] args) { OgreAlien brutus = new OgreAlien(100,"brutus"); SnakeAlien slimy = new SnakeAlien(100,"slimy"); MarshmallowAlien puffy = new MarshmallowAlien(100,"puffy"); AlienPack pack = new AlienPack(3); // 3 aliens in the pack pack.addAlien(brutus, 0); pack.addAlien(slimy, 1); pack.addAlien(puffy, 2); System.out.println("Total pack damage = " + pack.calculateDamage()); } } // Question1AlienAbstract 2. /** * Employee.java * * This program defines a class called Employee, which stores basic * information like name, employee id etc., that is extended by Clerk * and Manager classes which include additional properties and methods. * * Created: Feb 3, 2016 * * @author * @version 1 */ public class Employee { String employeeID; String name; String departmentName; double salary; String designation; /** * Constructor that takes basic details of an Employee * * @param eID * Employee ID * @param name * Name * @param dname * Name of the department * @param salary Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

* Salary * @param desg * Designation */ public Employee(String eID, String name, String dname, double salary, String desg) { this.employeeID = eID; this.name = name; this.salary = salary; this.designation = desg; } //Various accessor and mutator methods public String getEmployeeID() { return (employeeID); } public String getName() { return (name); } public String getDepartmentName() { return (departmentName); } public double getSalary() { return (salary); } public String getDesignation() { return (designation); } public void setEmployeeID(String empId) { this.employeeID = empId; } public void setName(String name) { this.name = name; } public void setdepartmentName(String dname) { this.departmentName = dname; } public void getSalary(double salary) { this.salary = salary; } public void getDesignation(String desg) { this.designation = desg; } /** * This method overrides equals() method of the Object class to Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

* compare the designations of the employees * * @param emp * Employee object whose designation need to be * compared * @return True if designations are identical. False otherwise. */ public boolean equals(Employee emp) { boolean flag = false; if (this.designation.equals(emp.designation)) flag = true; return (flag); } /** * Method that adds bonus to the employee's salary * * @return Revised salary after adding bonus */ public double addBonus() { double bonus = 200; salary = salary + bonus; return (salary); } /** * Display the details of the Employee */ public void display() { System.out.println("\nEmployee ID :" + employeeID); System.out.println("Employee name : " + name); System.out.println("Department name : " + departmentName); System.out.println("Salary :" + salary); System.out.println("Designation : " + designation); } public static void main(String[] args) { Manager manager1 = new Manager("E001", "Mark", "HR", 15000); Manager manager2 = new Manager("E012", "Peter", "R&D", 15000); Clerk clerk1 = new Clerk("E056", "Samual", "Accounts", 10000); Clerk clerk2 = new Clerk("E089", "John", "Accounts", 10000); manager1.display(); System.out.println("Salary after adding the bonus is : " + manager1.addBonus()); manager2.display(); System.out.println("Salary after adding the bonus is : " Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

+ manager2.addBonus()); clerk1.display(); if (manager1.equals(clerk2) == false) System.out.println("Designations are different"); else System.out.println("Designations are same"); } } /** * Manager class that extends Employee and * overrides bonus component */ class Manager extends Employee { public Manager(String eID, String name, String dname, double salary) { super(eID, name, dname, salary, "Manager"); } /** * Adds bonus(different from that of an Employee) * component to the Manager's salary and returns the revised salary. */ @Override public double addBonus() { double bonus = 300; salary = salary + bonus; return (salary); } } /** * Clerk class that extends Employee and * overrides bonus component */ class Clerk extends Employee { public Clerk(String eID, String name, String dname, double salary) { super(eID, name, dname, salary, "Clerk"); } /** * Adds bonus(different from that of an Employee) * component to the Clerk's salary and returns the revised salary. */ @Override public double addBonus() { double bonus = 100; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

salary = salary + bonus; return (salary); } } 3. import java.util.Scanner; /** * SalaryDeduction.java * * This program uses the Employee class to create 4 objects of * Employee type and takes the user input for the number of days each * employee was not present in a month of 20 working days. And it * calculates the deductions made in the salary of each employee based * on the number of days the employee is absent. * * Created: Feb 3, 2016 * * @author * @version 1 */ import java.util.Scanner; public class SalaryDeduction { //calculate total deductions of the employee static double calculateDeduction(Employee emp, int present, int absent) { double absentPercentage = (absent / (double) (absent + present)); double deduction = emp.getSalary() * absentPercentage; return (deduction); } public static void main(String[] args) { double totalDeductions = 0; Scanner keyboard = new Scanner(System.in); Manager manager1 = new Manager("E001", "Mark", "HR", 15000); Manager manager2 = new Manager("E012", "Peter", "R&D", 15000); Clerk clerk1 = new Clerk("E056", "Samuel", "Accounts", 10000); Clerk clerk2 = new Clerk("E089", "John", "Accounts", 10000); Employee emp[] = { manager1, manager2, clerk1, clerk2 }; double deduction[] = new double[emp.length]; int present[] = new int[emp.length]; int absent[] = new int[emp.length]; for (int i = 0; i < emp.length; i++) { System.out.print("\nEnter the number of days Employee " Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

+ emp[i].employeeID + " is Present out of 20 :"); present[i] = keyboard.nextInt(); absent[i] = 20 - present[i]; deduction[i] = calculateDeduction(emp[i], present[i], absent[i]); totalDeductions += deduction[i]; } System.out.println("\nEmployee ID\tPresent\tAbsent\tDeductions"); for (int i = 0; i < emp.length; i++) { System.out.println(emp[i].employeeID + "\t\t" + present[i] + "\t" + absent[i] + "\t" + deduction[i]); } System.out.println("\n Total Deductions : " + totalDeductions); } } 4. /** * Question4Simulation.java * * This program simulates a 2D world with predators and prey. * The predators (doodlebugs) and prey (ants) inherit from the * Organism class that keeps track of basic information about each * critter (time ticks since last bred, position in the world). * * The 2D world is implemented as a separate class, World, * that contains a 2D array of pointers to type Organism. * * Created: Sat Mar 19 2005 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; /** * The World class stores data about the world by creating a * WORLDSIZE by WORLDSIZE array of type Organism. * null indicates an empty spot, otherwise a valid object * indicates an ant or doodlebug. To determine which, * invoke the virtual function getType of Organism that should return * ANT if the class is of type ant, and DOODLEBUG otherwise. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

*/ class World { public static final int WORLDSIZE = 20; private Organism[][] grid; // Array of organisms for each cell /** * Default constructor; Initialize the world to NULL's. */ public World() { // Initialize world to empty spaces int i,j; grid = new Organism[WORLDSIZE][WORLDSIZE]; for (i=0; i<WORLDSIZE; i++) { for (j=0; j<WORLDSIZE; j++) { grid[i][j]=null; } } } /** * getAt * Returns the entry stored in the grid array at x,y. * @param x X coordinate of the cell to retrieve * @param y Y coordinate of the cell to retrieve */ public Organism getAt(int x, int y) { if ((x>=0) && (x<World.WORLDSIZE) && (y>=0) && (y<World.WORLDSIZE)) return grid[x][y]; return null; } /** * setAt * Sets the entry in the grid array at x,y to the input organism * @param x X coordinate of the cell to store * @param y Y coordinate of the cell to store * @param org Organism object to store in the grid */ public void setAt(int x, int y, Organism org) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

{ if ((x>=0) && (x<World.WORLDSIZE) && (y>=0) && (y<World.WORLDSIZE)) { grid[x][y] = org; } } /** * Display * Displays the world in ASCII.text */ public void Display() { int i,j; System.out.println(); System.out.println(); for (j=0; j<World.WORLDSIZE; j++) { for (i=0; i<World.WORLDSIZE; i++) { if (grid[i][j]==null) System.out.print("."); else System.out.print(grid[i][j].getPrintableChar()); // X for Doodle, o for Ant } System.out.println(); } } /** * SimulateOneStep * This is the main routine that simulates one turn in the world. * First, a flag for each organism is used to indicate if it has moved. * This is because we iterate through the grid starting from the top * looking for an organism to move . If one moves down, we don't want * to move it again when we reach it. * First move doodlebugs, then ants, and if they are still alive then * we breed them. */ public void SimulateOneStep() { int i,j; // First reset all organisms to not moved for (i=0; i<World.WORLDSIZE; i++) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

for (j=0; j<World.WORLDSIZE; j++) { if (grid[i][j]!=null) grid[i][j].setMoved(false); } // Loop through cells in order and move if it's a Doodlebug for (i=0; i<World.WORLDSIZE; i++) for (j=0; j<World.WORLDSIZE; j++) { if ((grid[i][j]!=null) && (grid[i][j] instanceof Doodlebug)) { if (grid[i][j].getMoved() == false) { grid[i][j].setMoved(true); // Mark as moved grid[i][j].move(); } } } // Loop through cells in order and move if it's an Ant for (i=0; i<World.WORLDSIZE; i++) for (j=0; j<World.WORLDSIZE; j++) { if ((grid[i][j]!=null) && (grid[i][j] instanceof Ant)) { if (grid[i][j].getMoved() == false) { grid[i][j].setMoved(true); // Mark as moved grid[i][j].move(); } } } // Loop through cells in order and check if anyone is starving for (i=0; i<World.WORLDSIZE; i++) for (j=0; j<World.WORLDSIZE; j++) { // Kill off any doodlebugs that haven't eaten recently if ((grid[i][j]!=null) && (grid[i][j] instanceof Doodlebug)) { if (grid[i][j].starve()) { grid[i][j] = null; } } } // Loop through cells in order and check if we should breed for (i=0; i<World.WORLDSIZE; i++) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

for (j=0; j<World.WORLDSIZE; j++) { // Only breed organisms that have moved, since // breeding places new organisms on the map we // don't want to try and breed those if ((grid[i][j]!=null) && (grid[i][j].getMoved())) { grid[i][j].breed(); } } } } // World

/** * Definition for the Organism base class. * Each organism has a reference back to * the World object so it can move itself * about in the world. */ abstract class Organism { protected int x,y; // Position in the world protected boolean moved; // Bool to indicate if moved this turn protected int breedTicks; // Number of ticks since breeding protected World world; // Reference to the world object so we can update its // grid when we move around in the world /** * Constructors */ public Organism() { world = null; moved = false; breedTicks = 0; x=0; y=0; } public Organism(World world, int x, int y) { this.world = world; moved = false; breedTicks = 0; this.x=x; this.y=y; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

world.setAt(x,y,this); } /** * Accessor/Mutator for the Moved variable */ public boolean getMoved() { return moved; } public void setMoved(boolean moved) { this.moved = moved; } /** * Determines whether or not this organism should breed */ public abstract void breed(); /** * Determines how this organism should move */ public abstract void move(); /** * Determines if this organism starves */ public abstract boolean starve(); /** * Returns a symbol for the organism */ public abstract String getPrintableChar(); } // Organism

/** * Start with the Ant class */ class Ant extends Organism { public static final int ANTBREED = 3; /** Copyright © 2016 Pearson Education Ltd. All rights reserved.

// How many ticks to breed an ant


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

* Constructors */ public Ant() { super(); } public Ant(World world, int x, int y) { super(world,x,y); } /** * Ant breed * Increment the tick count for breeding. * If it equals our threshold, then clone this ant either * above, right, left, or below the current one. */ public void breed() // Must define this since virtual { breedTicks++; if (breedTicks == ANTBREED) { breedTicks = 0; // Try to make a new ant either above, left, right, or down if ((y>0) && (world.getAt(x,y-1)==null)) { Ant newAnt = new Ant(world, x, y-1); } else if ((y<World.WORLDSIZE-1) && (world.getAt(x,y+1)==null)) { Ant newAnt = new Ant(world, x, y+1); } else if ((x>0) && (world.getAt(x-1,y)==null)) { Ant newAnt = new Ant(world, x-1, y); } else if ((x<World.WORLDSIZE-1) && (world.getAt(x+1,y)==null)) { Ant newAnt = new Ant(world, x+1, y); } } } /** * Ant Move Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

* Look for an empty cell up, right, left, or down and * try to move there. */ public void move() // Must define this since virtual { // Pick random direction to move int dir = (int) (Math.random() * 4); // Try to move up, if not at an edge and empty spot if (dir==0) { if ((y>0) && (world.getAt(x,y-1)==null)) { world.setAt(x,y-1,world.getAt(x,y)); // Move to new spot world.setAt(x,y,null); y--; } } // Try to move down else if (dir==1) { if ((y<World.WORLDSIZE-1) && (world.getAt(x,y+1)==null)) { world.setAt(x,y+1,world.getAt(x,y)); // Move to new spot world.setAt(x,y,null); // Set current spot to empty y++; } } // Try to move left else if (dir==2) { if ((x>0) && (world.getAt(x-1,y)==null)) { world.setAt(x-1,y,world.getAt(x,y)); // Move to new spot world.setAt(x,y,null); // Set current spot to empty x--; } } // Try to move right else { if ((x<World.WORLDSIZE-1) && (world.getAt(x+1,y)==null)) { world.setAt(x+1,y,world.getAt(x,y)); // Move to new spot world.setAt(x,y,null); // Set current spot to empty x++; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

} } /** * Return false since an ant never starves */ public boolean starve() { return false; } /** * an Ant is represented by "o" */ public String getPrintableChar() { return "o"; } } // Ant

/** * Now define Doodlebug Class */ class Doodlebug extends Organism { public static final int DOODLEBREED = 8; public static final int DOODLESTARVE = 3; private int starveTicks;

// Ticks to breed // Ticks to starve

// Number of moves since last feeding

/** * Constructors */ public Doodlebug() { super(); starveTicks = 0; } public Doodlebug(World world, int x, int y) { super(world,x,y); starveTicks = 0; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

/** * Doodlebug breed * Creates a new doodlebug adjacent to the current cell * if the breedTicks meets the threshold. */ public void breed() // Must define this since virtual { breedTicks++; if (breedTicks == DOODLEBREED) { breedTicks = 0; // Try to make a new ant either above, left, right, or down if ((y>0) && (world.getAt(x,y-1)==null)) { Doodlebug newDoodle = new Doodlebug(world, x, y-1); } else if ((y<World.WORLDSIZE-1) && (world.getAt(x,y+1)==null)) { Doodlebug newDoodle = new Doodlebug(world, x, y+1); } else if ((x>0) && (world.getAt(x-1,y)==null)) { Doodlebug newDoodle = new Doodlebug(world, x-1, y); } else if ((x<World.WORLDSIZE-1) && (world.getAt(x+1,y)==null)) { Doodlebug newDoodle = new Doodlebug(world, x+1, y); } } } /** * Doodlebug move * Look up, down, left or right for a bug. If one is found, move there * and eat it, resetting the starveTicks counter. */ public void move() // Must define this since virtual { // Look in each direction and if a bug is found move there // and eat it. if ((y>0) && (world.getAt(x,y-1)!=null) && (world.getAt(x,y-1) instanceof Ant)) { world.setAt(x,y-1,this); // Move to spot world.setAt(x,y,null); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

starveTicks =0 ; y--; return;

// Reset hunger

} else if ((y<World.WORLDSIZE-1) && (world.getAt(x,y+1)!=null) && (world.getAt(x,y+1) instanceof Ant)) { world.setAt(x,y+1,this); // Move to spot world.setAt(x,y,null); starveTicks =0; // Reset hunger y++; return; } else if ((x>0) && (world.getAt(x-1,y)!=null) && (world.getAt(x-1,y) instanceof Ant)) { world.setAt(x-1,y,this); // Move to spot world.setAt(x,y,null); starveTicks =0 ; // Reset hunger x--; return; } else if ((x<World.WORLDSIZE-1) && (world.getAt(x+1,y)!=null) && (world.getAt(x+1,y) instanceof Ant)) { world.setAt(x+1,y,this); // Move to spot world.setAt(x,y,null); starveTicks =0 ; // Reset hunger x++; return; }

// If we got here, then we didn't find food. Move // to a random spot if we can find one. int dir = (int) (Math.random() * 4); // Try to move up, if not at an edge and empty spot if (dir==0) { if ((y>0) && (world.getAt(x,y-1)==null)) { world.setAt(x,y-1,world.getAt(x,y)); // Move to new spot world.setAt(x,y,null); y--; } } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

// Try to move down else if (dir==1) { if ((y<World.WORLDSIZE-1) && (world.getAt(x,y+1)==null)) { world.setAt(x,y+1,world.getAt(x,y)); // Move to new spot world.setAt(x,y,null); // Set current spot to empty y++; } } // Try to move left else if (dir==2) { if ((x>0) && (world.getAt(x-1,y)==null)) { world.setAt(x-1,y,world.getAt(x,y)); // Move to new spot world.setAt(x,y,null); // Set current spot to empty x--; } } // Try to move right else { if ((x<World.WORLDSIZE-1) && (world.getAt(x+1,y)==null)) { world.setAt(x+1,y,world.getAt(x,y)); // Move to new spot world.setAt(x,y,null); // Set current spot to empty x++; } } starveTicks++; // Increment starve tick since we didn't // eat on this turn }

/** * Doodlebug starve * Returns true or false if a doodlebug should die off * because it hasn't eaten enough food. */ public boolean starve() // Check if a doodlebug starves to death { // Starve if no food eaten in last DOODLESTARVE time ticks if (starveTicks > DOODLESTARVE) { return true; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

} else { return false; } } /** * Doodlebug represented by "X" */ public String getPrintableChar() { return "X"; } } // Doodlebug

class Question4Simulation { public static final int INITIALANTS = 100; public static final int INITIALBUGS = 5; // ====================== // main method // ====================== public static void main(String[] args) { String s; World w = new World(); Scanner scan = new Scanner(System.in); // Randomly create 100 ants int antcount = 0; while (antcount < INITIALANTS) { int x = (int) (Math.random() * World.WORLDSIZE); int y = (int) (Math.random() * World.WORLDSIZE); if (w.getAt(x,y)==null) // Only put ant in empty spot { antcount++; Ant a1 = new Ant(w,x,y); } } // Randomly create 5 doodlebugs int doodlecount = 0; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

while (doodlecount < INITIALBUGS) { int x = (int) (Math.random() * World.WORLDSIZE); int y = (int) (Math.random() * World.WORLDSIZE); if (w.getAt(x,y)==null) // Only put doodlebug in empty spot { doodlecount++; Doodlebug d1 = new Doodlebug(w,x,y); } } // Run simulation forever, until user cancels while (true) { w.Display(); w.SimulateOneStep(); System.out.println("Press enter for next step"); s = scan.nextLine(); } } } // Question4Simulation

5. /** * Figure.java * * * Created: Tue Jan 13 19:41:56 2004 * * @author Adrienne Decker * @version */ public class Figure { public Figure () { System.out.println("Creating a figure with no parameters."); } public void erase() { System.out.println("Call to Figure's erase method."); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

} public void draw() { System.out.println("Call to Figure's draw method."); } public void center() { System.out.println("Calling Figure's center method."); this.erase(); this.draw(); } }// Figure

/** * Rectangle.java * * * Created: Tue Jan 13 19:48:48 2004 * * @author Adrienne Decker * @version */ public class Rectangle extends Figure { private int _width; private int _height; public Rectangle () { System.out.println("Creating Rectangle Class with no parameters."); _width = 0; _height = 0; } public Rectangle(Rectangle other) { System.out.println("Creating Rectangle Class from another " + "Rectangle."); _width = other._width; _height = other._height; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

public Rectangle(int width, int height) { System.out.println("Creating Rectangle Class given width and " + "height."); _width = width; _height = height; } public void draw() { System.out.println("Calling Rectangle's draw method."); } public void erase() { System.out.println("Calling Rectangle's erase method."); } }// Rectangle

/** * Triangle.java * * * Created: Tue Jan 13 19:44:15 2004 * * @author Adrienne Decker * @version */ public class Triangle extends Figure{ private int _base; private int _height; public Triangle () { System.out.println("Creating Triangle Class with no parameters."); _base = 0; _height = 0; } public Triangle(Triangle other) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

System.out.println("Creating Triangle Class from another Triangle."); _base = other._base; _height = other._height; } public Triangle(int base, int height) { System.out.println("Creating Triangle Class given base and height."); _base = base; _height = height; } public void draw() { System.out.println("Calling Triangle's draw method."); } public void erase() { System.out.println("Calling Triangle's erase method."); } }// Triangle /** * Question5.java * * * Created: Fri Jan 09 20:07:39 2004 * * @author Adrienne Decker * @version */ public class Question5 { public static void main(String[] args) { Figure f1 = new Figure(); f1.draw(); f1.erase(); f1.center(); Triangle t1 = new Triangle(); t1.draw(); t1.erase(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

t1.center(); Rectangle r1 = new Rectangle(); r1.draw(); r1.erase(); r1.center(); } } // Question5

6. /** * Figure.java * * * Created: Tue Jan 13 19:41:56 2004 * * @author Adrienne Decker * @version */ public class Figure { public Figure () { } public Figure(Figure figure) { } public void erase() { for ( int i = 0; i < 15; i++) { System.out.println(); } // end of for () } public void draw() { } public void center() { this.erase(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

this.draw(); } }// Figure /** * Rectangle.java * * * Created: Tue Jan 13 19:48:48 2004 * * @author Adrienne Decker * @version */ public class Rectangle extends Figure { private int _width; private int _height; public Rectangle () { _width = 0; _height = 0; } public Rectangle(Rectangle other) { _width = other._width; _height = other._height; } public Rectangle(int width, int height) { _width = width; _height = height; } public void draw() { for ( int i = 0; i < _height; i++) { for ( int j = 0; j < _width; j++) { System.out.print("*"); } // end of for () System.out.println(); } // end of for () Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

} }// Rectangle /** * Triangle.java * * * Created: Tue Jan 13 19:44:15 2004 * * @author Adrienne Decker * @version */ public class Triangle extends Figure{ private int _height; public Triangle () { _height = 0; } public Triangle(Triangle other) { super(other); _height = other._height; } public Triangle(int height) { _height = height; } public void draw() { for ( int i = 1; i <= _height; i++ ) { for ( int j = 0; j < i; j++) { System.out.print("*"); } // end of for () System.out.println(); } // end of for () } public void erase() Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

{ super.erase(); } }// Triangle /** * Question6.java * * * Created: Tue Jan 13 20:02:12 2004 * * @author Adrienne Decker * @version */ public class Question6 { public static void main(String[] args) { Triangle t1 = new Triangle(5); t1.center(); Rectangle r1 = new Rectangle(6, 8); r1.center(); } } // Question6

7. /** * MultiItemSale.java * * * Created: Tue Jan 13 20:07:29 2004 * * @author Adrienne Decker * @version */ public class MultiItemSale { private Sale[] _sales; private int _curr; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

public MultiItemSale () { _sales = new Sale[10]; _curr = 0; } public void insertSale(Sale insert) { if ( _curr > _sales.length) { this.resize(); } // end of if () _sales[_curr] = insert; _curr++; } public void resize() { int currSize = _sales.length; currSize *= 2; Sale[] newSales = new Sale[currSize]; for ( int i = 0; i < _curr; i++) { newSales[i] = _sales[i]; } // end of for () _sales = newSales; } public Sale getSale(int index) { return _sales[index]; } public double computeTotal() { double result = 0.0; for ( int i = 0; i < _curr; i++ ) { result = result + _sales[i].bill(); } // end of for () return result; } //Students should be encouraged to write an equals, and // clone method for completeness Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

public String toString() { String result = ""; for ( int i = 0; i < _curr; i++) { result += _sales[i] + "\n"; } // end of for () return result; } }// MultiItemSale

/** * Question7.java * * Created: Fri Jan 09 20:07:48 2004 * Modified: Sat Mar 19 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ import java.util.Scanner; public class Question7 { public static void main(String[] args) { MultiItemSale ms1 = new MultiItemSale(); Scanner keyboard = new Scanner(System.in); while ( true ) { System.out.println("Enter S for a sale, D for discounted " + "sale or Q to quit"); String first = keyboard.nextLine(); if ( first.charAt(0) == 'Q' || first.charAt(0) == 'q') { break; } // end of if () else if ( first.charAt(0) == 'S' || first.charAt(0) == 's') { System.out.println("Enter name of item: "); String item = keyboard.nextLine(); if ( item == null ) { System.err.println("Null string"); System.exit(1); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

} // end of if () System.out.println("Enter item's price: "); double temp = keyboard.nextDouble(); keyboard.nextLine(); // Eat newline if ( temp < 0 ) { System.err.println("Negative price."); System.exit(1); } // end of if () Sale s1 = new Sale(item, temp); ms1.insertSale(s1); } // end of if () else if ( first.charAt(0) == 'D' || first.charAt(0) == 'd' ) { System.out.println("Enter name of item: "); String item = keyboard.nextLine(); if ( item == null ) { System.err.println("Null string"); System.exit(1); } // end of if () System.out.println("Enter item's price: "); double temp = keyboard.nextDouble(); keyboard.nextLine(); // Eat newline if ( temp < 0 ) { System.err.println("Negative price."); System.exit(1); } // end of if () System.out.println("Enter percentage discount as a double." + "\nFor example 6.5 for 6.5%"); double tempDis = keyboard.nextDouble(); keyboard.nextLine(); // Eat newline if ( tempDis < 0 ) { System.err.println("Negative discount."); System.exit(1); } // end of if () DiscountSale d1 = new DiscountSale(item, temp, tempDis); ms1.insertSale(d1); } // end of else } System.out.println("Total bill: $" + ms1.computeTotal());

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

} } // Question7

8. /** * Question 8 * * Modification of the solution to PP 7.8 to make * the class abstract. * */ /** Class for basic pet records: name, age, and weight. */ public abstract class Pet { private String name; private int age;//in years private double weight;//in pounds public String toString( ) { return ("Name: " + name + " Age: " + age + " years" + "\nWeight: " + weight + " pounds"); } public Pet(String initialName, int initialAge, double initialWeight) { name = initialName; if ((initialAge < 0) || (initialWeight < 0)) { System.out.println("Error: Negative age or weight."); System.exit(0); } else { age = initialAge; weight = initialWeight; } } public void set(String newName, int newAge, double newWeight) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

{ name = newName; if ((newAge < 0) || (newWeight < 0)) { System.out.println("Error: Negative age or weight."); System.exit(0); } else { age = newAge; weight = newWeight; } } public Pet(String initialName) { name = initialName; age = 0; weight = 0; } public void setName(String newName) { name = newName; } public Pet(int initialAge) { name = "No name yet."; weight = 0; if (initialAge < 0) { System.out.println("Error: Negative age."); System.exit(0); } else age = initialAge; } public void setAge(int newAge) { if (newAge < 0) { System.out.println("Error: Negative age."); System.exit(0); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

else age = newAge; } public Pet(double initialWeight) { name = "No name yet"; age = 0; if (initialWeight < 0) { System.out.println("Error: Negative weight."); System.exit(0); } else weight = initialWeight; } public void setWeight(double newWeight) { if (newWeight < 0) { System.out.println("Error: Negative weight."); System.exit(0); } else weight = newWeight; } public Pet( ) { name = "No name yet."; age = 0; weight = 0; } public String getName( ) { return name; } public int getAge( ) { return age; } public double getWeight( ) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

{ return weight; } // Must be overridden in subclass; public abstract double acepromazine(); // Must be overriden in subclass; public abstract double carprofen(); } public class Dog extends Pet { public Dog() { super(); } public Dog(String initialName, int initialAge, double initialWeight) { super(initialName, initialAge, initialWeight); } public String toString() { return "Type: Dog. " + super.toString(); } public double acepromazine() { return (getWeight() / 2.2) * (0.03 / 10); } public double carprofen() { return (getWeight() / 2.2) * (0.5 / 10); } } public class Cat extends Pet { public Cat() { super(); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

public Cat(String initialName, int initialAge, double initialWeight) { super(initialName, initialAge, initialWeight); } public String toString() { return "Type: Cat. " + super.toString(); } public double acepromazine() { return (getWeight() / 2.2) * (0.002 / 10); } public double carprofen() { return (getWeight() / 2.2) * (0.025 / 10); } }

import java.util.Scanner; public class PetDemo { public static void main(String[] args) { Pet[] pets = new Pet[4]; pets[0] = new Cat("Garfield", 10, 20); pets[1] = new Cat("Mr. Whiskers", 3, 10); pets[2] = new Dog("Odie", 8, 45); pets[3] = new Dog("Rex", 11, 65); // Output pet info and dosage for (int i = 0; i < pets.length; i++) { System.out.println(pets[i].toString()); System.out.printf("Acepromazine: %.4f\n", pets[i].acepromazine()); System.out.printf("Carprofen: %.4f\n", pets[i].carprofen()); System.out.println(); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

} } // Question 8

/** * Question 9 * * Overloading the nextInt method of the Random class to sneak in a loaded die. * */ import java.util.Random; public class LoadedDice extends Random { public LoadedDice() { super(); // Invoke constructor for Random class } // Here we override the nextInt method of the parent public int nextInt(int num) { // Get a random number from 0-1 // by invoking the parent's random int r = super.nextInt(2); // With a 50% chance return the biggest number // possible, otherwise return a number from 0 to num-1 // with an equal probability if (r==0) return num-1; else return super.nextInt(num); }

public static void printDiceRolls(Random randGenerator) { for (int i = 0; i < 100; i++) { System.out.println(randGenerator.nextInt(6) + 1); } } public static void main(String[] args) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 8, Instructor’s Manual

// This version will output lots of numbers from 1-6 Random randGenerator = new Random(); printDiceRolls(randGenerator); // This version will output lots of 6's // If there was an actual game of some sort based on rolling dice // and we somehow substituted a LoadedDice object // in place of a normal Random object then we could influence the outcome // by changing the distribution of numbers returned by nextInt(). LoadedDice loadedRandom = new LoadedDice(); printDiceRolls(loadedRandom); } } // Question 9

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

Chapter 9

Exception Handling Key Terms throw exception handle exception try block throw statement throwing an exception catch block handling an exception exception handler catch block parameter Exception constructors throws clause declaring an exception catch or declare rule checked and unchecked exceptions event-driven programming firing an event

Brief Outline 9.1 Exception Handling Basics try-throw-catch Mechanism Exception classes Exception classes from Standard Packages Defining Exception Classes Multiple catch Blocks 9.2 Throwing Exceptions in Methods Throwing an Exception in a Method Declaring Exceptions in a throws Clause Exceptions to the Catch or Declare Rule throws Clause in Derived Classes When to Use Exceptions Event-Driven Programming 9.3 More Programming Techniques for Exception Handling The finally Block Rethrowing an Exception The AssertionError Class Exception Handling with the Scanner Class ArrayIndexOutOfBoundsException

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

Teaching Suggestions This chapter discusses using Exceptions for handling errors in programs. The chapter discusses what exceptions are, how to create them, how to use them, and how to handle them when they are thrown by a program. After covering this material, students should be able to use Exceptions in their programs when errors occur. Key Points throw Statement. When an error occurs in a program, you need to throw an exception using the keyword throw. At this time an Exception object will also be created and then execution of the program will stop at that point and go back to the caller looking for a catch block. The getMessage Method. In a catch block, we can access the message that is contained in an Exception that is thrown. This message is set when the exception is created and thrown and should give some meaningful information about what error has occurred. catch Block Parameter. When a catch block is created, it must specify what type of exception it will catch and gives that exception a name (identifier) that will be used inside of the catch block when referring to the exception that was caught. try-throw--catch. These three keywords represent the entire mechanism for using exceptions in Java. We put code that might generate an exception into a try block. If there is a case to throw an exception, it happens from within this block. The try is coupled with a catch that will handle the case when then exception is thrown. The Class Exception. Exceptions are object inside Java. All exceptions are subclasses of the class Exception and it is common practice to not use the Exception class when throwing exceptions, but rather the subclasses that are specialized for different possible exceptions. Exception Object Characteristics. The two important things that an exception carries are the type of the exception and the message about the error. Programmer Defined Exception Classes. A programmer can define their own exceptions. These exceptions should extend an already defined exception, or the class Exception itself. throws Clause. When your method will generate an exception, you need to specify this when creating the method by using the throws keyword and the type of exception or exceptions thrown. Catch or Declare Rule. If an exception will be generated inside a method, you must either use a catch block and catch it or declare that the method throws the exception. The exceptions that must follow these rules are called checked exceptions. Display 9.10 gives a list of the checked exceptions, and which exceptions are unchecked and should not be caught.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

Throwing and Exception Can End a Method. If an exception is thrown from inside a method and that method does not catch the exception, the method’s execution is terminated. What Happens if an Exception is Never Caught? If you throw an exception and never have a catch block for the exception, the program will terminate. A good program will have a catch block for all possible exceptions thrown. Checked and Unchecked Exceptions. Exceptions that are subject to the catch or declare rule are called checked exceptions. These are exceptions that are subclasses of Exception or Throwable are checked. All other exceptions are considered unchecked and could be viewed as errors, and in fact all subclasses of Error fall into this category. When to Throw an Exception. When to use an exception is one question that students usually ask. Exceptions should be thrown when there are exceptional cases, or possible error conditions in a program that we want handled in a specific way.

Tips Preserve getMessage. Even if you create an exception class that takes other parameters other than a String when created, you still should preserve the ability for the new exception to be created with a String as a parameter, even if you do not use the String. If you do not use the String, you should simply call the superclass’ constructor with the String. An Exception Class Can Carry a Message of Any Type. When you create your own exception classes that extend from Exception, you can add instance variables if you choose. Therefore, you can create accessors for those instance variables similar to getMessage that return the appropriate value. Exception Controlled Loops. You can use a loop to keep repeating code that might cause an error, especially when the exceptions could be generated due to user input. For example, if a user inputs an improper number and a NumberFormatException is generated, you may want to give the user more tries to input a number. Pitfalls Catch the More Specific Exception First. If your catch block is catching multiple exceptions, the order in which they are caught is important. You should catch more specific exceptions (subclasses) before the more generic ones (superclasses). Therefore, catching Exception should always be the last catch block in any sequence. Nested try-catch Blocks. You can nest try-catch blocks. However, it is better practice if this is needed to put the inner try-catch into another method. Examples A Toy Example of Exception Handling. In this example we see a simple use of exceptions by first showing how this would be handled without using them and then how and where they would be inserted into the program. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

Programming Projects Answers 1. /** * Question1Average.java * * This program calculates the average of N numbers and throws * an exception if a negative number is entered for N. If any * exception occurs while entering a number, the user will be prompted * for the number again. * * Created: Sat Mar 19 2005 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; public class Question1Average { public static void main(String[] args) { // Variable declarations Scanner scan = new Scanner(System.in); int n = 0; int sum = 0; double average; boolean error; // Loop until there is no error do { try { error = false; // Assume no error System.out.println("How many numbers do you want to enter?"); n = scan.nextInt(); if (n <= 0 ) throw new Exception("Number must be greater than 0."); } catch (Exception e) // Catch any exception and print the error message { error = true; // Set error flag if an exception occurs System.out.println(e.getMessage()); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

} while (error); // Loop through each number and calculate the average for (int i=0; i<n; i++) { // Repeat input as long as there is an error do { try { error = false; // Assume no error System.out.println("Enter number " + (i+1)); int num = scan.nextInt(); sum += num; } catch (Exception e) { // Set error flag if an exception occurs error = true; System.out.println("Error, please enter the number again."); // Read newLine remaining from nextInt String temp = scan.nextLine(); } } while (error); } average = (double) sum / n; System.out.println("\nThe average is " + average); } } // Question1Average

2. /** * BankAccount.java * * This class lets you create a Bank Account by letting the user enter * the customerID, account number and balance in the account by * considering the following validation rules. * <ol> * <li>Customer ID must be a string that starts with an alphabet and * followed by 3 digits</li> * <li>Account number must be a 5-digit long integer</li> * <li>Balance must be a number greater than or equal to 1000</li> * </ol> Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

* * Created: Feb 3, 2016 * * @author * @version 1 */ import java.util.Scanner; public class BankAccount { String customerID; int accountNo; double balance; //Read user input data public void inputData() { Scanner keyboard = new Scanner(System.in); boolean flag = false; do { //Try-Catch block for validating customer id try { System.out.print("Enter customer ID : "); customerID = keyboard.next(); if (customerID.length() != 4 || !Character.isLetter(customerID.charAt(0)) || !Character.isDigit(customerID.charAt(1)) || !Character.isDigit(customerID.charAt(2))) throw new Exception("Customer ID incorrect"); else flag = true; } catch (Exception e) { System.out.println(e.getMessage()); System.out.println("Input Again\n"); flag = false; } } while (!flag); flag = false; do { //Try-Catch block for validating account number try { System.out.print("Enter account no : "); accountNo = keyboard.nextInt(); if (accountNo < 10000 || accountNo > 99999) throw new Exception("Account No is incorrect"); else flag = true; } catch (Exception e) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

System.out.println(e.getMessage()); System.out.println("Input Again\n"); flag = false; } } while (!flag); flag = false; do { //Try-Catch block for validating account balance try { System.out.print("Enter balance : "); balance = keyboard.nextDouble(); if (balance <= 1000) throw new Exception("Minimum balance is not maintained"); else flag = true; } catch (Exception e) { System.out.println(e.getMessage()); System.out.println("Input Again\n"); flag = false; } } while (!flag); } public static void main(String[] args) { BankAccount myAccount = new BankAccount(); myAccount.inputData(); System.out.println("Successfully created bank account!"); } } 3. import java.util.Scanner; /** * SavingBankAccount.java * * The class extends BankAccount class and defines a custom exception * that is thrown when the user tries to deposit or withdraw amount * that is not allowed for his/her account * * Created: Feb 3, 2016 * * @author * @version 1 */ import java.util.Scanner; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

public class SavingBankAccount extends BankAccount { /** * This method deposits the specified amount to the user's account if * the new balance greater than 5000 * * @param amount * Amount to be added to the balance */ public void deposit(double amount) { try { if (balance + amount > 5000) throw new BalanceCheckException("Balance is going too high"); else { balance += amount; System.out.println("After deposit the balance is : " + balance); } } catch (Exception e) { System.out.println(e.getMessage()); } } /** * Method to withdraw a specified amount from the account only if * the new balance is not falling below 1000 * * @param amount * Amount to be withdrawn */ public void withdrawl(double amount) { try { if (balance - amount < 1000) throw new BalanceCheckException("Balance is going too low"); else { balance -= amount; System.out.println("After withdrawal balance is : " + balance); } } catch (Exception e) { System.out.println(e.getMessage()); } } public static void main(String[] args) { double amount; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

Scanner keyboard = new Scanner(System.in); SavingBankAccount account = new SavingBankAccount(); account.inputData(); System.out.print("\nEnter amount for deposit : "); amount = keyboard.nextDouble(); account.deposit(amount); System.out.print("\nEnter amount for withdrawal : "); amount = keyboard.nextDouble(); account.withdrawal(amount); } } /** * * Exception that is used to show error message when amount exceeds or * falls below the boundary values defined */ class BalanceCheckException extends Exception { String message; public BalanceCheckException(String message) { super(message); } } class SavingBankAccount{ String customerID; int accountNo; double balance; public void deposit(double amount){ try{ if(balance + amount > 5000) throw new BalanceCheckException("Balance is going too high"); else{ balance += amount; System.out.println("After deposit balance is : "+balance); } }catch(Exception e){ System.out.println(e.getMessage()); } } public void withdrawal(double amount){ try{ if(balance - amount < 1000) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

throw new BalanceCheckException("Balance is going too low"); else{ balance -= amount; System.out.println("After withdrawal balance is : "+balance); } }catch(Exception e){ System.out.println(e.getMessage()); } } public void inputData(){ boolean flag; do{ flag=true; Scanner keyboard=new Scanner(System.in); System.out.print("Enter customer ID : "); customerID=keyboard.next(); System.out.print("Enter account no : "); accountNo=keyboard.nextInt(); System.out.print("Enter balance : "); balance=keyboard.nextDouble(); try{ if(customerID.length()!=4 || !Character.isLetter(customerID.charAt(0)) !Character.isDigit(customerID.charAt(1)) || !Character.isDigit(customerID.charAt(2))) throw new Exception("Customer ID incorrect"); if(accountNo < 10000 || accountNo > 99999) throw new Exception("Account No is incorrect"); if(balance <= 1000) throw new Exception("Minimum balance is not maintained"); }catch(Exception e){ System.out.println(e.getMessage()); System.out.println("Input Again\n"); flag=false; } }while(flag==false); } public static void main(String[] args){ double amount; Scanner keyboard=new Scanner(System.in); SavingsBankAccount myAccount = new SavingsBankAccount(); myAccount.inputData(); System.out.print("\nEnter amount for deposit : "); amount=keyboard.nextDouble(); myAccount.deposit(amount); System.out.print("\nEnter amount for withdrawal : "); Copyright © 2016 Pearson Education Ltd. All rights reserved.

||


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

amount=keyboard.nextDouble(); myAccount.withdrawal(amount); } } 4. /** * Question4Fraction.java * * This program examines throwing an Exception from the Fraction * class if the denominator is set to zero. * * Created: Sat Mar 19 2005 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; import java.util.InputMismatchException; /** * This class is used to catch a division by zero exception * in the event that the denominator of a fraction is set to zero. */ class DenominatorIsZeroException extends Exception { public DenominatorIsZeroException() { super("Denominator should not be set to zero."); } public DenominatorIsZeroException(String message) { super(message); } } // DenominatorIsZeroException /** * A class to represent fractions, but throws exceptions if * we attempt to set the denominator to zero */ public class Question4Fraction { private int numerator; // Store numerator and denominator Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

private int denominator; /** * Default constructor; Initialize num=0, * denominator=1 to avoid divide by zero */ public Question4Fraction() { numerator = 0; denominator = 1; } /** * Fraction constructor. * * @param num The initial numerator * @param denom The initial denominator */ public Question4Fraction(int num, int denom) throws DenominatorIsZeroException { numerator = num; if (denom==0) throw new DenominatorIsZeroException(); denominator = denom; }

/** * Finds greatest common divisor of numerator and denominator * by brute force (start at larger of two, work way down to 1) * * @return The greatest common denominator * of the numerator and denominator */ private int gcd() { int g; // candidate for gcd, start at the smaller of the // numerator and denominator if (numerator > denominator) { g = denominator; } else { g = numerator; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

} // Work down to 1, testing to see if both numerator and denominator // can be divided by g. If so, return it. while (g>1) { if (((numerator % g)==0) && ((denominator % g)==0)) return g; g--; } return 1; } /** * Mutator to set the numerator. * * @param n The new value for the numerator. */ public void setNumerator(int n) { numerator = n; } /** * Mutator to set the denominator. * * @param d The new value for the denominator * throws an exception, DenominatorIsZeroException, if d=0 */ public void setDenominator(int d) throws DenominatorIsZeroException { if (d==0) throw new DenominatorIsZeroException(); // Don't allow zero denominator = d; } /** * Accessor to retrieve the fraction's value as a double. * * @return The fraction's value as a double. */ public double getDouble() { return (double) numerator / denominator; } /** Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

* Output the fraction with no reduction. */ public void DisplayFraction() { System.out.println(numerator + "/" + denominator); } /** * Returns true if the two fractions are equal, false otherwise. * It computes the gcd for both fractions and determines if the * numerator and denominator are equivalent. */ public boolean equals(Question4Fraction otherFraction) { int gcdMe, gcdOther; gcdMe = gcd(); gcdOther = otherFraction.gcd(); return (((numerator/gcdMe) == (otherFraction.numerator/gcdOther)) && ((denominator/gcdMe) == (otherFraction.denominator/gcdOther))); } /** * Output the reduced fraction to the console. * Uses a private greatest-common-denominator method to * reduce the fraction. */ public void outputReducedFraction() { int g; g = gcd(); System.out.println(numerator / g + " / " + denominator / g); return; }

/** * This is the main method. It allows the user to enter a numerator and * denominator and outputs the reduced fraction, but catches * an exception if the denominator is zero. */ public static void main(String[] args) { Question4Fraction f = new Question4Fraction(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

int numerator, denominator; String s; Scanner scan = new Scanner(System.in); do { try { System.out.println("Enter a numerator:"); numerator = scan.nextInt(); System.out.println("Enter a denominator:"); denominator = scan.nextInt(); f.setNumerator(numerator); f.setDenominator(denominator); System.out.print("The fraction reduced is "); f.outputReducedFraction(); } catch (DenominatorIsZeroException e) // Catch denominator = 0 { System.out.println("The denominator should not be set to zero."); } catch (InputMismatchException e) // Catch if user enters non-integer { System.out.println("You must enter an integer. Try again."); } catch (Exception e) // Catch anything else { System.out.println("Exception: " + e.getMessage()); } System.out.println(); scan.nextLine(); // Skip newline System.out.println("Enter 'Y' to go again, anything else to exit."); s = scan.nextLine(); } while (s.equals("Y")); } } // Question4Fraction

5. /** * MonthException.java * * * Created: Sat Jan 10 20:50:48 2004 Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

* * @author Adrienne Decker * @version */ public class MonthException extends Exception{

}// MonthException /** * DayException.java * * * Created: Sat Jan 10 20:51:40 2004 * * @author Adrienne Decker * @version */ public class DayException extends Exception { }// DayException /** * YearException.java * * * Created: Sat Jan 10 20:52:04 2004 * * @author Adrienne Decker * @version */ public class YearException extends Exception { }// YearException

/** * Date.java * * * Created: Sat Jan 10 20:48:04 2004 Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

* * @author Adrienne Decker * @version */ import java.util.StringTokenizer; import java.util.NoSuchElementException; public class Date { private int _month; private int _day; private int _year; private String _formattedDate; public Date(String rawDate) { StringTokenizer st = new StringTokenizer(rawDate, "/"); try { _month = Integer.parseInt(st.nextToken()); _day = Integer.parseInt(st.nextToken()); _year = Integer.parseInt(st.nextToken()); } catch (NoSuchElementException nse) { } } public void parseDate() throws MonthException, DayException, YearException { if (_month < 1 || _month > 12) { throw new MonthException(); } // end of if () switch (_month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: if (_day < 1 || _day > 31) throw new DayException(); break; case 2: if (leapYear(_year)) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

if (_day < 1 || _day > 29) throw new DayException(); } else { if (_day < 1 || _day > 28) throw new DayException(); } // end of if () break; case 4: case 6: case 11: if (_day < 1 || _day > 30) throw new DayException(); break; default: break; } // end of switch ()

if (_year < 1000 || _year > 3000) { throw new YearException(); } // end of if () _formattedDate = getMonthValue(_month) + " " + _day + ", " + _year; } public void setMonth(int month) { _month = month; } public void setDay(int day) { _day = day; } public void setYear(int year) { _year = year; } public String getFormattedDate() { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

return _formattedDate; } private boolean leapYear(int year) { return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } private String getMonthValue(int month) { switch (_month) { case 1: return "January"; case 2: return "February"; case 3: return "March"; case 4: return "April"; case 5: return "May"; case 6: return "June"; case 7: return "July"; case 8: return "August"; case 9: return "September"; case 10: return "October"; case 11: return "November"; case 12: return "December"; } return ""; } }// Date

/** * Question5.java * * Created: Fri Jan 09 20:07:56 2004 * Modified: Sat Mar 19 2005, Kenrick Mock Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

* * @author Adrienne Decker * @version 2 */ import java.util.Scanner; public class Question5 { private static Date date; private static Scanner keyboard = new Scanner(System.in); private static boolean convertDate() { String dateInput; try { date.parseDate(); return true; } catch (MonthException me) { System.out.println("Invalid month. Reenter a valid month: "); date.setMonth(keyboard.nextInt()); } catch (DayException de) { System.out.println("Invalid day. Reenter a valid day: "); date.setDay(keyboard.nextInt()); } catch (YearException ye) { System.out.println("Invalid year. Reenter a valid year: "); date.setYear(keyboard.nextInt()); } return false; } public static void main(String[] args) { System.out.println("Enter date to parse (MM/DD/YYYY format):"); String dateInput = keyboard.nextLine(); date = new Date(dateInput); while (!convertDate()) { } // end of while () System.out.println("Parsed date: " + date.getFormattedDate()); } } // Question5 Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

6. /** * UnknownOperatorException.java * * * Created: Sat Jan 10 22:21:42 2004 * * @author Adrienne Decker * @version */ public class UnknownOperatorException extends Exception { public UnknownOperatorException(String msg) { super(msg); } }// UnknownOperatorException

/** * Question6.java * * Created: Fri Jan 09 20:08:02 2004 * Modified: Sat Mar 19 2005, Kenrick Mock * * @author Adrienne Decker * @version */ import java.util.Scanner; public class Question6 { private static double doCalculation(String input, double prevRes) throws UnknownOperatorException { if (input.equals("")) { throw new UnknownOperatorException("Must specify an operation."); } // end of if ()

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

String op = input.substring(0, 1); if (!op.equals("+") && !op.equals("-") && !op.equals("*") && !op.equals("/") && !op.equals("%")) { throw new UnknownOperatorException(op + " is an unknown operation."); } // end of if () double value = Double.parseDouble(input.substring(1, input.length())); if (op.equals("+")) { System.out.println("result " + op + value + " = " + (prevRes + value)); return prevRes + value; } // end of if () else if (op.equals("-")) { System.out.println("result " + op + value + " = " + (prevRes - value)); return prevRes - value; } // end of if () else if (op.equals("*")) { System.out.println("result " + op + value + " = " + prevRes * value); return prevRes * value; } // end of if () else if (op.equals("/")) { System.out.println("result " + op + value + " = " + prevRes / value); return prevRes / value; } // end of if () else if (op.equals("%")) { System.out.println("result " + op + value + " = " + prevRes % value); return prevRes % value; } // end of if () return 0; } public static void main(String[] args) { String input; String againInput; double curResult = 0.0; Scanner keyboard = new Scanner(System.in);

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

System.out.println("Calculator is on."); do { System.out.println("result = 0.0"); do { input = keyboard.nextLine(); try { if (input.equalsIgnoreCase("r")) { System.out.println("final result = " + curResult); } else { curResult = doCalculation(input, curResult); System.out.println("updated result == " + curResult); } // end of else } catch (UnknownOperatorException uoe) { System.out.println(uoe.getMessage()); } } while (!input.equalsIgnoreCase("r")); System.out.println("Again? (y/n)"); againInput = keyboard.nextLine(); curResult = 0.0; } while (!againInput.substring(0,1).equalsIgnoreCase("n")); } } // Question6

7. /** * Question 7 * * Rewrite of the Account class using * exceptions instead of returning -1 for an * error condition. * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

* Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ class InsufficientFundsException extends Exception { public InsufficientFundsException() { super("Insufficient funds to withdraw this amount."); } } class NonPositiveNumberException extends Exception { public NonPositiveNumberException() { super("Deposit amount must be positive."); } } public class Account { private double balance; public Account() { balance = 0; } public Account(double initialDeposit) { balance = initialDeposit; } public double getBalance() { return balance; } // returns new balance or -1 if error public double deposit(double amount) throws NonPositiveNumberException { if (amount > 0) balance += amount; else //return -1; // Code indicating error throw new NonPositiveNumberException(); return balance; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

} // returns new balance or -1 if invalid amount public double withdraw(double amount) throws InsufficientFundsException { if ((amount > balance) || (amount < 0)) //return -1; throw new InsufficientFundsException(); else balance -= amount; return balance; }

public static void main(String[] args) { try { Account savings = new Account(100); savings.withdraw(50); savings.deposit(-2); System.out.println(savings.getBalance()); savings.withdraw(60); System.out.println(savings.getBalance()); } catch (NonPositiveNumberException e) { System.out.println(e); } catch (InsufficientFundsException e) { System.out.println("Not enough money."); System.out.println(e); } catch (Exception e) { System.out.println(e.toString()); } } } // Question 7

8. /** * Question 8 * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 9, Instructor’s Manual

* Testing the exceptions thrown by sort in java.util.Arrays * * Created: Thu May 21 2015 * * @author Kenrick Mock * @version 1 */ import java.util.Arrays; public class Question8 { public static void main(String[] args) { int[] testArray = {3, 4, 100, 1, 23}; // Sorts from index 0 (inclusive) to index 5 (exclusive) Arrays.sort(testArray, 0, testArray.length); // Sort entire array // Output the array System.out.println("Successful sort"); for (int i = 0; i < testArray.length; i++) System.out.println(testArray[i]); // Exceptional cases System.out.println(); System.out.println("Exceptional case: fromIndex > toIndex"); try { Arrays.sort(testArray, 2, 1); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } System.out.println(); System.out.println("Exceptional case: fromIndex < 0 or toIndex > a.length"); try { Arrays.sort(testArray, -100, 2); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(e.toString()); } } } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

Chapter 10

File I/O Key Terms stream input stream output stream System.out System.in text file ASCII file binary file PrintWriter java.io opening a file FileOutputStream file name reading the file name FileNotFoundException println, print, and printf buffered buffer appending opening a file BufferedReader opening a file readLine read method path names using \. \\. or / redirecting output abstract name opening a file writeInt writeChar writeUTF for Strings closing a binary file reading multiple types closing a binary files EOFException Serializable interface writeObject readObject Serializable class instance variable Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

file pointer opening a file

Brief Outline 10.1 Introduction to File I/O Streams Text Files and Binary Files 10.2 Text Files Writing to a Text File Appending to a Text File Reading from a Text File Reading a Text File Using Scanner Testing for the End of a Text File with Scanner Reading a Text File Using BufferedReader Testing for the End of a Text File with BufferedReader Path Names Nested Constructor Invocations System.in, System.out, System.err 10.3 The File Class Programming with the File Class 10.4 Binary Files Writing Simple Data to a Binary File UTF and writeUTF Reading Simple Data from a Binary File Checking for the End of a Binary File Binary I/O of Objects The Serializable Interface Array Objects in Binary Files 10.5 Random Access to Binary Files Reading and Writing to the Same File

Teaching Suggestions This chapter discusses using files for reading and writing information. The first sections deal with text files and inputting and outputting information using just text. This is accomplished in Java using streams. Reading from a file and reading from the console are actually not that much different because both are treated as streams. With the introduction of the Scanner class in Java 5, there is another new way to process files and this chapter discusses both the use of BufferedReader and Scanner. The last two sections of the chapter are optional and discuss how to use binary files and read and write entire objects to a file. These sections introduce the Serializable interface for allowing the reading and writing of objects.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

Key Points Streams. Streams are flows of date. There are input streams and output streams. Streams are the method used for console I/O as well as file I/O. Text Files Versus Binary Files. Text files are those which are written with an editor and use characters that are commonly recognizable to humans. Binary files are those that are easily read by the machine. A type of file that would be a binary file are the .class files that are generated when we compile a .java file. Opening a Text File for Writing Output. You create a PrintWriter to write to a file using the methods print and println. You must tell the PrintWriter what the name of the file is that you will be writing to. If the file can not be found, a FileNotFoundException will be thrown. File Names. The name of a file on the system is dictated by the system, not by Java. Therefore, the name of the file is the name of the file on the system. A File has Two Names. In the program, you connect the stream to the file and use its name on the system. The stream itself has a name and that is the name you use when writing to the file within your program. IOException. This is the base class for all exceptions dealing with input and output errors. Closing a Text File. It is important that when you are done with a stream, that you close the stream using the close method. Opening a Text File for Appending. You can open file for writing and append text to the end as opposed to overwriting the information by adding the parameter true to the creation of the FileOutputStream that is created when creating the PrintWriter. Opening a Text File for Reading with Scanner. If you open a file for reading with Scanner, you can use the methods of the scanner just like when you were reading from console input, nextInt, nextLine, etc. FileNotFoundException. This exception is thrown when a file that the system requests is not present on the system. It is a type of IOException and will appear when doing File I/O. Checking for the End of a Text File with Scanner. The methods of the Scanner help to see when the input from the file is finished. Unchecked Exceptions. There are many unchecked exceptions that can occur while reading and writing to a file. These include the NoSuchElementException, InputMismathException, and IllegalStatementException. Opening a Text File for Reading with BufferedReader. Using the BufferedReader to read from a file, you can then use the readLine and read methods to retrieve the information.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

Checking for the End of a Text File with BufferedReader. readLine returns null when it tries to read beyond the end of the file, and read returns -1 if it goes beyond the end of the file. The File Class. There is a class defined in Java to represent a file. Creating an instance of this class will help determine whether a file exists and if the program has read/write access to the file. Opening a Binary File for Output. Writing to a binary file requires an ObjectOutputStream and you can use any of its multiple write methods to write information to the file. Opening a Binary File for Reading. You use a ObjectInputStream to read information from a binary file. There are also multiple read methods to help read the information from the file. EOFException. If you read beyond the end of the file, this exception will be thrown and can be used in a loop to help determine when you have reached the end of the file.

Tips toString Helps with Text File Output. The methods print and println in a PrintWriter work like System.out.print and System.out.println. If you give an object as a parameter, they will automatically call the toString method on that object. Another good reason to always have a toString in the objects you create. Reading Numbers with BufferedReader. Reading from a file gives the information as a String. To convert a String from a file into a number, you must use the method Integer.parseInt or similar methods to convert the string to the number.

Pitfalls A try Block is a Block. This pitfall discusses the fact that declaring a variable inside the block makes the variable local to the block and not accessible outside of the block. This is important when creating streams. Overwriting an Output File. When you create a PrintWriter for a file, you will destroy a file on the system with the same name if one exists. All of the information in that file will be lost. If a file by that name does not exist, it will be created. Checking for the End of a File in the Wrong Way. If you are looking for the end of the file marker in the wrong way, chances are your program will generate an error or go into an infinite loop. It is important to remember that the EOFException will be generated if using a binary file and a character like null will be read if at the end of a text file. Mixing Class Types in the Same File. You do not want to mix class types within the same binary file. It is best to only store items of the same class or primitive type in a file and not to mix the two.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

A RandomAccessFile Need Not Start Empty. When a file is opened in this way, the file is not erased, but rather the file pointer is set to the beginning of the file, not always the best place for writing, but usually the better place for reading from the file.

Programming Projects Answers 1. /** * Question1Names.java * * This program reads through a list of names and finds * the most popular boys and girls names. * * Created: Sat Mar 19 2005 * * @author Kenrick Mock * @version 1 */ import java.io.FileInputStream; import java.io.IOException; import java.io.FileNotFoundException; import java.util.Scanner; public class Question1Names { public static final int NUMNAMES = 1000; // Number of names in the file /** * isInArray * Searches the string array for target. * It returns the index of the matching name. If no match * is found, then -1 is returned. * * This algorithm uses a simple linear search. * A much more efficient method is binary search, * which can be used since the array is sorted. * Binary search is covered in chapter 11. * * @param names Array of names to search * @param target String target we are searching for * @return int Index of matching position, -1 if no match found. */ public static int isInArray(String[] names, String target) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

{ int i; // Scan through all strings for a match. // Since the arrays are not sorted, we can't use // binary search or other search optimizations. for (i=0; (i<NUMNAMES); i++) { if (names[i].equals(target)) return i; } return -1; } /** * LoadFile reads from the specified filename into the arrays * for the names and count of occurrences of that name. * * @param names String array where to store the names from the file * @param count int array where to store the count numbers from the file * @param filename String holding the name of the file to open */ public static void LoadFile(String[] names, int[] count, String filename) { // Read the entire file into an array so it can be searched. Scanner inputStream = null; int i; try { inputStream = new Scanner(new FileInputStream(filename)); for (i=0; i< NUMNAMES; i++) { String line = inputStream.nextLine(); // Parse out first name and number int space = line.indexOf(" ",0); String first = line.substring(0,space); String number = line.substring(space+1); // Store values in arrays // Convert name to lowercase to avoid case sensitivity names[i] = first.toLowerCase(); count[i] = Integer.parseInt(number); } inputStream.close(); } catch (FileNotFoundException e) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

System.out.println ("File not found!"); System.exit (0); } catch (IOException e) { System.out.println("Error reading from file."); System.exit(0); } } /** * Main method */ public static void main(String[] args) { int i; String name; String[] boyNames = new String[NUMNAMES]; // Array of boy names String[] girlNames = new String[NUMNAMES]; // Array of girl names int[] boyCount = new int[NUMNAMES]; // Array of number of names for boys int[] girlCount = new int[NUMNAMES]; // Array of number of names for girls // e.g. boyCount[0] is how many // namings of boyNames[0] // A more OO design would be to create a class // that encapsulates both a name and count // than to have two separate arrays.

// Load files into arrays LoadFile(boyNames, boyCount, "boynames.txt"); LoadFile(girlNames, girlCount, "girlnames.txt"); // Input the target name and search through the arrays for a match System.out.println("Enter name: "); Scanner scan = new Scanner(System.in); name = scan.nextLine(); String lowerName = name.toLowerCase(); // First look through girls i = isInArray(girlNames, lowerName); if (i>=0) { System.out.println(name + " is ranked " + (i+1) + " in popularity " + "among girls with " + girlCount[i] + " namings."); } else Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

{ System.out.println(name + " is not ranked among the top 1000 girl names. "); } // Repeat for boys i = isInArray(boyNames, lowerName); if (i>=0) { System.out.println(name + " is ranked " + (i+1) + " in popularity " + "among boys with " + boyCount[i] + " namings."); } else { System.out.println(name + " is not ranked among the top 1000 boy names. "); } } } // Question1Names

2. /** * NumberCount.java * * This program reads a file that has numbers separated by space and * counts the occurrences of 10 * * Created: Feb 6, 2016 * * @author * @version 1 */ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; public class NumberCount { public static void main(String[] args) { //access file from current directory File fileName = new File("input.txt"); Scanner inputStream = null; try { inputStream = new Scanner(new FileInputStream(fileName)); } catch (FileNotFoundException e) { System.out.println("File input.txt was not found"); System.out.println("or could not be opened."); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

System.exit(0); } int next, count = 0; while (inputStream.hasNextInt()) { next = inputStream.nextInt(); if (next == 10) count++; } inputStream.close(); System.out.println("The number of occurrences of number 10 is " + count); } } Input.txt

3. /** * Question3.java * * Created: Fri Jan 09 20:08:16 2004 * Modified: Sun Mar 20 2005, Kenrick Mock * * @author Adrienne Decker * @version */ import java.io.FileReader; import java.io.IOException; import java.io.FileInputStream; import java.util.Scanner; public class Question3 { public static void main(String[] args){ int count = 0; double sum = 0.0; try { Scanner inputStream = new Scanner(new FileInputStream("Question3.txt")); // File must have at least one value // to operate properly if (inputStream.hasNextDouble()) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

count = 1; sum = inputStream.nextDouble(); } while (inputStream.hasNextDouble()) { sum += inputStream.nextDouble(); count++; } inputStream.close(); System.out.println("Average: " + sum/count); } catch (IOException e) { System.out.println("Error reading from Question3.txt"); } } } // Question3

4. /** * Question4.java * * Created: Fri Jan 09 20:08:21 2004 * Modified: Sun Mar 20 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ import java.io.FileReader; import java.io.IOException; import java.io.FileInputStream; import java.util.Scanner; public class Question4 { public static void main(String[] args) { int count = 0; double temp = 0.0; double sum = 0.0; double avg = 0.0; try { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

Scanner inputStream = new Scanner(new FileInputStream("Question4.txt")); // File must have at least one value // to operate properly if (inputStream.hasNextDouble()) { count = 1; sum = inputStream.nextDouble(); } while (inputStream.hasNextDouble()) { sum += inputStream.nextDouble(); count++; } inputStream.close(); avg = sum / count; // Open again and calculate standard deviation inputStream = new Scanner(new FileInputStream("Question4.txt")); sum = count = 0; while (inputStream.hasNextDouble()) { double val = inputStream.nextDouble(); sum += Math.pow(val - avg, 2.0); count++; } inputStream.close(); System.out.println("Standard Deviation: " + Math.sqrt(sum/count)); } catch (IOException e) { System.out.println("Error reading from Question4.txt"); } } } // Question4 5. import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintWriter; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

import java.util.Scanner; /** * CorrectFile.java * * This program reads a file with the file name entered by the user, * copy its contents into a temporary file which is created with a * unique name ensuring that no file exists with the same name in the * current directory. The contents of the temporary file would be * corrected by inserting a newline character after every period. * Finally the contents are copied back to the original file and the * temporary file is deleted. * * Created: Feb 6, 2016 * * @author * @version 1 */ public class CorrectFile { public static void main(String[] args) { Scanner inputStream = null, keyboard = new Scanner(System.in); PrintWriter outputStream = null; File dataFile, tempFile; int i = 0; System.out.print("\nEnter the file to be edited : "); dataFile = new File(keyboard.next()); do { // finding temporary file if it exists create new with digit prefix if (i == 0) tempFile = new File("temp.txt"); else tempFile = new File("temp" + i + ".txt"); i++; } while (tempFile.exists()); try { inputStream = new Scanner(new FileInputStream(dataFile)); outputStream = new PrintWriter(tempFile); } catch (FileNotFoundException e) { System.out.println("File not found"); System.exit(0); } System.out.println("\nTemporary file : " + tempFile.getName() + " created for intermediate operation"); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

String next, line = ""; while (inputStream.hasNext()) { //reading data from file and put in a line till . occurs next = inputStream.next(); if (next.contains(".")) { line += next.substring(0, next.length() - 1); outputStream.println(line); line = ""; } else line += next + " "; } inputStream.close(); outputStream.close(); System.out.println("\nRetrive data from " + dataFile.getName() + " and put it into temporary file each line till . occurs"); try { inputStream = new Scanner(new FileInputStream(tempFile)); outputStream = new PrintWriter(dataFile); } catch (FileNotFoundException e) { System.out.println("File not found"); System.exit(0); } line = ""; while (inputStream.hasNext()) { // write back content of temp file to data file outputStream.println(inputStream.nextLine()); } inputStream.close(); outputStream.close(); System.out.println("\nData written back to " + dataFile.getName()); tempFile.deleteOnExit(); // delete temp file. System.out.println("\nDelete temporary file"); } } Text Project 6. /** * Question6.java * * Created: Fri Jan 09 20:08:32 2004 * Modified: Sun Mar 20 2005, Kenrick Mock Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

* * @author Adrienne Decker * @version 2 */ import java.io.FileInputStream; import java.util.Scanner; import java.io.FileOutputStream; import java.io.FileReader; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; public class Question6 { public static void main(String[] args){ try { Scanner inputStream = new Scanner(new FileInputStream("advice.txt")); String line; while (inputStream.hasNextLine()) { line = inputStream.nextLine(); System.out.println(line); } inputStream.close(); Scanner keyboard = new Scanner(System.in); System.out.println("Enter advice (hit return on empty line to quit):"); PrintWriter outputStream = new PrintWriter(new FileOutputStream("advice.txt")); line = keyboard.nextLine(); while (!line.equals("")) { outputStream.println(line); line = keyboard.nextLine(); } outputStream.close(); } catch (IOException e) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

{ System.out.println("Error reading or writing files."); } } } // Question6

7. No solution given 8. import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; /** * Palindrome.java * * The program reads the words in a file with the name WordBuff.txt * and prints all words that are not palindrome into a newly created * file output.txt and prints the count of palindrome on the output * console. * * Created: Feb 6, 2016 * * @author * @version 1 */ public class Palindrome { static boolean checkPalindrom(String original) { String reverse = ""; int length = original.length(); for (int i = length - 1; i >= 0; i--) reverse = reverse + original.charAt(i); if (original.equals(reverse)) return (true); else return (false); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

public static void main(String[] args) { Scanner inputStream = null; PrintWriter outputStream = null; File inputFile = new File("WordBuff.txt"); try { inputStream = new Scanner(new FileInputStream(inputFile)); outputStream = new PrintWriter("output.txt"); } catch (FileNotFoundException e) { System.out.println("File not found " + e.getMessage()); System.out.println("or could not be opened."); System.exit(0); } String word; int count = 0; while (inputStream.hasNext()) { word = inputStream.next(); if (checkPalindrom(word) == true) count++; else outputStream.print(word + " "); } inputStream.close(); outputStream.close(); System.out.println("The number of Palindrome words are " + count); } } 9. No solution given (see question 10 below, substitute int for double) 10. import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Scanner; /** * Grades.java * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

* The program reads the grades of 8 students in the scale between 0 * and 10. Writes these values into a binary file student.txt to read * the values from the file and print on the output console, the * highest and lowest grades among the grades of the 8 students. * * Created: Feb 6, 2016 * * @author * @version 1 */ public class Grades { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); ObjectOutputStream outputStream; ObjectInputStream inputStream; String fileName = "student.txt"; double grade = 0.0, highest, lowest; try { outputStream = new ObjectOutputStream (new FileOutputStream(fileName)); for (int i = 0; i < 8; i++) { System.out.print("Input grade of student " + (i + 1) + " :"); grade = keyboard.nextDouble(); outputStream.writeDouble(grade); } outputStream.close(); } catch (FileNotFoundException e) { System.out.println("Cannot find the file "); } catch (IOException e) { System.out.println("Problems with input"); } System.out.println("Grades are written to the file " + fileName); highest = lowest = grade; try { inputStream = new ObjectInputStream (new FileInputStream(fileName)); System.out.println("Reading grades from the file"); for (int i = 0; i < 8; i++) { grade = inputStream.readDouble(); if (grade > highest) highest = grade; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

else if (grade < lowest) lowest = grade; } inputStream.close(); } catch (FileNotFoundException e) { System.out.println("Cannot find the file "); } catch (IOException e) { System.out.println("Problems with input "); } System.out.println("Highest grade is :" + highest); System.out.println("Lowest Grade is :" + lowest); System.out.println("End of the program."); } } 11. /** * Question11.java * * * Created: Fri Jan 09 20:08:50 2004 * * @author Adrienne Decker * @version */ import java.io.EOFException; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class Question11 { public static void main(String[] args){ int count = 0; double avg = 0.0; double sum = 0.0; try { ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("Question9.dat")); try { while (true) { sum += inputStream.readDouble(); count++; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

} // end of while () } catch (EOFException e) { } inputStream.close(); avg = sum / count; inputStream = new ObjectInputStream(new FileInputStream("Question9.dat")); sum = count = 0; try { while (true) { sum += Math.pow(inputStream.readDouble() - avg, 2.0); count++; } // end of while () } catch (EOFException e) { } inputStream.close(); System.out.println("Standard Deviation: " + Math.sqrt(sum/count)); } catch (IOException e) { System.out.println("Error reading from Question9.dat"); } } } // Question11

12. /** * PersonFileWrapper.java * * Created: Sun Jan 11 14:59:41 2004 * Modified Sun Mar 20 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

import java.util.Scanner; import java.io.EOFException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.File; public class PersonFileWrapper { private static final String FILENAME = "person.dat"; public static final int MAXRECORDS = 100; Person[] data; private int numEntries = 0; public PersonFileWrapper() { data = new Person[MAXRECORDS]; // Load file from disk if it exists, otherwise initialize to blank File fileObject = new File(FILENAME); if (fileObject.exists()) { loadData(); } else { for (int i=0; i<MAXRECORDS; i++) { data[i]=null; // Blank entries indicated by null } } } public void saveData() { try { ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(FILENAME)); outputStream.writeObject(data); outputStream.close(); } catch (IOException e) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

{ System.out.println("Error: " + e.getMessage()); } } public void loadData() { try { ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(FILENAME)); data = (Person[]) inputStream.readObject(); inputStream.close(); // Recalculate number of entries numEntries = 0; for (Person p : data) { if (p!=null) numEntries++; } } catch (ClassNotFoundException e) { System.out.println("Person class not found."); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } } public int getNumEntries() { return numEntries; } public void addPerson() { if (numEntries < MAXRECORDS) { Scanner keyboard = new Scanner(System.in); System.out.println("Enter person name:"); String name = keyboard.nextLine(); System.out.println("Enter birth month:"); int birthMonth = keyboard.nextInt(); System.out.println("Enter birth day:"); int birthDay = keyboard.nextInt(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

System.out.println("Enter birth year:"); int birthYear = keyboard.nextInt(); System.out.println("Is person alive (y/n)?"); keyboard.nextLine(); // Newline String alive = keyboard.nextLine(); Date deathDate = null; if (alive.equalsIgnoreCase("n")) { System.out.println("Enter death month:"); int deathMonth = keyboard.nextInt(); System.out.println("Enter death day:"); int deathDay = keyboard.nextInt(); System.out.println("Enter death year:"); int deathYear = keyboard.nextInt(); keyboard.nextLine(); // Newline deathDate = new Date(deathMonth, deathDay, deathYear); } Date birthDate = new Date(birthMonth, birthDay, birthYear); Person person = new Person(name, birthDate, deathDate); data[numEntries] = person; numEntries++; } else { System.out.println("Database full."); } } public void retrievePerson() { Scanner keyboard = new Scanner(System.in); System.out.println("Enter person name:"); String name = keyboard.nextLine(); for (Person p : data) { if (p!=null) { if (p.getName().equalsIgnoreCase(name)) { System.out.println(p); return; } } } System.out.println("\nName not found.\n"); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

} // If a match is found, replace with null. // Leaves "holes" in the array, so we must account for nulls. public void deletePerson() { Scanner keyboard = new Scanner(System.in); System.out.println("Enter person name:"); String name = keyboard.nextLine(); for (int i=0; i< MAXRECORDS; i++) { if (data[i] !=null) { if (data[i].getName().equalsIgnoreCase(name)) { System.out.println("\n"+ name + " found and removed.\n"); data[i] = null; numEntries--; return; } } } System.out.println("\nName not found.\n"); } public void peopleInRange() { Scanner keyboard = new Scanner(System.in); System.out.println("You are about to retrieve people " + "within a certain age range."); System.out.println("You will need to enter today's date."); System.out.println("Enter the month:"); int month = keyboard.nextInt(); System.out.println("Enter the day:"); int day = keyboard.nextInt(); System.out.println("Enter the year:"); int year = keyboard.nextInt(); Date todaysDate = new Date(month, day, year); System.out.println("Enter the beginning of the age range: "); int youngest = keyboard.nextInt(); System.out.println("Enter the end of the age range: "); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

int oldest = keyboard.nextInt(); for (Person p : data) { if (p!=null) { if (p.getDeathDate()==null) { Date birth = (Date) p.getBirthDate(); int age = 0; if ( birth.getMonth() < todaysDate.getMonth() ) { age = todaysDate.getYear() - birth.getYear(); } else if ( birth.getMonth() == todaysDate.getMonth() ) { if ( birth.getDay() < todaysDate.getDay() ) { age = todaysDate.getYear() - birth.getYear(); } else { age = todaysDate.getYear() - birth.getYear() - 1; } } else { age = todaysDate.getYear() - birth.getYear() - 1; } if ( age >= youngest && age <= oldest) { System.out.println(p); } } } } } }

/** * Question12.java * * Created: Fri Jan 09 20:08:57 2004 * Modified: Sun Mar 20 2005, Kenrick Mock * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

* @author Adrienne Decker * @version 2 */ import java.util.Scanner; public class Question12 { public static void main(String[] args){ String input; PersonFileWrapper pfw = new PersonFileWrapper(); String menu; Scanner keyboard = new Scanner(System.in); do { menu = "Person Manipulation Menu (" + pfw.getNumEntries() + " entries of " + pfw.MAXRECORDS + " max)\n"; menu += "[A]dd person\n"; menu += "[R]etrieve person\n"; menu += "[D]elete person\n"; menu += "[O]btain persons by age range\n"; menu += "[S]ave data to disk\n"; menu += "[L]oad data from disk\n"; menu += "[Q]uit"; System.out.println(menu); input = keyboard.nextLine(); if (input.equalsIgnoreCase("a")) { pfw.addPerson(); } // end of if () else if (input.equalsIgnoreCase("r")) { pfw.retrievePerson(); } // end of else else if (input.equalsIgnoreCase("d")) { pfw.deletePerson(); } // end of else else if ( input.equalsIgnoreCase("o")) { pfw.peopleInRange(); } // end of if () else if ( input.equalsIgnoreCase("s")) { pfw.saveData(); } // end of if () Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

else if ( input.equalsIgnoreCase("l")) { pfw.loadData(); } // end of if () } while (!input.equalsIgnoreCase("q")); } } // Question12

13. /** * Question 13 * * Trivia game administrator interface program. Stores the * questions into a binary file. * * Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; import java.io.*; public class Question13 { private static int numQuestions = 0; private static Trivia[] data = null; public Question13() { } // Increases the size of the array by 1. // This is done by copying to a new array. private static void IncreaseArraySize() { if (data == null) { data = new Trivia[1]; } else { Trivia[] newData = new Trivia[data.length + 1]; for (int i = 0; i < data.length; i++) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

{ newData[i] = data[i]; } newData[data.length] = null; data = newData; } } // Decreases the item at the specified index // of the array. // This is done by copying to a separate // array everything except the specified // index. private static void DeleteArrayItemAt(int index) { if (data == null) { return; } if (data.length == 1) { data = null; return; } Trivia[] newData = new Trivia[data.length - 1]; for (int i = 0, j = 0; i < data.length; i++) { if (i != index) { newData[j++] = data[i]; } } data = newData; } // MAIN METHOD public static void main(String[] args) { String s; Scanner kbd = new Scanner(System.in); // Read file in if it exists try { ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("triviafile")); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

data = (Trivia[]) inputStream.readObject(); numQuestions = data.length; inputStream.close(); } catch (FileNotFoundException e) { System.out.println("No file found, starting with empty array."); } catch (Exception e) { System.out.println("Error reading file."); System.exit(0); } do { // Display menu System.out.println(); System.out.println("Trivia Game Administration"); System.out.println(); System.out.println("1. List trivia"); System.out.println("2. Delete question"); System.out.println("3. Add question"); System.out.println("4. Quit"); s = kbd.nextLine(); System.out.println(); if (s.charAt(0) == '1') { // List all trivia questions if (data != null) { for (int i =0 ; i < data.length; i++) { System.out.println("Question: " + (i+1)); System.out.println(data[i].getQuestion() + "\n" + "Answer: " + data[i].getAnswer() + "\nValue: " + data[i].getValue()); System.out.println(); } } } else if (s.charAt(0) == '2') { // Delete question if (numQuestions > 0) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

{ System.out.println("Enter the question number " + "to delete. Use the List Trivia" + " menu item to find the question number."); int num = kbd.nextInt(); kbd.nextLine(); if ((num < 0) || (num >= numQuestions)) { System.out.println("Invalid number"); } else { DeleteArrayItemAt(num); numQuestions--; } } else { System.out.println("That question does not exist."); } } else if (s.charAt(0) == '3') { // Add new question System.out.println("Enter question."); String question = kbd.nextLine(); System.out.println("Enter answer."); String answer = kbd.nextLine(); System.out.println("Enter value."); int value = kbd.nextInt(); kbd.nextLine(); // Process newline IncreaseArraySize(); data[numQuestions] = new Trivia(question, answer, value); numQuestions++; } } while (s.charAt(0) != '4'); // Save the array to a file try { ObjectOutputStream outputStream = new ObjectOutputStream( new FileOutputStream("triviafile")); outputStream.writeObject(data); outputStream.close(); System.out.println("Data saved."); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

catch (IOException e) { System.out.println("Error writing to file."); System.exit(0); } } }

// File Trivia.java // The base class for any array we store with // writeObject must be serializable import java.io.Serializable; public class Trivia implements Serializable { private String question; private String answer; private int value; // Default constructor public Trivia() { question = ""; answer = ""; value = 0; } // Constructor to set the question, answer, and value public Trivia(String question, String answer, int value) { this.question = question; this.answer = answer; this.value = value; } // Accessor methods to retrieve the question, answer, value public String getQuestion() { return question; } public String getAnswer() { return answer; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

} public int getValue() { return value; } } // File TriviaGame.java /** * Question 13 * * Trivia game with 5 questions loaded from the file * created by the administrator interface. * Uses a single array of trivia objects. * * Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; import java.io.*; public class TriviaGame { private Trivia[] trivia; private int score = 0; // Overall score private int questionNum = 0; // Track if question 0 - 4 public TriviaGame() // Constructor { // Read file in if it exists try { ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("triviafile")); trivia = (Trivia[]) inputStream.readObject(); inputStream.close(); } catch (FileNotFoundException e) { System.out.println("No trivia file found."); System.exit(0); } catch (Exception e) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

{ System.out.println("Error reading file."); System.exit(0); } } // Returns false if there are no more questions to ask. // Otherwise it asks the next question, gets an answer // from the user, and displays if the user was correct or not. public boolean askNextQuestion() { if (questionNum >= trivia.length) { return false; } // Show the current question System.out.println(); System.out.println("Question " + (questionNum + 1)); System.out.println(trivia[questionNum].getQuestion()); Scanner kbd = new Scanner(System.in); String guess = kbd.nextLine(); // Check if the answer is correct or not guess = guess.toLowerCase(); String answer = trivia[questionNum].getAnswer().toLowerCase(); if (guess.equals(answer)) { System.out.println("That is correct!"); score += trivia[questionNum].getValue(); } else { System.out.println("Wrong. The correct answer is " + trivia[questionNum].getAnswer()); } // Go to next question questionNum++; return true; } // Displays current score public void showScore() { System.out.println("Your score is " + score); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 10, Instructor’s Manual

// Main method public static void main(String[] args) { TriviaGame game = new TriviaGame(); while (game.askNextQuestion()) { game.showScore(); } System.out.println("Game over! Thanks for playing!"); } } // Question 13

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 11, Instructor’s Manual

Chapter 11

Recursion Key Terms recursive method How recursion works How recursion ends base case stopping case stack last-in/first-out recursion mutual recursion stack frame efficiency criteria for methods that return a value criteria for void methods stopping case Brief Outline 11.1 Recursive void Methods Tracing a Recursive Call A Closer Look at Recursion Stacks for Recursion Recursion versus Iteration 11.2 Recursive Methods that Return a Value General Form for a Recursive Method that Returns a Value 11.3 Thinking Recursively Recursive Design Techniques Binary Search Efficiency of Binary Search

Teaching Suggestions This chapter discusses recursion. Some instructors might choose to ignore this chapter for now and continue on with the other topics of the book and come back to this at some future point. Also, the chapter could be discussed closer to the other flow of control issues after Chapter 5. There is quite a bit of optional material in the chapter. If this is not a student’s first introduction to programming, the topics will be of interest, but for an introductory course, they might require more explanation that necessary to aid in the understanding of recursion. The chapter begins the discussion of recursion by using methods that have a void return type and explains how recursion actually happens in the system. Then, recursive methods that have a return type are introduced.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 11, Instructor’s Manual

The chapter ends with a section on thinking recursively, which seems to be a part that students find more difficult than understanding a simple recursive method. It is the actual process of writing a recursive method that tends to pose problems for them. Binary Search is introduced as an optional topic to show a side by side comparison of an iterative and recursive solution in a good sized piece of code. The programming projects for this chapter are rather short and have solutions that are easily found by searching the web. Instructors should take note of that fact if assigning the problems as a graded homework.

Key Points Recursion. A method that calls itself uses recursion. General Form of a Recursive Method Definition. A recursive method is made up of one or more cases that are stopping cases or base cases that tell the method when to stop executing and one or more cases that are recursive. We can use the recursive cases to solve smaller parts of the problem and when they are all finished executing, we have totally solved the problem. Stack. A data structure that can be described as “last-in first-out”. The computer uses a stack to keep track of recursion. Since stacks are concepts that may be covered in a more advanced course, this topic can be omitted from this chapter. Pitfalls Infinite Recursion. Infinite recursion is similar to infinite loops in that it will run forever. One of the most common ways a program will have infinite recursion is if the recursive method does not have a base case. Also, for the recursive cases, it is important to ensure that repeated calls will eventually lead you to the base case of the problem. Stack Overflow. When using recursion, successive recursive calls go on the stack. Since the size of the stack is finite. If too may recursive calls are executed, the stack becomes full and trying to place another item on the stack will cause a stack overflow. This error is common if you have an infinite recursion.

Examples Vertical Numbers. In this example we see using recursion to take in a number and write the numbers’ digits in a vertical manner. It is illustrated in Display 11.1 and later in the chapter we see the iterative version in Display 11.2. Another Powers Method. This example defines the pow method of the class Math using a recursive definition. Basically, the method takes in two numbers and raises the first number to the second number. This method is defined using integers instead of the doubles used by the Math class.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 11, Instructor’s Manual

Programming Projects Answers 1. /** * Question1Interest.java * * This program recursively computes compound interest.. * * Created: Sat Apr 2 2005 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; public class Question1Interest { /** * calculateSavings * Recursively compute compound interest. * The recursive definition is: * savings(d,i,y) = savings((d*i)+d,i,y-1) * where d = initial deposit, i = interest rate, y = number of years * @param initial_deposit Initial amount of deposit * @param yearly_interest_rate Interest rate, value between 0-1 * @param num_years integer that is number of years * @return double Savings accrued at the interest rate after the number of years */ public static double calculateSavings(double initial_deposit, double yearly_interest_rate, int num_years) { // Base case -- if num_years = 0, then we just get the amount of // the initial deposit if (num_years == 0) return initial_deposit; // If num_years > 0, then for the first year we make // (interest_rate * initial) + initial. Feed this into the // same function, but now for one fewer year since we have accounted // for the value after this year. return calculateSavings( (initial_deposit * yearly_interest_rate) + initial_deposit, yearly_interest_rate, num_years - 1); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 11, Instructor’s Manual

} // ====================== // main method // ====================== public static void main(String[] args) { // Input variables double initial_amount; double interest_rate; int num_years; double future_value; Scanner scan = new Scanner(System.in); System.out.println("Enter initial amount to save:"); initial_amount = scan.nextDouble(); System.out.println("Enter yearly interest rate (e.g. 0.10 for 10%)"); interest_rate = scan.nextDouble(); System.out.println("Enter number of years of compounded interest. "); num_years = scan.nextInt(); future_value = calculateSavings(initial_amount, interest_rate, num_years); System.out.println("$" + initial_amount + " after " + num_years + " years, at " + interest_rate + " would amount to $" + future_value); } } // Question1Interest

2. /** * Question2Handshake.java * * This program recursively computes, if we have n people in a room * where n >= 1, what is the total number of handshakes if each * person shakes hands once with every other person? * * Created: Sat Apr 2 2005 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner;

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 11, Instructor’s Manual

public class Question2Handshake { /** * handshakes * Recursively compute number of handshakes. * If 1 person is in the room, there are 0 handshakes. * If 2 people are in the room, there is 1 handshake. * For the nth person that enters the room, the new * person has to shake hands with (n-1) other people * so the total number of handshakes is: * h(n) = (n-1) + h(n-1) **/ public static int handshakes(int numpeople) { if (numpeople<=1) return 0; return (numpeople-1) + handshakes(numpeople-1); }

// ====================== // main method // ====================== public static void main(String[] args) { // Input variables int num_people; int num_handshakes; Scanner scan = new Scanner(System.in); System.out.println("How many people are in the room?"); num_people = scan.nextInt(); num_handshakes = handshakes(num_people); System.out.println("If everyone shakes hands once, there will be " + num_handshakes + " handshakes."); } } // Question2Handshake

3. /** * Question3BowlingPins.java * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 11, Instructor’s Manual

* This program recursively computes the total number of bowling * pins in a pyramid of n rows. * * Created: Sat Apr 2 2005 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; public class Question3BowlingPins { /** * numberOfPins * Recursively compute number of bowling pins if we have n rows. * If there are no rows, then there are 0 pins. * If there is only one row, then there is 1 pin. * If there are two rows, then we have two pins in row 2 + 1 from row 1 = 3 * If there are three rows, then we have three pins in row 3, plus * the three pins if there were two rows, for 6 pins.a * The recursive definition is: * pins(n) = n + pins(n-1) **/ public static int numberOfPins(int rows) { if (rows <=0) return 0; return (rows) + numberOfPins(rows-1); } // ====================== // main method // ====================== public static void main(String[] args) { // Input variables int num_rows; int num_pins; Scanner scan = new Scanner(System.in); System.out.println("How many rows of bowling pins will there be?"); num_rows = scan.nextInt(); num_pins = numberOfPins(num_rows); System.out.println("You will need to set up " + num_pins + " bowling pins."); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 11, Instructor’s Manual

} } // Question3BowlingPins

4. /** * Question4JumpIt.java * * This program recursively computes the lowest total cost * to move to the last column according to the rules of the Jump It * game. * * Created: Sat Apr 2 2005 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; public class Question4JumpIt { /** * Jumpcost * Recursively compute cheapest cost. Tries to move one column over and * also jumps and picks the move that has the cheapest cost. * * Uses the recurrence: * Cheapest = board[curPosition] if curPosition is the last column * Cheapest = board[curPosition] + * min(JumpCost(board,curPosition+1), * JumpCost(board,curPosition+2)) * * @param board - the board we are playing on * @param curPosition - index into the board of our current position * @return int Total cheapest cost to reach the end */ public static int JumpCost(int[] board, int curPosition) { // If we start out at the final column then the cost // is just the cost of being in that position if (curPosition == board.length-1) { return board[curPosition]; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 11, Instructor’s Manual

// Otherwise the cost is the cost of the current position // plus the minimum of the cost if we make a move to the // adjacent column or jump over two columns int valNext = JumpCost(board, curPosition+1); if (curPosition < board.length-2) { int valJump = JumpCost(board, curPosition+2); if (valJump < valNext) { return board[curPosition] + valJump; } else { return board[curPosition] + valNext; } } else { // We're two position from the end so // there is no jump. Return current + move to the end return board[curPosition] + valNext; } } // ====================== // main method // ====================== public static void main(String[] args) { // Sample game board int[] board = {0, 3, 80, 6, 57, 10}; int cost = JumpCost(board, 0); // Output the board System.out.println("For the following board:"); for (int i=0; i< board.length; i++) { System.out.print(board[i] + " "); } System.out.println("\nThe lowest cost to the end is " + cost); } } // Question4JumpIt

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 11, Instructor’s Manual

5. /** * SearchElement.java * * The program takes an array of 5 numbers from the user input in * ascending order and an element to search for in the array. The * program uses Binary Search algorithm using recursion to search for * the element. * * Created: Feb 6, 2016 * * @author * @version 1 */ public class SearchElement { /** * Method that performs binary search for the search element using * recursion * * @param a * Input array of integers in ascending order * @param size * Size of the array * @param num * Number to search for * @return True if the search element present in the array. False * otherwise. */ static boolean searchList(int[] a, int size, int num) { boolean flag = false; //to keep the compiler happy. if (size > 0 && a[size - 1] == num) return (true); else if (size == 0) return (false); else return (searchList(a, size - 1, num)); } public static void main(String[] args) { int data[] = new int[5]; int num; Scanner keyboard = new Scanner(System.in); System.out.println("Input data for the array " + "in ascending order \n"); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 11, Instructor’s Manual

for (int i = 0; i < data.length; i++) { System.out.print("Enter number " + (i + 1) + " : "); data[i] = keyboard.nextInt(); } System.out.println("\nEnter number to search : "); num = keyboard.nextInt(); if (searchList(data, data.length, num)) System.out.println("Number found in the array"); else System.out.println("Number not found in the array "); } } 6. /** * Exponentiation.java * * The program computes exponential value using the base number and * the exponent number that the user inputs. * * Created: Feb 6, 2016 * * @author * @version 1 */ import java.util.Scanner; public class Exponentiation { /** * Method that returns the exponential value using base number x * and exponent value m * * @param x * Base number * @param m * Exponent value * @return Exponential value */ static int expEvaluate(int x, int m) { if (m == 1) return (x); else return (x * expEvaluate(x, m - 1)); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 11, Instructor’s Manual

} public static void main(String[] args) { int x, m, expReslut; Scanner keyboard = new Scanner(System.in); System.out.print("\nInput value of x (0 < x <=10) : "); x = keyboard.nextInt(); System.out.print("\nInput value of m (0 <= m <=10): "); m = keyboard.nextInt(); System.out.println("\n The Answer is :" + expEvaluate(x, m)); } } 7. /** * Question7.java * * * Created: Sat Jan 17 15:09:15 2004 * * @author Adrienne Decker * @note There are many standard solutions to this problem, readily * available in many languages, this is a variant of one of those * solutions. */ public class Question7 { public static void hanoi(int discs) { hanoiSolver(discs, "First", "Second", "Third"); } public static void hanoiSolver(int discs, String first, String second, String third) { if ( discs == 0 ) { return; } // end of if () hanoiSolver(discs - 1, first, third, second); System.out.println("Move disc from " + first + " to " + second); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 11, Instructor’s Manual

hanoiSolver(discs - 1, third, second, first); } public static void main(String[] args) { for ( int i = 0; i < 6; i++) { System.out.println("Solution to the Towers of Hanoi puzzle" +" for" + i + " discs."); hanoi(i); } // end of for () } } // Question7

8. import java.util.Scanner; public class Searching { static int findNumber(int [] a, int first, int last, int key) { int result = 0; //to keep the compiler happy. if (first > last) result = -1; else { int mid = (first + last)/2; if (key == a[mid]) result = mid; else if (key < a[mid]) result = findNumber(a,first,mid-1,key); else if (key > a[mid]) result = findNumber(a, mid + 1, last, key); } return result; } public static void main(String [] args){ int data[]= new int[7]; int num,index; Scanner keyboard = new Scanner(System.in); System.out.println("Input data for the array in ascending order \n"); for(int i=0;i<data.length;i++){ System.out.print("Enter number "+ (i+1)+ " : "); data[i] = keyboard.nextInt(); } System.out.println("\nEnter number to search : "); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 11, Instructor’s Manual

num = keyboard.nextInt(); index = findNumber(data,0,data.length-1,num); if(index >0) System.out.println("Number found at position : "+(index+1)); else System.out.println("Number not found in the array "); } } /** * Question 9 * * Recursive method to find all matching filenames. * * Created: Fri Apr 27 2016 * * @author Kenrick Mock * @version 1 */ import java.io.File; public class FindFile { public static String searchForFile(File dir, String target) { String result = ""; // If dir is not a directory, return if (!dir.isDirectory()) return "Path is not a directory."; // Check each item in the directory for (File folderItem : dir.listFiles()) { // Recurse if it's a directory if (folderItem.isDirectory()) { result = searchForFile(folderItem,target); } // If it's a file, check for a match else { if (folderItem.getName().equals(target)) { // Print result instead of returning it //return folderItem.getAbsolutePath(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 11, Instructor’s Manual

System.out.println(folderItem.getAbsolutePath()); } } } // If we got here, nothing more was found return ""; } public static void main(String[] args) { // The root folder to search File rootFolder = new File("C:\\homeworks\\"); String result = searchForFile(rootFolder, "filelist.xml"); if (!result.equals("")) System.out.println(result); else System.out.println("End of search."); } } // Question 9 10. /** * Question 10 * * Recursive method to output subsets of an array. * * Created: Fri Apr 27 2016 * * @author Kenrick Mock * @version 1 */ public class Question10 { /* * Recursively prints out all unique combinations of each of the subsets * of the 2D array 'data'. * curList - The list in String form that is constructed recursively and is * output once the end of a list is reached * index - The current subset being searching * data - The 2D array containing the original data */ private static void printLists(String curList, int index, String[][] data) { for(int i = 0; i < data[index].length; i++) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 11, Instructor’s Manual

{ if(index < data.length - 1) printLists(curList + " " + data[index][i], index + 1, data); else System.out.println(curList + " " + data[index][i]); } } public static void main(String[] args) { String[][] data = { { "A", "B" }, { "1", "2" }, { "XX", "YY", "ZZ" } }; printLists("", 0, data); System.out.println("\n"); String[][] data2 = { { "A" }, { "1" }, { "2" }, { "XX", "YY" } }; printLists("", 0, data2); } } // Question 10

11. /** * WordGame.java * * The program reads a 3-letter word(with no repeating letter) from * the user input and prints all the words that are formed using all * possible combinations of the 3 letters in the input word. * * Created: Feb 6, 2016 * * @author * @version 1 */ import java.util.Scanner; public class WordGame { public static void printWord(String prefix, String word) { if (word.length() <= 1) { System.out.println(prefix + word); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 11, Instructor’s Manual

} else { for (int i = 0; i < word.length(); i++) { String cur = word.substring(i, i + 1); String before = word.substring(0, i); String after = word.substring(i + 1); printWord(prefix + cur, before + after); } } } public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); boolean flag = true; while (flag == true) { System.out.print("Give a word : "); String word = keyboard.next(); if (word.length() != 3) System.out.println("Must be three letter " + "word ! Try again"); else if (word.charAt(0) == word.charAt(1) || word.charAt(0) == word.charAt(2) || word.charAt(1) == word.charAt(2)) System.out.println("Must not have repeated " + "letter ! Try again"); else { flag = false; WordGame.printWord("", word); } } } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

Chapter 12

UML and Patterns Key Terms UML class diagram inheritance diagram arrows pattern Container-Iterator container iterator Adaptor Model-View-Controller

Brief Outline 12.1UML History of UML UML Class Diagrams Class Interactions Inheritance Diagrams More UML 12.2 Patterns Adaptor Pattern The Model-View-Controller Pattern Restrictions to the Sorting Pattern Efficiency of the Sorting Pattern Pattern Formalism

Teaching Suggestions This chapter discusses UML and Patterns. UML is commonly used as a tool for helping to visualize the design of computer programs. There have been many tools developed for use by introductory students learning programming and UML in the first programming course. UML gives a way to represent classes, their instance variables and methods, inheritance and various other interactions between the classes. Patterns are also growing in popularity for the creation of software. Patterns give a general solution for a common problem with examples of where and how it can be used. The chapter develops a solution using a Sorting Pattern, a generic way to implement sorting. These sections of the book are optional, but help introduce the use of patterns in a software development framework. Since there are many other patterns available to instructors, each instructor should Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

feel free to show other patterns that may apply to problems that students have already seen to illustrate how the problem could have been solved in the context of the pattern.

Tips Pragmatics and Patterns. Patterns serve as a guide for solving problems and there are times when adaptations are necessary to make a pattern work in a particular circumstance. This is the case with the implementation of Quick Sort presented and is common when implementing most patterns.. Examples A Sorting Pattern. This example is developed and implemented in the chapter to illustrate what a pattern gives us and an implementation of the pattern for a specific purpose.

Programming Projects Answers 1. /** * Question1Movie.java * * This implements the Movie class defined by the UML diagram. * * Created: Sat Apr 2 2005 * * @author Kenrick Mock * @version 1 */ public class Question1Movie { private String title; private int minutes; private int year; protected double price; /** * Movie constructor */ public Question1Movie(String title, int minutes, int year, double price) { this.title = title; this.minutes = minutes; this.year = year; this.price = price; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

} // Accessor/Mutator for the Title public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } /** * printDescription outputs all member variables. */ public void printDescription() { System.out.println("Movie title: " + title); System.out.println("Length in minutes: " + minutes); System.out.println("Year of release: " + year); System.out.println("Price: " + price); System.out.println(); } // ====================== // main method // ====================== public static void main(String[] args) { // Make and print some sample movie objects Question1Movie central = new Question1Movie("Central Station", 113, 1998, 14.99); Question1Movie hannibal = new Question1Movie("Hannibal", 120, 2005, 16.99); central.printDescription(); hannibal.printDescription(); } } // Question1Movie

2. /** * Question2Pizza.java Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

* * This program implements a pizza order based upon UML * specifications. * * Created: Sat Apr 2 2005 * * @author Kenrick Mock * @version 1 */ /** * The Pizza class stores information about a single pizza. */ class Pizza { private boolean pepperoni, sausage, mushrooms; private char size; // Constructors public Pizza() { // Default pizza settings pepperoni = false; sausage = false; mushrooms = false; size = 's'; } public Pizza(char size, boolean pepperoni, boolean sausage, boolean mushrooms) { this.size = size; this.pepperoni = pepperoni; this.sausage = sausage; this.mushrooms = mushrooms; } /** * getSize * @return char Returns the size of the pizza */ public char getSize() { return this.size; }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

/** * getNumToppings * @return int Returns the number of toppings on the pizza. */ public int getNumToppings() { int num=0; if (pepperoni) num++; if (sausage) num++; if (mushrooms) num++; return num; } }

/** * The PizzaOrder class stores information about a pizza order. */ class PizzaOrder { private static final int MAXPIZZAS = 100; private int numPizzas; private Pizza[] pizzas; public PizzaOrder() { pizzas = new Pizza[MAXPIZZAS]; numPizzas = 0; } /** * addPizzaToOrder * Creates a new pizza of the specified type and * appends it to the pizza array. */ public void addPizzaToOrder(char size, boolean pepperoni, boolean sausage, boolean mushrooms) { if (numPizzas == MAXPIZZAS) { // Would be better to throw an exception, but left off for simplicity System.out.println("No more pizzas allowed in the order."); return; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

Pizza newpie = new Pizza(size, pepperoni, sausage, mushrooms); // Store new pizza in array and increment number of pizzas pizzas[numPizzas++] = newpie; } /** * PizzaOrder calcCost * @return double total Cost of the order */ public double calcCost() { int i; double total=0; for (i=0; i<numPizzas; i++) { if (pizzas[i].getSize()=='s') total+=8; else if (pizzas[i].getSize()=='m') total+=10; else if (pizzas[i].getSize()=='l') total+=12; total+=pizzas[i].getNumToppings(); } return total; } } class Question2Pizza { // ====================== // main method // ====================== public static void main(String[] args) { PizzaOrder order = new PizzaOrder(); // Make a sample order with two pizzas order.addPizzaToOrder('m',true,false,false); // medium pepperoni order.addPizzaToOrder('l',false,true,true); // large sausage & mushrooms System.out.println("For two pizzas, one medium with pepperoni and " + "one large with sausage and mushrooms, the total is:"); System.out.println(order.calcCost()); // $11 + $14 = $25 } } // Question2Pizza

3.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

/** * Question3Payment.java * * This program implements payment classes based upon UML * specifications. * * Created: Sat Apr 2 2005 * * @author Kenrick Mock * @version 1 */ /** * This is an abstract class to represent a type of Payment */ abstract class Payment { protected double amount; // Constructors public Payment(double amount) { this.amount = amount; } /* * toString * @return String description of the payment. **/ public abstract String toString(); } /** * The cash class simply extends Payment. */ class Cash extends Payment { public Cash(double amount) { super(amount); } /** * toString * @return String Indicates amount is cash */ Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

public String toString() { return("Cash amount: " + amount); } } /** * The check class extends Payment and adds some new member variables */ class Check extends Payment { private String routingNumber; private String name; // Constructor public Check(double amount, String number, String name) { super(amount); this.routingNumber = number; this.name = name; } // Accessor and mutator methods public void setRoutingNumber(String routingNumber) { this.routingNumber = routingNumber; } public String getRoutingNumber() { return routingNumber; } public void setName(String name) { this.name = name; } public String getName() { return name; } /* * toString * @return String Indicates amount is check Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

**/ public String toString() { return("Check routing number: " + routingNumber + ". Name on check: " + name + ". Amount: " + amount); } }

/** * The credit card class extends Payment and adds some new member variables */ class CreditCard extends Payment { private String number; private String expiration; private String name; // Constructor public CreditCard(double amount, String name, String number, String expiration) { super(amount); this.number = number; this.name = name; this.expiration = expiration; } // Accessor and mutator methods public void setNumber(String number) { this.number = number; } public String getNumber() { return number; } public void setName(String name) { this.name = name; } public String getName() { return name; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

} public void setExpiration(String exp) { this.expiration = exp; } public String getExpiration() { return expiration; } /** * toString * @return String Indicates amount is check */ public String toString() { return("Credit Card number: " + number + ". Name on card: " + name + ". Expiration Date: " + expiration + ". Amount: " + amount); } }

class Question3Payment { // ====================== // main method, create some instances and output values as strings // ====================== public static void main(String[] args) { Cash payment1 = new Cash(100); Check payment2 = new Check(50, "1501234121", "Joe King"); CreditCard payment3 = new CreditCard(1000, "Barry Schmelly", "5142-4123-4231-3231", "10/06"); System.out.println(payment1.toString()); System.out.println(payment2.toString()); System.out.println(payment3.toString()); } } // Question3Payment

4. /** Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

* Question4Counter.java * * This program implements a counter using the model-view-controller * paradigm. * * Created: Sat Apr 2 2005 * * @author Kenrick Mock * @version 1 */ /** * The CounterView class simply displays a * value passed in. */ class CounterView { public CounterView() { } /** * @param counterValue value that is displayed to the console **/ public void Display(int counterValue) { System.out.println(counterValue); } }

/** * The CounterModel class stores the counter value * and counter logic. */ class CounterModel { private CounterView view; // Reference to the view for the model private int counter; // CounterModel constructors. // Initialize variables and // create a reference to the view. public CounterModel() { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

view = new CounterView(); counter = 0; view.Display(counter); } public CounterModel(int initialVal) { view = new CounterView(); counter = initialVal; view.Display(counter); } /** * Increment * Increments the counter * and calls Display. */ public void Increment() { view.Display(++counter); } } /** * The CounterController class waits one second * before calling increment in the CounterModel */ class CounterController { private CounterModel model; // Reference to the model private int startValue, endValue; // CounterController constructors. // Initialize variables and // create a reference to the model. public CounterController() { startValue = 0; endValue = 0; model = new CounterModel(startValue); } public CounterController(int s, int e) { startValue = s; endValue = e; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

model = new CounterModel(startValue); } /** * Start * Counts from start to end, * calling model's increment. */ public void Start() { int i = startValue; while (i<endValue) { try { Thread.sleep(1000); // Wait one second model.Increment(); i++; } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } } } }

/** * Test class */ class Question4Counter { // ====================== // main method // ====================== public static void main(String[] args) { // Create a new CounterController which in turn creates the other classes // Simply count from 5 to 15 CounterController c = new CounterController(5,15); c.Start(); } } // Question4Counter

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

5. /** * Question5Counter.java * * This program implements a counter using the model-view-controller * paradigm, but in true geek fashion outputs the counter in binary. * Requires changes only to the CounterView class. * * Only the Display and BinaryDisplay methods in the CounterView * class have been changed from the MVC Counter program. * * Created: Sat Apr 2 2005 * * @author Kenrick Mock * @version 1 */ /** * The CounterView class simply displays a * value passed in. */ class CounterView { public CounterView() { } /** * @param counterValue value that is displayed to the console */ public void Display(int counterValue) { BinaryDisplay(counterValue); System.out.println(); } /** * BinaryDisplay * Recursively computes the binary value from a decimal input. * Since we get the remainders in reverse input, the newline is * output in the calling routine (the Display method) * * @param counterValue the Value to display in binary */ Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

public void BinaryDisplay(int counterValue) { if (counterValue < 2) { System.out.print(counterValue); } else { BinaryDisplay(counterValue / 2); System.out.print(counterValue % 2); } } }

/** * The CounterModel class stores the counter value * and counter logic. */ class CounterModel { private CounterView view; // Reference to the view for the model private int counter; // CounterModel constructors. // Initialize variables and // create a reference to the view. CounterModel() { view = new CounterView(); counter = 0; view.Display(counter); } CounterModel(int initialVal) { view = new CounterView(); counter = initialVal; view.Display(counter); } /** * Increment * Increments the counter * and calls Display. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

*/ public void Increment() { view.Display(++counter); } } /** * The CounterController class waits one second * before calling increment in the CounterModel */ class CounterController { private CounterModel model; // Reference to the model private int startValue, endValue; // CounterController constructors. // Initialize variables and // create a reference to the model. CounterController() { startValue = 0; endValue = 0; model = new CounterModel(startValue); } CounterController(int s, int e) { startValue = s; endValue = e; model = new CounterModel(startValue); } /** * Start * Counts from start to end, * calling model's increment. */ public void Start() { int i = startValue; while (i<endValue) { try { Thread.sleep(1000); // Wait one second Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

model.Increment(); i++; } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } } } }

/** * Test class */ class Question5Counter { // ====================== // main method // ====================== public static void main(String[] args) { // Create a new CounterController which in turn creates the other classes // Simply count from 5 to 15 CounterController c = new CounterController(5,15); c.Start(); } } // Question5Counter

6. /** Class that realizes the divide-and-conquer sorting pattern and uses the quick sort algorithm. */ public class Question6Quicksort { /** Precondition: Interval a[begin] through a[end] of a have elements. Postcondition: The values in the interval have been rearranged so that a[begin] <= a[begin+1] <= ... <= a[end]. */ public static void sort(double[] a, int begin, int end) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

{ if ( end - begin < 1) { return; } // end of if () if ( (end - begin) == 1) { if ( a[begin] < a[end] ) { return; } // end of if () else { double temp = a[begin]; a[begin] = a[end]; a[end] = temp; } // end of else } // end of if () if ((end - begin) >= 2) { int splitPoint = split(a, begin, end); sort(a, begin, splitPoint); sort(a, splitPoint + 1, end); }//else sorting one (or fewer) elements so do nothing. } private static int split(double[] a, int begin, int end) { double[] temp; int size = (end - begin + 1); temp = new double[size]; double splitValue = a[begin]; int up = 0; int down = size - 1; //Note that a[begin] = splitValue is skipped. for (int i = begin + 1; i <= end; i++) { if (a[i] <= splitValue) { temp[up] = a[i]; up++; } else { temp[down] = a[i]; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

down--; } } //0 <= up = down < size temp[up] = a[begin]; //Positions the split value, spliV. //temp[i] <= splitValue for i < up // temp[up] = splitValue // temp[i] > splitValue for i > up for (int i = 0; i < size; i++) a[begin + i] = temp[i]; return (begin + up); } } // Question6Quicksort

7. /** Class that realizes the divide-and-conquer sorting pattern and uses the quick sort algorithm. */ public class Question7Quicksort { /** Precondition: Interval a[begin] through a[end] of a have elements. Postcondition: The values in the interval have been rearranged so that a[begin] <= a[begin+1] <= ... <= a[end]. */ public static void sort(double[] a, int begin, int end) { if ((end - begin) >= 1) { int splitPoint = split(a, begin, end); sort(a, begin, splitPoint); sort(a, splitPoint + 1, end); }//else sorting one (or fewer) elements so do nothing. } private static int split(double[] a, int begin, int end) { double[] temp; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

int size = (end - begin + 1); temp = new double[size]; double splitValue = (a[begin] + a[end] + a[size/2])/3; int up = 0; int down = size - 1; //Note that a[begin] = splitValue is skipped. for (int i = begin + 1; i <= end; i++) { if (a[i] <= splitValue) { temp[up] = a[i]; up++; } else { temp[down] = a[i]; down--; } } //0 <= up = down < size temp[up] = a[begin]; //Positions the split value, spliV. //temp[i] <= splitValue for i < up // temp[up] = splitValue // temp[i] > splitValue for i > up for (int i = 0; i < size; i++) a[begin + i] = temp[i]; return (begin + up); } } // Question7Quicksort

8. /** Class that realizes the divide-and-conquer sorting pattern and uses the quick sort algorithm. */ public class Question8Quicksort {

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

/** Precondition: Interval a[begin] through a[end] of a have elements. Postcondition: The values in the interval have been rearranged so that a[begin] <= a[begin+1] <= ... <= a[end]. */ public static void sort(double[] a, int begin, int end) { if ( end - begin < 1) { return; } // end of if () if ( (end - begin) == 1) { if ( a[begin] < a[end] ) { return; } // end of if () else { double temp = a[begin]; a[begin] = a[end]; a[end] = temp; } // end of else } // end of if () if ((end - begin) >= 2) { int splitPoint = split(a, begin, end); sort(a, begin, splitPoint); sort(a, splitPoint + 1, end); }//else sorting one (or fewer) elements so do nothing. } private static int split(double[] a, int begin, int end) { double[] temp; int size = (end - begin + 1); temp = new double[size]; double splitValue = (a[begin] + a[end] + a[size/2])/3; int up = 0; int down = size - 1; //Note that a[begin] = splitValue is skipped. for (int i = begin + 1; i <= end; i++) { if (a[i] <= splitValue) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

temp[up] = a[i]; up++; } else { temp[down] = a[i]; down--; } } //0 <= up = down < size temp[up] = a[begin]; //Positions the split value, spliV. //temp[i] <= splitValue for i < up // temp[up] = splitValue // temp[i] > splitValue for i > up for (int i = 0; i < size; i++) a[begin + i] = temp[i]; return (begin + up); } } // Question8Quicksort

9. /** * Question 9 * * Implementation of Insertion Sort using the * Sorting Pattern. * * Created: Sat Mar 22 2009 * * @author Kenrick Mock * @version 1 */ public class InsertionSort { public static void sort(double[] a, int begin, int end) { if ((end - begin) >= 1) { int splitPoint = split(a, begin, end); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 12, Instructor’s Manual

sort(a, begin, splitPoint); sort(a, splitPoint + 1, end); join(a, begin, splitPoint, end); }//else sorting one (or fewer) elements //so do nothing. } private static int split(double[] a, int begin, int end) { return (end - 1); } private static void join(double[] a, int begin, int splitPoint, int end) { double key = a[end]; // Value we are inserting int i; for (i = end; ((begin < i) && (key < a[i-1])); i--) { a[i] = a[i-1]; } a[i] = key; } public static void main(String[] args) { double[] a = {5, 10, 3, 77, 12, 94, 1, 34, 21}; sort(a, 0, a.length - 1); for (int i = 0; i < a.length; i++) System.out.println(a[i]); } } // Question 9

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

Chapter 13

Interfaces and Inner Classes Key Terms interface implementing an interface extending an interface compareTo no instance variables inconsistent constants inconsistent method headings Serializable Cloneable inner class outer class static public inner classes anonymous class

Brief Outline 13.1 Interfaces Interfaces Abstract Classes Implementing Interfaces Derived Interfaces The Comparable Interface Defined Constants in Interfaces The Serializable Interface The Cloneable Interface 13.2 Simple Uses of Inner Classes Helping Classes The .class File for an Inner Class 13.3 More About Inner Classes Static Inner Classes Public Inner Classes Nesting Inner Classes Inner Classes and Inheritance Anonymous Classes

Teaching Suggestions This chapter discusses interfaces and inner classes. Interfaces are implemented by classes who define the methods that are declared inside an interface definition. The basic syntax for an interface and the basics of implementing an interface are discussed first. Some instructors might choose to move this material closer to when inheritance and polymorphism are discussed as Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

polymorphism can apply to interfaces as well. There are several interfaces that are standard parts of Java that are discussed in the first part of this chapter, such as Serializable, which is seen in the File I/O chapter and Cloneable. Therefore, it would serve the students to see what an interface is before asking them to implement one blindly in Chapter 10. Another technique that is common to Java Code is that of inner classes, which are discussed in the second section of the book. The last section, which is optional, discusses other types of inner classes, static inner classes and public inner classes. These topics are not used elsewhere in the book and an instructor could possibly choose to postpone the discussion of inner classes until needed. They will be used when creating GUIs in the subsequent chapters, but can be discussed then.

Key Points Interfaces. A type that specifies method headings and possibly constants, but gives no method definitions or other instance variables. A class can implement as many interfaces as needed by using the keyword implements in the class definition. If a class does not fully implement an interface then it will be abstract. The Comparable Interface. There is one method in this interface called compareTo that helps us to order two objects. There are specific rules that should be followed when implementing this method as to its return values. Access Privileges Between Inner and Outer Classes. As stated in the Tip for this section, they each have access to the other’s private members. Helping Inner Classes. When creating an inner class that is a helper to the outer class, it is common that we make the class private. This idea is similar to helper methods in a class that we have also made private. Static Inner Classes. You can also write inner classes that are not associated with their outer classes. These classes require the modifier static in their definition.

Tips Inner and Outer Classes Have Access to Each Other’s Private Members. If a class has an inner class, the inner class has access to the private members of the outer class. The reverse relationship takes in instance of the inner class in the outer class for access. Referring to a Method of the Outer Class. If both the inner class and the outer class have a method with the same name and you want to explicitly call the outer class’ version of the method, there is a syntax that you can use explained in this tip. Why Use Inner Classes? This tip tries to make the argument for when to use inner classes. This argument could be solved by indicating style preferences or by citing some of the examples

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

where the inner classes make sense. There will be a few in upcoming chapters as well to help see where these types of inner classes will be useful.

Pitfalls Interface Semantics are not Enforced. This issue is also discussed in a Pitfall box. The idea is that even though the compiler enforces the implementation of an interface, the compiler does not control the semantics of how the methods are written. It is up to the programmer to implement the methods in a way that makes sense given their declarations. Inconsistent Interfaces. Even though there is very little chance of inconsistencies with interfaces, there are a few cases where errors can occur. One is the case where two different interfaces both declare constants with the same name, but different values. Another place is when two different interfaces declare a method with the same name and parameters, but different return types. Other Uses of Inner Classes. Since Strings are objects, the equality operator does not always give the correct result and should not be used to check for two Strings that contain the same character sequence. The equals method is introduced as the way to achieve the correct answer always to this problem.

Examples Using the Comparable Interface. This example shows using an object that implements the Comparable interface to perform some task. One place implementing this interface comes in handy is when trying to sort objects. A Bank Account Class. This example uses inner classes to create a bank account class. The inner class is a class for Money to be stored in the bank account. Programming Projects Answers 1. /** * Question1BinarySearch.java * * This implements the BinarySearch algorithm described in chapter * 11 of the text using an array of Comparable instead of integer. * This allows the search routine to work on any object that implements * the comparable interface. * * Created: Sat Apr 2 2005 * * @author Kenrick Mock * @version 1 */

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

public class Question1BinarySearch { /** * Searches the array a for a key. If it is not in the array then * -1 is returned. Otherwise it returns an index to the key. * @param a The array, of type Comparable, to search * @param first Index to first position in array to search * @param last Index to the last position in the array to search * @param key The item we are searching for * @return int Index of the key or -1 if not found */ public static int search(Comparable[] a, int first, int last, Comparable key) { int result = 0; if (first>last) result = -1; else { int mid = (first+last)/2; // Use the compareTo method to compare the key with the array element int compareResult = key.compareTo(a[mid]); if (compareResult == 0) // Match, key == a[mid] { result = mid; } else if (compareResult < 0) // key < a[mid] { result = search(a, first, mid-1, key); } else if (compareResult > 0) // key > a[mid] { result = search(a, mid+1, last, key); } } return result; } // ====================== // main method. Creates sample arrays and searches them. // ====================== public static void main(String[] args) { // Make an array of Integer. Java 1.5 will convert to int // for us via automatic boxing/unboxing Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

Integer[] intArray = {1, 3, 5, 7, 9, 11, 13}; // Make an array of String with some sample strings. String[] StringArray = {"blue", "fuschia", "mauve", "periwinkle", "turquoise"}; int position; // Display the integer array and then search it System.out.println("Contents of the Integer array:"); for (int i=0; i < intArray.length; i++) { System.out.print(intArray[i] + " "); } System.out.println(); // Search for 15 position = search(intArray, 0, intArray.length-1, 15); System.out.println("Result of searching for 15: " + position); // Search for 9 position = search(intArray, 0, intArray.length-1, 9); System.out.println("Result of searching for 9: " + position);

// Display the String array and then search it // using the same search routine System.out.println("\nContents of the String array:"); for (int i=0; i < StringArray.length; i++) { System.out.print(StringArray[i] + " "); } System.out.println(); // Search for "purple" position = search(StringArray, 0, StringArray.length-1, "purple"); System.out.println("Result of searching for blue: " + position); // Search for "mauve" position = search(StringArray, 0, StringArray.length-1, "mauve"); System.out.println("Result of searching for mauve: " + position); } } // Question1BinarySearch

2. /** * CityList.java * * The program creates an array of objects of type CityTemperature, * which extends Comparable interface. Using the selection sort Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

* algorithm and Comparable interface's methods, the program performs * sorting of the array of CityTemperature objects. * * Created: Feb 6, 2016 * * @author * @version 1 */ import java.util.Scanner; public class CityList { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); CityTemperature[] c = new CityTemperature[5]; for (int i = 0; i < c.length; i++) { c[i] = new CityTemperature(); System.out.print("\nEnter the name the of city " + (i + 1) + " :"); c[i].setCityName(keyboard.next()); System.out.print("Enter the temperature of the city " + (i + 1) + " :"); c[i].setTemperature(keyboard.nextDouble()); } System.out.println("Show the temperature Before sorting:"); int i; for (i = 0; i < c.length; i++) System.out.print(c[i].getTemperature() + ", "); System.out.println(); SelectionSort.sort(c, c.length); System.out.println("Show the temperature After sorting:"); for (i = 0; i < c.length; i++) System.out.print(c[i].getTemperature() + ", "); System.out.println(); } } /** * This class lets you sort an array of Comparable type objects using * selection sort algorithm. */ class SelectionSort { /** Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

* Sorts the array of Comparable type objects passed in the * arguments. * * @param a * Array of Comparable type objects * @param numberUsed * Index of the number selected to compare the array * elements against. */ public static void sort(Comparable[] a, int numberUsed) { int index, indexOfNextSmallest; for (index = 0; index < numberUsed - 1; index++) { indexOfNextSmallest = indexOfSmallest(index, a, numberUsed); interchange(index, indexOfNextSmallest, a); } } /** * The method returns the index of the smallest element in the * array * * @param startIndex * Starting index of the array to look for the smallest * element * @param a * Array from which the smallest element has to be * picked * @param numberUsed * Index until which the array has to be traversed to * pick the smallest element * @return Index of the smallest element */ private static int indexOfSmallest(int startIndex, Comparable[] a, int numberUsed) { Comparable min = a[startIndex]; int indexOfMin = startIndex; int index; for (index = startIndex + 1; index < numberUsed; index++) if (a[index].compareTo(min) < 0) //if a[index] is less than min { min = a[index]; indexOfMin = index; //min is smallest of a[startIndex] through a[index] } return indexOfMin; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

} /** * Swap the numbers at the specified indexes in the specified * array * * @param i * First index of the array to be swapped * @param j * Second index of the array to be swapped * @param a * Array to be used to swap the elements */ private static void interchange(int i, int j, Comparable[] a) { Comparable temp; temp = a[i]; a[i] = a[j]; a[j] = temp; //original value of a[i] } } /** * Class that contains city name and city temperature fields and * extends Comparable interface * */ class CityTemperature implements Comparable { private String cityName; private double temperature; public String getCityName() { return (cityName); } public double getTemperature() { return (temperature); } public void setCityName(String newName) { this.cityName = newName; } public void setTemperature(double newTemp) { this.temperature = newTemp; } public int compareTo(Object obj) { return (-1); } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

3. /** * Question3Namecollection.java * * This program creates an inner class that is returned to provide * an interface to enumerate through the items in a collection. * * Created: Sat Apr 2 2005 * * @author Kenrick Mock * @version 1 */

/** * Enumeration * This interface provides for a known interface to iterate * through objects in some sort of collection (e.g. array, list, etc.) */ interface Enumeration { // Returns true if another element in the collection exists public boolean hasNext(); // Returns the next element in the collection public Object getNext(); }

/** * NameCollection implements a collection of names using a simple array. */ class NameCollection { private String[] names; /** * NameCollection constructor. * The list of names is simply set to an array of names sent in as a parameter. * @param names String array of names that should be stored in this collection. */ public NameCollection(String[] names) { this.names = names; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

/** * getEnumeration should return a class that implements * the Enumeration interface where hasNext() and getNext() * correspond to data stored within the names array. */ Enumeration getEnumeration () { return new Enumeration () { int i = 0; public boolean hasNext() { if (i < names.length) return true; else return false; } public Object getNext() { String s = names[i]; i++; return s; } }; } } class Question3NameCollection { // Main Method public static void main(String[] args) { // Create a sample array of names and put them into a NameCollection object String[] names = {"Joe", "Frank", "Susan"}; NameCollection nc = new NameCollection(names); // Iterate through the collection using the interface // and output each name Enumeration enumerate = nc.getEnumeration(); while (enumerate.hasNext()) { System.out.println(enumerate.getNext()); } } } // Question3NameCollection

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

4. /** Class that realizes the divide-and-conquer sorting pattern and uses the merge sort algorithm. Modified to use Comparables. */ public class MergeSort { /** Precondition: Interval a[begin] through a[end] of a have elements. Postcondition: The values in the interval have been rearranged so that a[begin] <= a[begin+1] <= ... <= a[end]. */ public static void sort(Comparable[] a, int begin, int end) { if ((end - begin) >= 1) { int splitPoint = split(a, begin, end); sort(a, begin, splitPoint); sort(a, splitPoint + 1, end); join(a, begin, splitPoint, end); }//else sorting one (or fewer) elements so do nothing. } private static int split(Comparable[] a, int begin, int end) { return ((begin + end)/2); } private static void join(Comparable[] a, int begin, int splitPoint, int end) { Comparable[] temp; int intervalSize = (end - begin + 1); temp = new Comparable[intervalSize]; int nextLeft = begin; //index for first chunk int nextRight = splitPoint + 1; //index for second chunk int i = 0; //index for temp

//Merge till one side is exhausted: while ((nextLeft <= splitPoint) && (nextRight <= end)) { if (a[nextLeft].compareTo(a[nextRight]) < 0 ) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

{ temp[i] = a[nextLeft]; i++; nextLeft++; } else { temp[i] = a[nextRight]; i++; nextRight++; } } while (nextLeft <= splitPoint)//Copy rest of left chunk, if any. { temp[i] = a[nextLeft]; i++; nextLeft++; } while (nextRight <= end) //Copy rest of right chunk, if any. { temp[i] = a[nextRight]; i++; nextRight++; } for (i = 0; i < intervalSize; i++) a[begin + i] = temp[i]; } } /** * Question4.java * * * Created: Thu Jan 22 20:11:52 2004 * * @author Adrienne Decker * @version */ public class Question4 { public static void main(String[] args){ Double[] b = new Double[10]; b[0] = new Double(7.7); b[1] = new Double(5.5); b[2] = new Double(11); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

b[3] = new Double(3); b[4] = new Double(16); b[5] = new Double(4.4); b[6] = new Double(20); b[7] = new Double(14); b[8] = new Double(13); b[9] = new Double(42); System.out.println("Array contents before sorting:"); int i; for (i = 0; i < b.length; i++) System.out.print(b[i] + " "); System.out.println( ); MergeSort.sort(b, 0, b.length-1); System.out.println("Sorted array values:"); for (i = 0; i < b.length; i++) System.out.print(b[i] + " "); System.out.println( ); } } // Question4

5. /** Class that realizes the divide-and-conquer sorting pattern and uses the quick sort algorithm. Modified for Comparables. */ public class QuickSort { /** Precondition: Interval a[begin] through a[end] of a have elements. Postcondition: The values in the interval have been rearranged so that a[begin] <= a[begin+1] <= ... <= a[end]. */ public static void sort(Comparable[] a, int begin, int end) { if ((end - begin) >= 1) { int splitPoint = split(a, begin, end); sort(a, begin, splitPoint); sort(a, splitPoint + 1, end); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

join(a, begin, splitPoint, end); }//else sorting one (or fewer) elements so do nothing. } private static int split(Comparable[] a, int begin, int end) { Comparable[] temp; int size = (end - begin + 1); temp = new Comparable[size]; Comparable splitValue = a[begin]; int up = 0; int down = size - 1; //Note that a[begin] = splitValue is skipped. for (int i = begin + 1; i <= end; i++) { if (a[i].compareTo(splitValue) <= 0 ) { temp[up] = a[i]; up++; } else { temp[down] = a[i]; down--; } } //0 <= up = down < size temp[up] = a[begin]; //Positions the split value, spliV. //temp[i] <= splitValue for i < up // temp[up] = splitValue // temp[i] > splitValue for i > up for (int i = 0; i < size; i++) a[begin + i] = temp[i]; return (begin + up); } private static void join(Comparable[] a, int begin, int splitPoint, int end) { //Nothing to do. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

} } /** * Question5.java * * * Created: Thu Jan 22 20:11:52 2004 * * @author Adrienne Decker * @version */ public class Question5 { public static void main(String[] args){ Double[] b = new Double[10]; b[0] = new Double(7.7); b[1] = new Double(5.5); b[2] = new Double(11); b[3] = new Double(3); b[4] = new Double(16); b[5] = new Double(4.4); b[6] = new Double(20); b[7] = new Double(14); b[8] = new Double(13); b[9] = new Double(42); System.out.println("Array contents before sorting:"); int i; for (i = 0; i < b.length; i++) System.out.print(b[i] + " "); System.out.println( ); QuickSort.sort(b, 0, b.length-1); System.out.println("Sorted array values:"); for (i = 0; i < b.length; i++) System.out.print(b[i] + " "); System.out.println( ); } } // Question5

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

6. /** Class for a person with a name and dates for birth and death. Class invariant: A Person always has a date of birth, and if the Person has a date of death, then the date of death is equal to or later than the date of birth. */ class Person implements Cloneable { private String name; private Date born; private Date died;//null indicates still alive. public Person(String initialName, Date birthDate, Date deathDate) { if (consistent(birthDate, deathDate)) { name = initialName; born = new Date(birthDate); if (deathDate == null) died = null; else died = new Date(deathDate); } else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } public Person(Person original) { if (original == null) { System.out.println("Fatal error."); System.exit(0); } name = original.name; born = new Date(original.born); if (original.died == null) died = null; else Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

died = new Date(original.died); } public void set(String newName, Date birthDate, Date deathDate) { if (consistent(birthDate, deathDate)) { name = newName; born = new Date(birthDate); if (deathDate == null) died = null; else died = new Date(deathDate); } else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } public String toString( ) { String diedString; if (died == null) diedString = ""; //Empty string else diedString = died.toString( ); return (name + ", " + born + "-" + diedString); } public boolean equals(Person otherPerson) { if (otherPerson == null) return false; else return (name.equals(otherPerson.name) && born.equals(otherPerson.born) && datesMatch(died, otherPerson.died) ); } /** To match date1 and date2 must either be the same date or both be null. */ private static boolean datesMatch(Date date1, Date date2) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

{ if (date1 == null) return (date2 == null); else if (date2 == null) //&& date1 != null return false; else // both dates are not null. return(date1.equals(date2)); } /** Precondition: newDate is a consistent date of birth. Postcondition: Date of birth of the calling object is newDate. */ public void setBirthDate(Date newDate) { if (consistent(newDate, died)) born = new Date(newDate); else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } /** Precondition: newDate is a consistent date of death. Postcondition: Date of death of the calling object is newDate. */ public void setDeathDate(Date newDate) { if (!consistent(born, newDate)) { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } if (newDate == null) died = null; else died = new Date(newDate); } public void setName(String newName) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

name = newName; } /** Precondition: The date of birth has been set, and changing the year part of the date of birth will give a consistent date of birth. Postcondition: The year of birth is (changed to) newYear. */ public void setBirthYear(int newYear) { if (born == null) //Precondition is violated { System.out.println("Fata; Error. Aborting."); System.exit(0); } born.setYear(newYear); if (!consistent(born, died)) { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } /** Precondition: The date of death has been set, and changing the year part of the date of death will give a consistent date of death. Postcondition: The year of death is (changed to) newYear. */ public void setDeathYear(int newYear) { if (died == null) //Precondition is violated { System.out.println("Fata; Error. Aborting."); System.exit(0); } died.setYear(newYear); if (!consistent(born, died)) { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } public String getName( ) { return name; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

} public Date getBirthDate( ) { return new Date(born); } public Date getDeathDate( ) { if (died == null) return null; else return new Date(died); } /** To be consistent, birthDate must not be null. If there is no date of death (deathDate == null), that is consistent with any birthDate. Otherwise, the birthDate must come before or be equal to the deathDate. */ private static boolean consistent(Date birthDate, Date deathDate) { if (birthDate == null) return false; else if (deathDate == null) return true; else return (birthDate.precedes(deathDate ) || birthDate.equals(deathDate )); } public Object clone() { try { Person copy = (Person)super.clone(); copy.born = (Date)born.clone(); if ( died == null ) { copy.died = null; } // end of if () else { copy.died = (Date)died.clone(); } // end of else return copy; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

} catch(CloneNotSupportedException e) { return null; } } } /** * Question6.java * * * Created: Thu Jan 22 20:24:24 2004 * * @author Adrienne Decker * @version */ public class Question6 { public static void main(String[] args) { Date d = new Date(1,22, 2004); System.out.println("The date is: " + d); Date otherD = (Date)d.clone(); System.out.println("The cloned date is: " + otherD); Person p = new Person("Test Person", new Date(1,1, 1900), null); System.out.println("The person is: " + p); Person other = (Person)p.clone(); System.out.println("The cloned person is: " + other); } } // Question6

7. /** Class for a person with a name and dates for birth and death. Class invariant: A Person always has a date of birth, and if the Person has a date of death, then the date of death is equal to or later than the date of birth. */

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

import java.io.IOException; import java.io.InputStreamReader; import java.io.BufferedReader;

public class Person { private String name; private Date born; private Date died;//null indicates still alive. public Person(String initialName, int birthMonth, int birthDay, int birthYear, int deathIndicator) { if ( deathIndicator <= 0 ) { Date birthDate = new Date(birthMonth, birthDay, birthYear); name = initialName; born = new Date(birthDate); died = null; } else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } // end of if () } public Person(String initialName, String birthMonth, int birthDay, int birthYear, int deathIndicator) { if ( deathIndicator <= 0 ) { Date birthDate = new Date(birthMonth, birthDay, birthYear); name = initialName; born = new Date(birthDate); died = null; } else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } // end of if () } public Person(String initialName, int birthMonth, int birthDay, int birthYear, int deathMonth, int deathDay, int deathYear) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

{ Date birthDate = new Date(birthMonth, birthDay, birthYear); Date deathDate = new Date(deathMonth, deathDay, deathYear); if (consistent(birthDate, deathDate)) { name = initialName; born = new Date(birthDate); if (deathDate == null) died = null; else died = new Date(deathDate); } else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } public Person(String initialName, String birthMonth, int birthDay, int birthYear, String deathMonth, int deathDay, int deathYear) { Date birthDate = new Date(birthMonth, birthDay, birthYear); Date deathDate = new Date(deathMonth, deathDay, deathYear); if (consistent(birthDate, deathDate)) { name = initialName; born = new Date(birthDate); if (deathDate == null) died = null; else died = new Date(deathDate); } else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } public Person(Person original) { if (original == null) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

{ System.out.println("Fatal error."); System.exit(0); } name = original.name; born = new Date(original.born); if (original.died == null) died = null; else died = new Date(original.died); } public void set(String newName, int birthMonth, int birthDay, int birthYear, int deathMonth, int deathDay, int deathYear ) { Date birthDate = new Date(birthMonth, birthDay, birthYear); Date deathDate = new Date(deathMonth, deathDay, deathYear); if (consistent(birthDate, deathDate)) { name = newName; born = new Date(birthDate); if (deathDate == null) died = null; else died = new Date(deathDate); } else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } public void set(String newName, String birthMonth, int birthDay, int birthYear, String deathMonth, int deathDay, int deathYear ) { Date birthDate = new Date(birthMonth, birthDay, birthYear); Date deathDate = new Date(deathMonth, deathDay, deathYear); if (consistent(birthDate, deathDate)) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

name = newName; born = new Date(birthDate); if (deathDate == null) died = null; else died = new Date(deathDate); } else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } public String toString( ) { String diedString; if (died == null) diedString = ""; //Empty string else diedString = died.toString( ); return (name + ", " + born + "-" + diedString); } public boolean equals(Person otherPerson) { if (otherPerson == null) return false; else return (name.equals(otherPerson.name) && born.equals(otherPerson.born) && datesMatch(died, otherPerson.died) ); } /** To match date1 and date2 must either be the same date or both be null. */ private static boolean datesMatch(Date date1, Date date2) { if (date1 == null) return (date2 == null); else if (date2 == null) //&& date1 != null return false; else // both dates are not null. return(date1.equals(date2)); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

} /** Precondition: newDate is a consistent date of birth. Postcondition: Date of birth of the calling object is newDate. */ public void setBirthDate(int month, int day, int year ) { Date newDate = new Date(month, day, year); if (consistent(newDate, died)) born = new Date(newDate); else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } public void setBirthDate(String month, int day, int year ) { Date newDate = new Date(month, day, year); if (consistent(newDate, died)) born = new Date(newDate); else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } }

/** Precondition: newDate is a consistent date of death. Postcondition: Date of death of the calling object is newDate. */ public void setDeathDate(int month, int day, int year ) { Date newDate = new Date(month, day, year); if (!consistent(born, newDate)) { System.out.println("Inconsistent dates. Aborting."); System.exit(0); }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

if (newDate == null) died = null; else died = new Date(newDate); } public void setDeathDate(String month, int day, int year ) { Date newDate = new Date(month, day, year); if (!consistent(born, newDate)) { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } if (newDate == null) died = null; else died = new Date(newDate); } public void setName(String newName) { name = newName; } /** Precondition: The date of birth has been set, and changing the year part of the date of birth will give a consistent date of birth. Postcondition: The year of birth is (changed to) newYear. */ public void setBirthYear(int newYear) { if (born == null) //Precondition is violated { System.out.println("Fata; Error. Aborting."); System.exit(0); } born.setYear(newYear); if (!consistent(born, died)) { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

/** Precondition: The date of death has been set, and changing the year part of the date of death will give a consistent date of death. Postcondition: The year of death is (changed to) newYear. */ public void setDeathYear(int newYear) { if (died == null) //Precondition is violated { System.out.println("Fata; Error. Aborting."); System.exit(0); } died.setYear(newYear); if (!consistent(born, died)) { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } public String getName( ) { return name; } public Date getBirthDate( ) { return new Date(born); } public Date getDeathDate( ) { if (died == null) return null; else return new Date(died); } /** To be consistent, birthDate must not be null. If there is no date of death (deathDate == null), that is consistent with any birthDate. Otherwise, the birthDate must come before or be equal to the deathDate. */ private static boolean consistent(Date birthDate, Date deathDate) { if (birthDate == null) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

return false; else if (deathDate == null) return true; else return (birthDate.precedes(deathDate ) || birthDate.equals(deathDate )); } private class Date { private String month; //always 3 letters long, as in Jan, Feb, etc. private int day; private int year; //a four digit number. public Date( ) { month = "Jan"; day = 1; year = 1000; } public Date(int monthInt, int day, int year) { setDate(monthInt, day, year); } public Date(String monthString, int day, int year) { setDate(monthString, day, year); } public Date(int year) { setDate(1, 1, year); } public Date(Date aDate) { if (aDate == null)//Not a real date. { System.out.println("Fatal Error."); System.exit(0); } month = aDate.month; day = aDate.day; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

year = aDate.year; } public void setDate(int monthInt, int day, int year) { if (dateOK(monthInt, day, year)) { this.month = monthString(monthInt); this.day = day; this.year = year; } else { System.out.println("Fatal Error"); System.exit(0); } } public void setDate(String monthString, int day, int year) { if (dateOK(monthString, day, year)) { this.month = monthString; this.day = day; this.year = year; } else { System.out.println("Fatal Error"); System.exit(0); } } public void setDate(int year) { setDate(1, 1, year); } public void setYear(int year) { if ( (year < 1000) || (year > 9999) ) { System.out.println("Fatal Error"); System.exit(0); } else Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

this.year = year; } public void setMonth(int monthNumber) { if ((monthNumber <= 0) || (monthNumber > 12)) { System.out.println("Fatal Error"); System.exit(0); } else month = monthString(monthNumber); } public void setDay(int day) { if ((day <= 0) || (day > 31)) { System.out.println("Fatal Error"); System.exit(0); } else this.day = day; } public int getMonth( ) { if (month.equals("Jan")) return 1; else if (month.equals("Feb")) return 2; else if (month.equals("Mar")) return 3; else if (month.equals("Apr")) return 4; else if (month.equals("May")) return 5; else if (month.equals("Jun")) return 6; else if (month.equals("Jul")) return 7; else if (month.equals("Aug")) return 8; else if (month.equals("Sep")) return 9; else if (month.equals("Oct")) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

return 10; else if (month.equals("Nov")) return 11; else if (month.equals("Dec")) return 12; else { System.out.println("Fatal Error"); System.exit(0); return 0; //Needed to keep the compiler happy } } public int getDay( ) { return day; } public int getYear( ) { return year; } public String toString( ) { return (month + " " + day + ", " + year); } public boolean equals(Date otherDate) { if (otherDate == null) return false; else return ( (month.equals(otherDate.month)) && (day == otherDate.day) && (year == otherDate.year) ); } public boolean precedes(Date otherDate) { return ( (year < otherDate.year) || (year == otherDate.year && getMonth( ) < otherDate.getMonth( )) || (year == otherDate.year && month.equals(otherDate.month) && day < otherDate.day) ); } public void readInput( ) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

{ boolean tryAgain = true; Scanner keyboard = new Scanner(System.in); while (tryAgain) { System.out.println( "Enter month, day, and year on three lines."); System.out.println( "Enter month, day, and year as three integers."); int monthInput = keyboard.nextInt(); int dayInput = keyboard.nextInt(); int yearInput = keyboard.nextInt(); if (dateOK(monthInput, dayInput, yearInput) ) { setDate(monthInput, dayInput, yearInput); tryAgain = false; } else System.out.println("Illegal date. Reenter input."); } } private boolean dateOK(int monthInt, int dayInt, int yearInt) { return ( (monthInt >= 1) && (monthInt <= 12) && (dayInt >= 1) && (dayInt <= 31) && (yearInt >= 1000) && (yearInt <= 9999) ); } private boolean dateOK(String monthString, int dayInt, int yearInt) { return ( monthOK(monthString) && (dayInt >= 1) && (dayInt <= 31) && (yearInt >= 1000) && (yearInt <= 9999) ); } private boolean monthOK(String month) { return (month.equals("Jan") || month.equals("Feb") || month.equals("Mar") || month.equals("Apr") || month.equals("May") || month.equals("Jun") || month.equals("Jul") || month.equals("Aug") || month.equals("Sep") || month.equals("Oct") || month.equals("Nov") || month.equals("Dec") ); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

private String monthString(int monthNumber) { switch (monthNumber) { case 1: return "Jan"; case 2: return "Feb"; case 3: return "Mar"; case 4: return "Apr"; case 5: return "May"; case 6: return "Jun"; case 7: return "Jul"; case 8: return "Aug"; case 9: return "Sep"; case 10: return "Oct"; case 11: return "Nov"; case 12: return "Dec"; default: System.out.println("Fatal Error"); System.exit(0); return "Error"; //to keep the compiler happy } } } } /** * Question7.java * * * Created: Thu Jan 22 20:42:08 2004 * * @author Adrienne Decker * @version Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

*/ public class Question7 { public static void main(String[] args) { Person p = new Person("Person", 3, 31, 2001, -1); System.out.println("Person is: " + p); Person p1 = new Person("p1", "Mar", 31, 2001, -1); System.out.println("p1 is: " + p1); Person p2 = new Person("p2", 7, 22, 1990, 7, 21, 2001); System.out.println("p2 is: " + p2); Person p3 = new Person("p3", "Jul", 22, 1990, "Jul", 21, 2001); System.out.println("p3 is: " + p3); p1.set("p1 new", 4, 30, 1990, 5, 31, 2005); System.out.println("p1 is now: " + p1); p1.set("p1 even newer", "Jun", 1, 1945, "Jul", 31, 2000); System.out.println("p1 is now: " + p1); p2.setBirthDate(1,1,2000); System.out.println("p2 is now: " + p2); p2.setBirthDate("Aug", 25, 1983); System.out.println("p2 is now: " + p2); p2.setDeathDate("Nov", 13, 2020); System.out.println("p2 is now: " + p2); p2.setDeathDate(12, 15, 2089); System.out.println("p2 is now: " + p2); System.out.println(p3.getBirthDate()); System.out.println(p3.getDeathDate()); } } // Question7

8. /** Class for a person with a name and dates for birth and death. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

Class invariant: A Person always has a date of birth, and if the Person has a date of death, then the date of death is equal to or later than the date of birth. */ import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner;

public class Person implements Cloneable { private String name; private Date born; private Date died;//null indicates still alive. public Person(String initialName, int birthMonth, int birthDay, int birthYear, int deathIndicator) { if ( deathIndicator <= 0 ) { Date birthDate = new Date(birthMonth, birthDay, birthYear); name = initialName; born = new Date(birthDate); died = null; } else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } // end of if () } public Person(String initialName, String birthMonth, int birthDay, int birthYear, int deathIndicator) { if ( deathIndicator <= 0 ) { Date birthDate = new Date(birthMonth, birthDay, birthYear); name = initialName; born = new Date(birthDate); died = null; } else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } // end of if () } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

public Person(String initialName, int birthMonth, int birthDay, int birthYear, int deathMonth, int deathDay, int deathYear) { Date birthDate = new Date(birthMonth, birthDay, birthYear); Date deathDate = new Date(deathMonth, deathDay, deathYear); if (consistent(birthDate, deathDate)) { name = initialName; born = new Date(birthDate); if (deathDate == null) died = null; else died = new Date(deathDate); } else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } public Person(String initialName, String birthMonth, int birthDay, int birthYear, String deathMonth, int deathDay, int deathYear) { Date birthDate = new Date(birthMonth, birthDay, birthYear); Date deathDate = new Date(deathMonth, deathDay, deathYear); if (consistent(birthDate, deathDate)) { name = initialName; born = new Date(birthDate); if (deathDate == null) died = null; else died = new Date(deathDate); } else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

public Person(Person original) { if (original == null) { System.out.println("Fatal error."); System.exit(0); } name = original.name; born = new Date(original.born); if (original.died == null) died = null; else died = new Date(original.died); } public void set(String newName, int birthMonth, int birthDay, int birthYear, int deathMonth, int deathDay, int deathYear ) { Date birthDate = new Date(birthMonth, birthDay, birthYear); Date deathDate = new Date(deathMonth, deathDay, deathYear); if (consistent(birthDate, deathDate)) { name = newName; born = new Date(birthDate); if (deathDate == null) died = null; else died = new Date(deathDate); } else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } public void set(String newName, String birthMonth, int birthDay, int birthYear, String deathMonth, int deathDay, int deathYear ) { Date birthDate = new Date(birthMonth, birthDay, birthYear); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

Date deathDate = new Date(deathMonth, deathDay, deathYear); if (consistent(birthDate, deathDate)) { name = newName; born = new Date(birthDate); if (deathDate == null) died = null; else died = new Date(deathDate); } else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } public String toString( ) { String diedString; if (died == null) diedString = ""; //Empty string else diedString = died.toString( ); return (name + ", " + born + "-" + diedString); } public boolean equals(Person otherPerson) { if (otherPerson == null) return false; else return (name.equals(otherPerson.name) && born.equals(otherPerson.born) && datesMatch(died, otherPerson.died) ); } /** To match date1 and date2 must either be the same date or both be null. */ private static boolean datesMatch(Date date1, Date date2) { if (date1 == null) return (date2 == null); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

else if (date2 == null) //&& date1 != null return false; else // both dates are not null. return(date1.equals(date2)); } /** Precondition: newDate is a consistent date of birth. Postcondition: Date of birth of the calling object is newDate. */ public void setBirthDate(int month, int day, int year ) { Date newDate = new Date(month, day, year); if (consistent(newDate, died)) born = new Date(newDate); else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } public void setBirthDate(String month, int day, int year ) { Date newDate = new Date(month, day, year); if (consistent(newDate, died)) born = new Date(newDate); else { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } }

/** Precondition: newDate is a consistent date of death. Postcondition: Date of death of the calling object is newDate. */ public void setDeathDate(int month, int day, int year ) { Date newDate = new Date(month, day, year); if (!consistent(born, newDate)) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

System.out.println("Inconsistent dates. Aborting."); System.exit(0); } if (newDate == null) died = null; else died = new Date(newDate); } public void setDeathDate(String month, int day, int year ) { Date newDate = new Date(month, day, year); if (!consistent(born, newDate)) { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } if (newDate == null) died = null; else died = new Date(newDate); } public void setName(String newName) { name = newName; } /** Precondition: The date of birth has been set, and changing the year part of the date of birth will give a consistent date of birth. Postcondition: The year of birth is (changed to) newYear. */ public void setBirthYear(int newYear) { if (born == null) //Precondition is violated { System.out.println("Fata; Error. Aborting."); System.exit(0); } born.setYear(newYear); if (!consistent(born, died)) { System.out.println("Inconsistent dates. Aborting."); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

System.exit(0); } } /** Precondition: The date of death has been set, and changing the year part of the date of death will give a consistent date of death. Postcondition: The year of death is (changed to) newYear. */ public void setDeathYear(int newYear) { if (died == null) //Precondition is violated { System.out.println("Fata; Error. Aborting."); System.exit(0); } died.setYear(newYear); if (!consistent(born, died)) { System.out.println("Inconsistent dates. Aborting."); System.exit(0); } } public String getName( ) { return name; } public Date getBirthDate( ) { return new Date(born); } public Date getDeathDate( ) { if (died == null) return null; else return new Date(died); } /** To be consistent, birthDate must not be null. If there is no date of death (deathDate == null), that is consistent with any birthDate. Otherwise, the birthDate must come before or be equal to the deathDate. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

*/ private static boolean consistent(Date birthDate, Date deathDate) { if (birthDate == null) return false; else if (deathDate == null) return true; else return (birthDate.precedes(deathDate ) || birthDate.equals(deathDate )); } public Object clone() { try { Person copy = (Person)super.clone(); return copy; } catch(CloneNotSupportedException e) { return null; } }

private class Date implements Cloneable { private String month; //always 3 letters long, as in Jan, Feb, etc. private int day; private int year; //a four digit number. public Date( ) { month = "Jan"; day = 1; year = 1000; } public Date(int monthInt, int day, int year) { setDate(monthInt, day, year); } public Date(String monthString, int day, int year) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

setDate(monthString, day, year); } public Date(int year) { setDate(1, 1, year); } public Date(Date aDate) { if (aDate == null)//Not a real date. { System.out.println("Fatal Error."); System.exit(0); } month = aDate.month; day = aDate.day; year = aDate.year; } public void setDate(int monthInt, int day, int year) { if (dateOK(monthInt, day, year)) { this.month = monthString(monthInt); this.day = day; this.year = year; } else { System.out.println("Fatal Error"); System.exit(0); } } public void setDate(String monthString, int day, int year) { if (dateOK(monthString, day, year)) { this.month = monthString; this.day = day; this.year = year; } else { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

System.out.println("Fatal Error"); System.exit(0); } } public void setDate(int year) { setDate(1, 1, year); } public void setYear(int year) { if ( (year < 1000) || (year > 9999) ) { System.out.println("Fatal Error"); System.exit(0); } else this.year = year; } public void setMonth(int monthNumber) { if ((monthNumber <= 0) || (monthNumber > 12)) { System.out.println("Fatal Error"); System.exit(0); } else month = monthString(monthNumber); } public void setDay(int day) { if ((day <= 0) || (day > 31)) { System.out.println("Fatal Error"); System.exit(0); } else this.day = day; } public int getMonth( ) { if (month.equals("Jan")) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

return 1; else if (month.equals("Feb")) return 2; else if (month.equals("Mar")) return 3; else if (month.equals("Apr")) return 4; else if (month.equals("May")) return 5; else if (month.equals("Jun")) return 6; else if (month.equals("Jul")) return 7; else if (month.equals("Aug")) return 8; else if (month.equals("Sep")) return 9; else if (month.equals("Oct")) return 10; else if (month.equals("Nov")) return 11; else if (month.equals("Dec")) return 12; else { System.out.println("Fatal Error"); System.exit(0); return 0; //Needed to keep the compiler happy } } public int getDay( ) { return day; } public int getYear( ) { return year; } public String toString( ) { return (month + " " + day + ", " + year); }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

public boolean equals(Date otherDate) { if (otherDate == null) return false; else return ( (month.equals(otherDate.month)) && (day == otherDate.day) && (year == otherDate.year) ); } public boolean precedes(Date otherDate) { return ( (year < otherDate.year) || (year == otherDate.year && getMonth( ) < otherDate.getMonth( )) || (year == otherDate.year && month.equals(otherDate.month) && day < otherDate.day) ); } public void readInput( ) { boolean tryAgain = true; Scanner keyboard = new Scanner(System.in); while (tryAgain) { System.out.println( "Enter month, day, and year on three lines."); System.out.println( "Enter month, day, and year as three integers."); int monthInput = keyboard.nextInt(); int dayInput = keyboard.nextInt(); int yearInput = keyboard.nextInt(); if (dateOK(monthInput, dayInput, yearInput) ) { setDate(monthInput, dayInput, yearInput); tryAgain = false; } else System.out.println("Illegal date. Reenter input."); } } private boolean dateOK(int monthInt, int dayInt, int yearInt) { return ( (monthInt >= 1) && (monthInt <= 12) && (dayInt >= 1) && (dayInt <= 31) && (yearInt >= 1000) && (yearInt <= 9999) ); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

} private boolean dateOK(String monthString, int dayInt, int yearInt) { return ( monthOK(monthString) && (dayInt >= 1) && (dayInt <= 31) && (yearInt >= 1000) && (yearInt <= 9999) ); } private boolean monthOK(String month) { return (month.equals("Jan") || month.equals("Feb") || month.equals("Mar") || month.equals("Apr") || month.equals("May") || month.equals("Jun") || month.equals("Jul") || month.equals("Aug") || month.equals("Sep") || month.equals("Oct") || month.equals("Nov") || month.equals("Dec") ); } private String monthString(int monthNumber) { switch (monthNumber) { case 1: return "Jan"; case 2: return "Feb"; case 3: return "Mar"; case 4: return "Apr"; case 5: return "May"; case 6: return "Jun"; case 7: return "Jul"; case 8: return "Aug"; case 9: return "Sep"; case 10: return "Oct"; case 11: return "Nov"; case 12: Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

return "Dec"; default: System.out.println("Fatal Error"); System.exit(0); return "Error"; //to keep the compiler happy } } } } /** * Question8.java * * * Created: Thu Jan 22 20:42:08 2004 * * @author Adrienne Decker * @version */ public class Question8 { public static void main(String[] args) { Person p = new Person("Person", 3, 31, 2001, -1); System.out.println("Person is: " + p); Person p1 = new Person("p1", "Mar", 31, 2001, -1); System.out.println("p1 is: " + p1); Person p2 = new Person("p2", 7, 22, 1990, 7, 21, 2001); System.out.println("p2 is: " + p2); Person p3 = new Person("p3", "Jul", 22, 1990, "Jul", 21, 2001); System.out.println("p3 is: " + p3); p1.set("p1 new", 4, 30, 1990, 5, 31, 2005); System.out.println("p1 is now: " + p1); p1.set("p1 even newer", "Jun", 1, 1945, "Jul", 31, 2000); System.out.println("p1 is now: " + p1); p2.setBirthDate(1,1,2000); System.out.println("p2 is now: " + p2); p2.setBirthDate("Aug", 25, 1983); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

System.out.println("p2 is now: " + p2); p2.setDeathDate("Nov", 13, 2020); System.out.println("p2 is now: " + p2); p2.setDeathDate(12, 15, 2089); System.out.println("p2 is now: " + p2); System.out.println(p3.getBirthDate()); System.out.println(p3.getDeathDate()); Person copy = (Person)p3.clone(); System.out.println("Clone of p3: " + copy); } } // Question8

9. /** Class Invariant: All objects have a name string and hire date. A name string of "No name" indicates no real name specified yet. A hire date of Jan 1, 1000 indicates no real hire date specified yet. */ import java.util.Scanner; import java.io.InputStreamReader; import java.io.IOException; public class Employee { private String name; private Date hireDate; public Employee( ) { name = "No name"; hireDate = new Date("Jan", 1, 1000); //Just a place holder. } /** Precondition: Neither theName nor theDate are null. */ public Employee(String theName, int month, int day, int year) { if (theName == null) { System.out.println("Fatal Error creating employee."); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

System.exit(0); } name = theName; hireDate = new Date(month, day, year); } public Employee(String theName, String month, int day, int year) { if (theName == null) { System.out.println("Fatal Error creating employee."); System.exit(0); } name = theName; hireDate = new Date(month, day, year); } public Employee(Employee originalObject) { name = originalObject.name; hireDate = new Date(originalObject.hireDate); } public String getName( ) { return name; } public Date getHireDate( ) { return new Date(hireDate); } /** Precondition newName is not null. */ public void setName(String newName) { if (newName == null) { System.out.println("Fatal Error setting employee name."); System.exit(0); } else name = newName; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

/** Precondition newDate is not null. */ public void setHireDate(int month, int day, int year) { hireDate = new Date(month, day, year); } public void setHireDate(String month, int day, int year) { hireDate = new Date(month, day, year); }

public String toString( ) { return (name + " " + hireDate.toString( )); } public boolean equals(Employee otherEmployee) { return (name.equals(otherEmployee.name) && hireDate.equals(otherEmployee.hireDate)); } private class Date { private String month; //always 3 letters long, as in Jan, Feb, etc. private int day; private int year; //a four digit number. public Date( ) { month = "Jan"; day = 1; year = 1000; } public Date(int monthInt, int day, int year) { setDate(monthInt, day, year); } public Date(String monthString, int day, int year) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

setDate(monthString, day, year); } public Date(int year) { setDate(1, 1, year); } public Date(Date aDate) { if (aDate == null)//Not a real date. { System.out.println("Fatal Error."); System.exit(0); } month = aDate.month; day = aDate.day; year = aDate.year; } public void setDate(int monthInt, int day, int year) { if (dateOK(monthInt, day, year)) { this.month = monthString(monthInt); this.day = day; this.year = year; } else { System.out.println("Fatal Error"); System.exit(0); } } public void setDate(String monthString, int day, int year) { if (dateOK(monthString, day, year)) { this.month = monthString; this.day = day; this.year = year; } else { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

System.out.println("Fatal Error"); System.exit(0); } } public void setDate(int year) { setDate(1, 1, year); } public void setYear(int year) { if ( (year < 1000) || (year > 9999) ) { System.out.println("Fatal Error"); System.exit(0); } else this.year = year; } public void setMonth(int monthNumber) { if ((monthNumber <= 0) || (monthNumber > 12)) { System.out.println("Fatal Error"); System.exit(0); } else month = monthString(monthNumber); } public void setDay(int day) { if ((day <= 0) || (day > 31)) { System.out.println("Fatal Error"); System.exit(0); } else this.day = day; } public int getMonth( ) { if (month.equals("Jan")) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

return 1; else if (month.equals("Feb")) return 2; else if (month.equals("Mar")) return 3; else if (month.equals("Apr")) return 4; else if (month.equals("May")) return 5; else if (month.equals("Jun")) return 6; else if (month.equals("Jul")) return 7; else if (month.equals("Aug")) return 8; else if (month.equals("Sep")) return 9; else if (month.equals("Oct")) return 10; else if (month.equals("Nov")) return 11; else if (month.equals("Dec")) return 12; else { System.out.println("Fatal Error"); System.exit(0); return 0; //Needed to keep the compiler happy } } public int getDay( ) { return day; } public int getYear( ) { return year; } public String toString( ) { return (month + " " + day + ", " + year); }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

public boolean equals(Date otherDate) { return ( (month.equals(otherDate.month)) && (day == otherDate.day) && (year == otherDate.year) ); } public boolean precedes(Date otherDate) { return ( (year < otherDate.year) || (year == otherDate.year && getMonth( ) < otherDate.getMonth( )) || (year == otherDate.year && month.equals(otherDate.month) && day < otherDate.day) ); } public void readInput( ) { boolean tryAgain = true; Scanner keyboard = new Scanner(System.in); while (tryAgain) { System.out.println( "Enter month, day, and year on three lines."); System.out.println( "Enter month, day, and year as three integers."); int monthInput = keyboard.nextInt(); int dayInput = keyboard.nextInt(); int yearInput = keyboard.nextInt(); if (dateOK(monthInput, dayInput, yearInput) ) { setDate(monthInput, dayInput, yearInput); tryAgain = false; } else System.out.println("Illegal date. Reenter input."); } } private boolean dateOK(int monthInt, int dayInt, int yearInt) { return ( (monthInt >= 1) && (monthInt <= 12) && (dayInt >= 1) && (dayInt <= 31) && (yearInt >= 1000) && (yearInt <= 9999) ); } private boolean dateOK(String monthString, int dayInt, int yearInt) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

{ return ( monthOK(monthString) && (dayInt >= 1) && (dayInt <= 31) && (yearInt >= 1000) && (yearInt <= 9999) ); } private boolean monthOK(String month) { return (month.equals("Jan") || month.equals("Feb") || month.equals("Mar") || month.equals("Apr") || month.equals("May") || month.equals("Jun") || month.equals("Jul") || month.equals("Aug") || month.equals("Sep") || month.equals("Oct") || month.equals("Nov") || month.equals("Dec") ); } private String monthString(int monthNumber) { switch (monthNumber) { case 1: return "Jan"; case 2: return "Feb"; case 3: return "Mar"; case 4: return "Apr"; case 5: return "May"; case 6: return "Jun"; case 7: return "Jul"; case 8: return "Aug"; case 9: return "Sep"; case 10: return "Oct"; case 11: return "Nov"; case 12: return "Dec"; default: System.out.println("Fatal Error"); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

System.exit(0); return "Error"; //to keep the compiler happy } } } } /** Class Invariant: All objects have a name string, hire date, nonnegative wage rate, and nonnegative number of hours worked. A name string of "No name" indicates no real name specified yet. A hire date of Jan 1, 1000 indicates no real hire date specified yet. */ public class HourlyEmployee extends Employee { private double wageRate; private double hours; //for the month public HourlyEmployee( ) { super( ); wageRate = 0; hours = 0; } /** Precondition: Neither theName nor theDate are null; theWageRate and theHours are nonnegative. */ public HourlyEmployee(String theName, int month, int day, int year, double theWageRate, double theHours) { super(theName, month, day, year); if ((theWageRate >= 0) && (theHours >= 0)) { wageRate = theWageRate; hours = theHours; } else { System.out.println( "Fatal Error: creating an illegal hourly employee."); System.exit(0); } } public HourlyEmployee(String theName, String month, int day, int year, Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

double theWageRate, double theHours) { super(theName, month, day, year); if ((theWageRate >= 0) && (theHours >= 0)) { wageRate = theWageRate; hours = theHours; } else { System.out.println( "Fatal Error: creating an illegal hourly employee."); System.exit(0); } } public HourlyEmployee(HourlyEmployee originalObject) { super(originalObject); wageRate = originalObject.wageRate; hours = originalObject.hours; } public double getRate( ) { return wageRate; } public double getHours( ) { return hours; } /** Returns the pay for the month. */ public double getPay( ) { return wageRate*hours; } /** Precondition: hoursWorked is nonnegative. */ public void setHours(double hoursWorked) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

if (hoursWorked >= 0) hours = hoursWorked; else { System.out.println("Fatal Error: Negative hours worked."); System.exit(0); } } /** Precondition: newWageRate is nonnegative. */ public void setRate(double newWageRate) { if (newWageRate >= 0) wageRate = newWageRate; else { System.out.println("Fatal Error: Negative wage rate."); System.exit(0); } }

public String toString( ) { String result = super.toString(); return result + "\n$" + wageRate + " per hour for " + hours + " hours"; } public boolean equals(HourlyEmployee other) { return (super.equals(other) && wageRate == other.wageRate && hours == other.hours); } }

/** * Question9.java * * * Created: Thu Jan 22 21:10:08 2004 Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

* * @author Adrienne Decker * @version */ public class Question9 { public static void main(String[] args) { Employee emp1 = new Employee("Emp1", 1, 1, 2000); System.out.println("emp1: " + emp1); Employee emp2 = new Employee("Emp2", "Jun", 1, 2002); System.out.println("emp2: " + emp2); System.out.println(emp1.getHireDate()); emp2.setHireDate(11, 18, 1979); System.out.println("emp2 is now: " + emp2); emp2.setHireDate("Jul", 12, 1984); System.out.println("emp2 is now: " + emp2); HourlyEmployee emp3 = new HourlyEmployee("emp3", 1, 1, 2000, 34.56, 40); System.out.println("emp3: " + emp3); HourlyEmployee emp4 = new HourlyEmployee("emp4", "Dec", 12, 1986, 4.15, 25); System.out.println("emp4: " + emp4); } } // Question9

10. /** * Question 10 * * Shape Interface with implementing classes, * Circle and Rectangle. * * Created: Sat Mar 15 2009 * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

* @author Kenrick Mock * @version 1 */ interface Shape { public double area(); } class Circle implements Shape { private double radius; public Circle() { radius = 0; } public Circle(double radius) { this.radius = radius; } public double getRadius() { return radius; } public void setRadius(double newRadius) { radius = newRadius; } public double area() { return 3.14159 * radius * radius; } } class Rectangle implements Shape { private double height, width; public Rectangle() { height = 0; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

width = 0; } public Rectangle(double height, double width) { this.height = height; this.width = width; } public double getWidth() { return width; } public void setWidth(double newWidth) { width = newWidth; } public double getHeight() { return height; } public void setHeight(double newHeight) { height = newHeight; } public double area() { return height * width; } } // Test class public class Question10 { public static void main(String[] args) { Circle c = new Circle(4); Rectangle r = new Rectangle(4,3); ShowArea(c); ShowArea(r); }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

// Displays the area of anything that implements // the Shape interface public static void ShowArea(Shape s) { double area = s.area(); System.out.println("The area of the shape is " + area); } } // Question 10

/** * Question 11 * * Exploring the Comparable interface with sorting. * * Created: Fri Apr 27 2012 * * @author Kenrick Mock * @version 1 */ import java.util.Arrays; public class Question11 { public static void main(String[] args) { Student[] students = new Student[5]; students[0] = new Student("Kenrick",43); students[1] = new Student("Khristy", 34); students[2] = new Student("Kelton", 99); students[3] = new Student("Kyler", 85); students[4] = new Student("Karsten", 42); Arrays.sort(students); for (Student s : students) { System.out.println(s.toString()); } } }

public class Student implements Comparable { private String lastName; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 13, Instructor’s Manual

private int ID; public Student() { lastName = ""; ID = 0; } public Student(String theName, int theID) { lastName = theName; ID = theID; } public String getLastName() { return lastName; } public int getID() { return ID; } public int compareTo(Object other) { Student otherStudent = (Student) other; /* * Uncomment this to compare by ID number instead of lastname if (ID == otherStudent.ID) return 0; if (ID < otherStudent.ID) return -1; return 1; */ return lastName.compareTo(otherStudent.lastName); } public String toString() { return lastName + " " + ID; } } // Question 11

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

Chapter 14

Generics and the ArrayList Class Key Terms generics ArrayList import statement capacity base type set add size for-each loop trimToSize Vector parameterized class generics type parameter instantiate max compareTo bounds for type parameters Brief Outline 14.1 The ArrayList Class Using the ArrayList Class Methods in the class ArrayList The For-Each Loop Immutable Iterators The Vector Class Parameterized Classes and Generics 14.2 Generics Generic Basics Bounds for Type Parameters Generic Methods Inheritance with Generic Classes

Teaching Suggestions This chapter introduces Generics using the ArrayList class. Generics were introduced beginning with Java version 5.0. Students should immediately see the comparison to arrays and note how it is generally much easier to work with ArrayLists. In particular, the ability to grow and shrink makes it a much easier dynamic data structure while the addition of generics allows ArrayLists to store arbitrary data types. If you have given assignments or examples with traditional arrays then it may be instructive to re-do those same programs with ArrayLists instead. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

It is also worthwhile to show the syntax of the for-each loop. This loop helps eliminate one-off errors and is particularly useful when iterating through collections. Key Points Creating an ArrayList Object. An ArrayList is created like any other object except to use generics the base type must be specified in <>. Elements can be accessed using the get and set methods. Why Are Some Parameters of Type Base_Type and Others of Type Object? Usually this is because methods inherited from the class Object are defined with the type Object since the actual type is not known when defined for the Object class. For-each Loop for ArrayList Objects. The for each loop is a good way to iterate through an ArrayList. Class Definition with a Type Parameter. You can define classes with a parameter for a type. These are called generic classes or parameterized classes and are instantiated with a specific data type. Type Parameter Bounds. Type parameters may extend other classes or interfaces. It is common to require a type parameter to extend Comparable, for example, to enforce the implementation of a compareTo method. Tips Summary o fAdding to an ArrayList. To place an element in the ArrayList use the method add. To retrieve an element use the method get. The method size can be used to determine how many elements are stored in the ArrayList. Use trimToSize to Save Memory. This method will trim an ArrayList so it does not have excess capacity. Compile with the –Xlint Option. This option gives warnings that may indicate sources of errors. A Class Definition Can Have More Than One Type Parameter. A generic class definition can have any number of type parameters. Generic Interfaces. An interface can have one or more type parameters.

Pitfalls The clone Method Makes a Shallow Copy. This pitfall refers back to Chapter 5. The clone method does not make a deep copy if the ArrayList elements make references to other objects.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

Nonparametrized ArrayList and Vector Classes. This pitfall explains that prior to Java 5.0 the Vector class did not use generics. For compatibility, the ArrayList and Vector classes with no base type parameter use Object as the base type. A Generic Constructor Name Has No Type Parameter. You do not repeat the type parameter specification <T> in the heading of the constructor definition. You Cannot Plug in a Primitive Type for a Type Parameter. You must use an object. You can use the corresponding Object class for primitives (e.g. Integer for int, Double for double, etc.) Automatic boxing and unboxing will allow you to access these as primitives. A Type Parameter Cannot Be Used Everywhere a Type Name Can Be Used. For example, you cannot use a type parameter T as an invocation of a constructor. An Instantiation of a Generic Class cannot be an Array Base Type. You cannot create an array of generic classes. A Generic Class Cannot Be an Exception Class. Your generic class cannot extend Exception or any descendant of Exception.

Examples Golf Scores. In this example we see an ArrayList to store golf scores. Simple statistics such as the average are computed. A Generic Class for Ordered Pairs. The second example in this chapter shows how to create a Pair class that contains a pair of the same data type specified by the calling class (e.g. String, Integer, etc.)

Programming Projects Answers 1. /** * DepartmentalStore.java * * The program demonstrates the usage of ArrayList class in Java by adding * 5 items from a departmental store into it. Two of the elements in the array * are replaced with new values and finally the ArrayList will be * converted into an array using the methods available in the * ArrayList class before printing the elements in the array on the * screen. * * Created: Feb 6, 2016 * * @author Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

* @version 1 */ public class DepartmentalStore { public static void main(String[] args) { ArrayList<String> itemList = new ArrayList<String>(); int index; System.out.println("Adding five items from the departmental store to the List"); itemList.add("Milk"); itemList.add("Sugar"); itemList.add("Soap"); itemList.add("Bread"); itemList.add("Shampoo"); System.out.println("\nDisplaying all the items in the list\n"); for (index = 0; index < itemList.size(); index++) System.out.print(itemList.get(index) + " ,"); System.out.println("\nTotal Items available in the list : " + itemList.size()); System.out.println("\nSoap item availablity : " + itemList.contains("Soap")); System.out.println("Butter item availablity : " + itemList.contains("Butter")); System.out.println("Replacing Bread with Butter"); index = itemList.indexOf("Bread"); itemList.remove(index); itemList.add(index, "Butter"); String list[] = new String[5]; list = itemList.toArray(list); System.out.println("\nUpdated List is\n"); for (index = 0; index < list.length; index++) System.out.print(list[index] + " ,"); } } 2. /** * WordDatabase.java * * The program lets the user perform actions in a Word Database * that includes: Add, Remove, Display and Search for words inside a Word Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

* Database. The program displays a menu using which the user can * select the operation which the user wishes to perform. * * Created: Feb 6, 2016 * * @author * @version 1 */ import java.util.ArrayList; import java.util.Scanner; public class WordDatabase { public static void main(String[] args) { int choice; boolean flag = true; Dictionary d; ArrayList<Dictionary> wordList = new ArrayList<Dictionary>(20); Scanner keyboard = new Scanner(System.in); while (flag) { System.out.println("\n 1. Add a Term"); System.out.println(" 2. Delete a Term"); System.out.println(" 3. Display All the Terms"); System.out.println(" 4. Search a specific Term"); System.out.println(" 5. Exit"); System.out.print("Enter your choice : "); choice = keyboard.nextInt(); switch (choice) { case 1: d = new Dictionary(); System.out.print("\nEnter the term to add : "); d.setTerm(keyboard.next()); System.out.print("Enter the synonym of the term : "); d.setSynonym(keyboard.next()); wordList.add(d); break; case 2: System.out.print("\nEnter the term to delete : "); String term = keyboard.next(); for (Dictionary d1 : wordList) { if (d1.getTerm().equals(term)) wordList.remove(d1); } break; case 3: for (Dictionary d1 : wordList) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

System.out.println(d1.getTerm() + "," + d1.getSynonym()); break; case 4: System.out.print("\nEnter the term to search : "); int count = 0; term = keyboard.next(); for (Dictionary d1 : wordList) if (d1.getTerm().equals(term)) count++; if (count == 0) System.out.println("Term not found in the list"); else System.out .println("Term found in the " + "list with count : " + count); break; case 5: flag = false; break; default: System.out.println("\n Input Correct Option!" + " Try Again "); } } } } /** * Dictionary class that contains a word and its synonym * */ class Dictionary { private String term; private String synonym; //Accessor and mutator methods public void setTerm(String t) { this.term = t; } public void setSynonym(String d) { this.synonym = d; } public String getTerm() { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

return (term); } public String getSynonym() { return (synonym); } } 3. /** * Question3GPS.java * * This program computes the distance and average speed based * on a set of waypoints. It uses an ArrayList of type Waypoint * to store and calculate the distances. * * Created: Sun Apr 3 2005 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; import java.util.ArrayList; /** * The Waypoint class stores the details for a single waypoint. */ class Waypoint { private double x, y; // Coordinates for the waypoint private int time; // Time in seconds the waypoint was recorded /** * Constructors */ public Waypoint() { time =0; x=0; y=0; } public Waypoint(double x, double y, int time) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

{ this.x = x; this.y = y; this.time = time; } /** * Accessor and mutator methods */ public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } public void setTime(int t) { this.time = t; } public double getX() { return x; } public double getY() { return y; } public int getTime() { return time; } } /** * The GPS class keeps an ArrayList of Waypoints and had * methods to operate on this ArrayList. */ class GPS { private ArrayList<Waypoint> waypoints; public static final double MAPSCALE = 0.1; GPS() { Copyright © 2016 Pearson Education Ltd. All rights reserved.

// 1 unit = 0.1 miles


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

waypoints = new ArrayList<Waypoint>(); } /** * This static method calculates the distance between two points. * @param x1 X coordinate of point 1 * @param y1 Y coordinate of point 1 * @param x2 X coordinate of point 2 * @param y2 Y coordinate of point 2 * @return double Distance between (x1,y1) and (x2,y2)\ */ public static double calcDistance(double x1, double y1, double x2, double y2) { return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } /** * This method inputs data from the keyboard into the ArrayList. */ public void inputData() { String s; Scanner scan = new Scanner(System.in); int t; double x,y; System.out.println("Enter waypoints, one per line, in the format: x y time"); System.out.println("Enter a blank line when finished."); do { s = scan.nextLine(); // Read in a line if (s.length() > 1) { // Extract the coordinates and time from the String using a scanner Scanner waypointScan = new Scanner(s); x = waypointScan.nextDouble(); y = waypointScan.nextDouble(); t = waypointScan.nextInt(); // Create a new waypoint Waypoint w = new Waypoint(x,y,t); // Add it to the ArrayList waypoints.add(w); } } while (s.length() > 1); System.out.println(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

}

/** * totalDistance iterates through the Waypoint arraylist and calculates * the distance between successive points. These distances are summed * and returned. * @return double total Euclidean distance between all points in the Waypoint arraylist. */ public double totalDistance() { double d = 0; Waypoint lastPoint = null, currentPoint = null; if (waypoints.size() < 2) return 0; lastPoint = waypoints.get(0); for (int i=1; i<waypoints.size(); i++) { currentPoint = waypoints.get(i); d += calcDistance(lastPoint.getX(), lastPoint.getY(), currentPoint.getX(), currentPoint.getY()); lastPoint = currentPoint; } return d; } /** * totalTime iterates through the Waypoint arraylist and calculates * the time between successive points. The difference in time is summed * and returned. This assumes that time is increasing with each successive waypoint. * * @return int total time in seconds for the course recorded in the waypoints. */ public int totalTime() { int t = 0; Waypoint lastPoint = null, currentPoint = null; if (waypoints.size() < 2) return 0; lastPoint = waypoints.get(0); for (int i=1; i<waypoints.size(); i++) { currentPoint = waypoints.get(i); t += (currentPoint.getTime() - lastPoint.getTime()); lastPoint = currentPoint; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

return t; } } public class Question3GPS { /** * Main method * In main we create a GPS object, input data from the keyboard, * then calculate and output the total distance, time, and average speed. */ public static void main(String[] args) { GPS g = new GPS(); double totalDistance; int totalTime; g.inputData(); totalDistance = g.totalDistance(); totalTime = g.totalTime(); System.out.printf("The total distance = %3.4f miles.\n", totalDistance * g.MAPSCALE); System.out.printf("The total time = %d seconds, or %3.4f hours.\n", totalTime, totalTime/3600.0); System.out.printf("The average speed is %3.4f miles per hour.", totalDistance*3600*g.MAPSCALE/totalTime); System.out.println(); } } // Question3GPS

4. /** * AverageMarks.java * * This program defines a class called Marks with a generic data type * M, which stores the marks obtained by a student. The program * instantiates Marks class with different type of Numeric data types. * * Created: Feb 7, 2016 * * @author * @version 1 */ import java.util.ArrayList; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

public class AverageMarks { public static void main(String[] args) { Marks<Double> m1 = new Marks<Double>(62.8); Marks<Double> m2 = new Marks<Double>(96.2); Marks<Double> m3 = new Marks<Double>(44.1); Marks<Double> m4 = new Marks<Double>(60.3); ArrayList<Double> marksList = new ArrayList<Double>(4); marksList.add(new Double(m1.getData())); marksList.add(new Double(m2.getData())); marksList.add(new Double(m3.getData())); marksList.add(new Double(m4.getData())); System.out.println("Average Marks.calculateAverage(marksList));

of

the

marks

} } /** * Marks class stores a numeric value(Integer/Double/Float.. etc.) * and defines a method that returns average value of the list of * numbers passed as an argument. * */ class Marks<M> { private M data; /** * Constructor with generic data type M * * @param d * The generic parameter (Can be integer/double/float.. * etc.) */ public Marks(M d) { this.data = d; } //Accessor and mutator methods public void setData(M newData) { data = newData; } public M getData() { Copyright © 2016 Pearson Education Ltd. All rights reserved.

:

"

+


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

return data; } /** * Calculates the average of the list of values passed in the * argument * * @param data * ArrayList that contains a list of numeric values * @return The average value */ public static double calculateAverage(ArrayList data) { double total = 0; for (int index = 0; index < data.size(); index++) { total += (Double) data.get(index); } return (total / data.size()); } } 5. /** * Question5RandomDrawing.java * * This program simulates drawing an item at random out of a box. * It uses a generic class with a parameter of type T so that * a RandomDrawing may be conducted with any object type. An * ArrayList is used to store the objects in the box. * * Created: Sun Apr 3 2005 * * @author Kenrick Mock * @version 1 */ import java.util.ArrayList;

class RandomDrawing<T> { private ArrayList<T> box;

// Holds objects in the box

/** * In the constructor we create a new, empty box, via the ArrayList. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

*/ public RandomDrawing() { box = new ArrayList<T>(); } /** * @param obj - Item to add to the box */ public void add(T obj) { box.add(obj); } /** * @return boolean True if the box is empty (had no items in it). */ public boolean isEmpty() { return (box.size() == 0); } /** * @return T Item that is randomly selected (and removed) from the box, * or null if the box is empty. */ public T drawItem() { if (isEmpty()) return null; // Compute index of random item in box int randIndex = (int) (Math.random() * box.size()); T item = box.get(randIndex); // Get the item box.remove(item); // Remove it return item; } } public class Question5RandomDrawing { /** * In this sample main, we simply add various strings to the box and output each one until * the box is empty. The order we draw the items out of the boxes should be different * upon successive runs of the program. */ public static void main(String[] args) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

{ RandomDrawing<Integer> intBox = new RandomDrawing<Integer>(); RandomDrawing<String> stringBox = new RandomDrawing<String>(); // Add some sample values to the integer box intBox.add(3); intBox.add(10); intBox.add(75); intBox.add(45); // Add some sample values to the string box stringBox.add("Carol"); stringBox.add("Bob"); stringBox.add("Ted"); stringBox.add("Alice"); // Draw from each box until empty System.out.println("Drawing from the box of integers:"); while (!intBox.isEmpty()) { System.out.println(intBox.drawItem()); } System.out.println("Drawing from the box of strings:"); while (!stringBox.isEmpty()) { System.out.println(stringBox.drawItem()); } } } // Question5RandomDrawing

6. /** * Question6Queue.java * * This program implements a priority queue of some type, T. * A priority queue is a type of list where every item added to the * queue also has an associated priority. In this case, the priority * is an integer where larger numbers indicate higher priorities. * Upon removing an item from the list, we only extract the item * that has the highest priority. * * Created: Sun Apr 3 2005 * * @author Kenrick Mock Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

* @version 1 */ import java.util.ArrayList; class PriorityQueue<T> { /** * This inner class pairs an item of type T with a priority. * It is used as the object that is stored in the arraylist for the * priority queue. */ public class PriorityPair<T> { private T item; private int priority; /** * Constructor sets the private instance variables. */ public PriorityPair(T item, int priority) { this.priority = priority; this.item = item; } /** * Accessor methods */ public T getItem() { return item; } public int getPriority() { return priority; } /** * Mutator methods */ public void setItem(T newItem) { item = newItem; } public void setPriority(int newP) { priority = newP; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

} } // Our method variable includes an ArrayList of PriorityPair private ArrayList<PriorityPair> queue; /** * Constructor creates an empty queue */ public PriorityQueue() { queue = new ArrayList<PriorityPair>(); } /** * Adds a new item to the queue with the associated priority * @param item The new item to add to the priority queue * @param priority The priority of the new item, where larger is higher priority */ public void add(T item, int priority) { // Create a new PriorityPair object PriorityPair<T> p = new PriorityPair<T>(item, priority); // Add the object to the queue queue.add(p); } /** * Removes the item from the queue with the highest priority. * Here, highest priority is defined as the item with the largest numerical value. * If the queue is empty, null is returned. * @return T item of the highest priority, or null if the queue is empty. */ public T remove() { if (queue.size()==0) return null; // Search through the queue for the item of highest priority // Item we currently found with the highest priority PriorityPair<T> curHighestPriority = queue.get(0); for (int i=1; i<queue.size(); i++) { if (queue.get(i).getPriority() > curHighestPriority.getPriority()) { // New top priority, so remember it curHighestPriority = queue.get(i); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

} } // Remove item we found with the highest priority queue.remove(curHighestPriority); // Return it return curHighestPriority.getItem(); } } public class Question6Queue { /** * Sample main -- this tests our class by * creating a priority queue of strings and outputting * each one until the queue is empty. */ public static void main(String[] args) { PriorityQueue<String> q = new PriorityQueue<String>(); // Add some sample strings q.add("X", 10); q.add("Y", 1); q.add("Z", 3); q.add("P", 2); // Remove each one from the queue and output it. // Should output X, Z, P, Y. String s; do { s = q.remove(); if (s!=null) { System.out.println("Removed : " + s); } } while (s!=null); } } // Question6Queue

7. /** * Question 7 * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

* ArrayList implementation of the Trivia Game. * Requires the Trivia class from PP 6.13. * * Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; import java.util.ArrayList; public class TriviaGame { private ArrayList<Trivia> trivia; private int score = 0; // Overall score private int questionNum = 0; // Track if question 0 - 4 private static int NUMQUESTIONS = 5; public TriviaGame() // Constructor { trivia = new ArrayList<Trivia>(NUMQUESTIONS); // Manually copy in questions, answers, and values // Note that we need to use NEW to create the instance of each // object to store in the array trivia.add(new Trivia("The first Pokemon that Ash receives from Professor Oak", "pikachu",1)); trivia.add(new Trivia("Erling Kagge skiied into here alone on January 7, 1993", "south pole", 2)); trivia.add(new Trivia("1997 British band that produced 'Tub Thumper'", "chumbawumba", 2)); trivia.add(new Trivia("Who is the tallest person on record (8 ft. 11 in) that has lived?", "Robert Wadlow", 3)); trivia.add(new Trivia("PT Barnum said 'This way to the _______' to attract people to the exit.", "egress", 1)); } // Returns false if there are no more questions to ask. // Otherwise it asks the next question, gets an answer // from the user, and displays if the user was correct or not. public boolean askNextQuestion() { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

if (questionNum >= trivia.size()) { return false; } // Show the current question System.out.println(); System.out.println("Question " + (questionNum + 1)); System.out.println(trivia.get(questionNum).getQuestion()); Scanner kbd = new Scanner(System.in); String guess = kbd.nextLine(); // Check if the answer is correct or not guess = guess.toLowerCase(); String answer = trivia.get(questionNum).getAnswer().toLowerCase(); if (guess.equals(answer)) { System.out.println("That is correct!"); score += trivia.get(questionNum).getValue(); } else { System.out.println("Wrong. The correct answer is " + trivia.get(questionNum).getAnswer()); } // Go to next question questionNum++; return true; } // Displays current score public void showScore() { System.out.println("Your score is " + score); }

// Main method public static void main(String[] args) { TriviaGame game = new TriviaGame(); while (game.askNextQuestion()) { game.showScore(); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

System.out.println("Game over! Thanks for playing!"); } } // Question 7

/** * Question 8 * * ArrayList implementation of recursive file search. * Matching pathnames are stored in the arraylist and returned. * * Created: Fri Apr 27 2012 * * @author Kenrick Mock * @version 1 */ import java.io.File; import java.util.ArrayList; public class FindFile { public static ArrayList<String> searchForFile(File dir, String target) { // This arraylist stores the pathnames of the // matching files ArrayList<String> fileList = new ArrayList<String>(); // If dir is not a directory, return if (!dir.isDirectory()) return fileList; // Check each item in the directory for (File folderItem : dir.listFiles()) { // Recurse if it's a directory if (folderItem.isDirectory()) { // Merge anything returned back into the arraylist ArrayList<String> temp = searchForFile(folderItem,target); fileList.addAll(temp); } // If it's a file, check for a match else { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 14, Instructor’s Manual

if (folderItem.getName().equals(target)) { // Add result to the arraylist fileList.add(folderItem.getAbsolutePath()); } } } return fileList; } public static void main(String[] args) { // The root folder to search File rootFolder = new File("C:\\homeworks\\"); ArrayList<String> result = searchForFile(rootFolder, "filelist.xml"); for (String s : result) System.out.println(s); System.out.println("End of file search."); } } // Question 8 9. No solution provided. 10. No solution provided. 11. No solution provided.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

Chapter 15

Linked Data Structures Key Terms node and link linked list head node empty list traversing a linked list adding a node removing a node automatic garbage collection equals iterator garbage collecting explicit memory management doubly linked list stack push and pop queue tail front back function running time worst-case running time big-O notation linear running time quadratic running time hash table hash map hash function collision chaining sets time-space tradeoff binary tree root node leaf node empty tree inorder Binary Search Tree Storage Rule binary search tree

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

Brief Outline 15.1 Java Linked Lists Working with Linked Lists Node Inner Classes The equals Method for Linked Lists 15.2 Copy Constructors and the clone Method Simple Copy Constructors and clone Methods Exceptions 15.3 Iterators Defining an Iterator Class Adding and Deleting Nodes 15.4 Variations on a Linked List Doubly Linked List The Stack Data Structure The Queue Data Structure Running Times and big-O Notation Efficiency of Linked Lists 15.5 Hash Tables with Chaining A Hash Function for Strings Efficiency of Hash Tables 15.6 Sets Fundamental Operations on Sets Efficiency of Sets Using Linked Lists 15.7 Trees Tree Properties Efficiency of Binary Search Trees Teaching Suggestions This chapter discusses linked data structures in a compact way. This chapter would probably not be appropriate for a formal data structures course, but would be fine for students who have already had a formal treatment of data structures and now want to see them in Java, or as an introduction to data structures. Another element that is missing from this chapter that some instructors might want to introduce is the Java Collections classes, which are talked about in Chapter 16. Some instructors might choose to skip this chapter and go right to Chapter 16. Especially if students have already seen data structures, an introduction to these Java classes would be appropriate. For this chapter, lists are introduced with the class for the Nodes given both as a separate class and as an inner class. The use of Java generics, which are new to Java 5, with linked lists is also discussed. An example is developed that showcases a LinkedList that uses generics. The use of generics is not followed through to all of the chapter examples, but is used for with the Set example and is given as an exercise in the programming projects. Many of the basic issues of developing data structures that use generics are discussed.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

The second section gives a detailed treatment of the clone method, which may be important for some instructors, but is also optional material that may be safely ignored. The third section tackles the topic of Iterators for Linked Lists. In the fourth section, other types of lists are discussed in this chapter including doubly linked, which is given as an exercise at the end of the chapter. Stacks and queues are also formally discussed in the first part of this chapter. A discussion is given on big-O notation so some instructors may wish to delve into the theoretical aspects of time and space efficiency in more detail. The material may also be skipped if desired, in which case the students should skip the paragraphs regarding efficiency. Only short paragraphs are given to the runtime analysis of the different data structures and their associated algorithms. The fifth and sixth sections present data structures for Hash Tables using linear chaining to resolve collisions and simple Sets implemented with linked lists. Both data structures are implemented using linked lists presented in the second section. The HashTable class uses the LinkedList2 class while the Set class uses the generic LinkedList3 class. You may wish to point out the benefits of code reuse to create more abstract data structures. The last section of the chapter deals with trees and more specifically binary search trees. The basic operations and tree traversal are also discussed. Efficiency in a binary search tree is also given as an optional topic at the end of the second section. For a first semester course, these topics may not be appropriate as they may be discussed in other more advanced courses and this chapter is not required for the chapters on GUIs that are forthcoming. These topics are probably more appropriate for a second semester course that lies in between a first course and a data structures course. Key Points Indicating the End of a Linked List. Since in a simple linked list, there is no reference to the end of the list, the most common method for indicating the end is to store a null value in the last element’s link reference, indicating that there is no node that follows it. Any Empty List is Indicated by null. Likewise, when trying to represent the empty list, the head element is set to the value null to indicate that there are not elements in the list. Node Inner Class. Since the equality operator cannot be used on objects, we have the equals method. On Strings, we also have the equalsIgnoreCase method when we are concerned with the content of the String, not necessarily that all of the same words are capitalized within the String. The equalsIgnoreCase can be important especially when taking user input. If you ask the user to input a certain letter as a choice, some of them might instinctively make that letter capital. If you are not ignoring case, equals may return false even if the user has pressed the correct key. Iterators. Iterators allow you to step through all of the elements stored in a collection one at a time.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

The Java Iterator Interface. There is a built in interface to Java to help define iterators for collections. These are discussed in Chapter 15. Stacks. Stacks are a last-in/first-out data structure that can be implementing using a list. Queue. Queues are a first-in/first-out data structure that can be implemented using a list. Hash Tables. A hash table is a data structure that allows quick retrieval of an item using a key that is hashed to a number. It can be implemented using a list. Sets. A set is a data structure that stores an unordered collection of items without duplication. It can be implemented using a list. Binary Search Tree Storage Rule. This box gives a description in brief for the organization of a binary search tree. All of the elements to the left of root are less than the root. All of the elements to the right of the root are greater than the root.

Tips Use a Type Parameter Bound for a Better clone. This tip is in conjunction with the example shown in Displays 15.13 – 15.14, where an interface named PubliclyCloneable is created to help implement Java’s Cloneable interface and ensure that the clone method returns a deep copy. Cloning is an “All or Nothing” Affair. If you decide to implement a clone method, then you should go through all the steps discussed in this section and implement Cloneable and then create your method. If you do not want to do this for some reason, then it would be a good practice to call your method something other than clone.

Pitfalls Privacy Leaks. This pitfall refers back to an idea that is presented in Chapter 5 about returning references to objects from a method. If a reference is returned, then there is free unrestricted access to an object available. Therefore it is not a good idea to simply return a reference. One solution that is presented is to make Node a private inner class of the list. Using Node Instead of Node<T>. When you have an inner class that uses generics, like the Node class in the example in Display 15.8, it is important that variables that reference Node are given the type Node<T> so that the generic type can be substituted in at run-time. This pitfall does not go on to explain what will happen if you leave off the <T> other than to say that you may or may not get a compiler error/warning. What will happen is that the compiler will interpret the type for the generic as Object, which may or may not cause a problem within the code.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

The clone Method is Protected in Object. This pitfall explains why copyOf in the generic linked list class is written as it is. This is due to the fact that clone is a protected method in the class Object and it is explained why this decision was made by Java developers.

Examples A Simple Linked List Class. In this example we see a simple linked list with a separate Node class. The list has methods for adding an element, deleting the head node, getting the size of th list, finding a node in the list, and outputting the list to the screen. A Generic Linked List. The second example in this chapter looks at creating a list that does not specify what type of element is stored inside it using the new Java 5 feature of generics. This makes the list applicable to more elements. It also foreshadows how the Java Collections classes work. A Linked List with a Deep Copy clone Method. This example illustrates a generic linked list that has a deep copy clone method. A doubly linked list. This example illustrates how to create a doubly linked list including insertion and deletion from the list. A Stack Class. This example shows how to create a simple stack. A Queue Class. This example shows how to create a FIFO queue. A Hash Table Class. This example shows how to hash a String using a simple hash function that sums the ASCII values in the String and computes the modulus given the size of an array. Each array entry stores a linked list of items. Sets Using Linked Lists. This is an implementation of sets using a generic linked list to store the items in the set. A Binary Search Tree Class. This is an implementation of the binary search tree using integers. It provides insertion, contains, and a show elements method.

Programming Projects Answers 1. /** * Question1Suitor.java * * This program determines where to stand in line if you would * like to win the hand of the princess. The princess eliminates * every third suitor and loops back to the beginning of the line upon * reaching the end. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

* * This program uses a circular linked list * to store the list of suitors and removes * each one in turn. * * Created: Sun Apr 3 2005 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; /** * SuitorNode is a class that is used for a linked list * of suitors within the Suitor class. The linked list is * circular where the tail points back to the head. */ class SuitorNode { private int num=0; // Suitor's position in line private SuitorNode next=null; // Reference to next suitor /** * SuitorNode constructor, initializes number */ public SuitorNode(int num) { this.num = num; } /* Accessor and mutator methods */ public int getNum() { return num; } public SuitorNode getNext() { return next; } public void setNext(SuitorNode nextNode) { next = nextNode; } } /** * Suitor contains the main code that creates the linked list of suitors Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

* and eliminates them one by one. */ public class Question1Suitor { /** * Main method constructs and manipulates the linked list */ public static void main(String[] args) { // Variable declarations int numSuitors; SuitorNode current = null; // Linked list of suitors SuitorNode tail = null; // Tracks end of list as it is constructed SuitorNode prev = null; // Tracks previous node as we eliminate suitors Scanner scan = new Scanner(System.in); System.out.println("Enter the number of suitors:"); numSuitors = scan.nextInt(); if (numSuitors > 0) { current = new SuitorNode(1); current.setNext(current); // Make into a circular list tail = current; for (int i=1; i<numSuitors; i++) { // Add new node to the end of the list SuitorNode temp = new SuitorNode(i+1); temp.setNext(tail.getNext()); tail.setNext(temp); tail = temp; } } if (numSuitors <=0) { System.out.println("Not enough suitors."); } else if (numSuitors == 1) { System.out.println("You would stand first in line."); } else { // Eliminate a suitor as long as there is at least one while (current.getNext() != current) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

{ // Count three people ahead, or go two people down // since we include the current person in the count for (int i=0; i<2; i++) { prev = current; current = current.getNext(); } // Eliminate contestant current prev.setNext(current.getNext()); // Skip over this node current = prev.getNext(); } System.out.println("To win the princess, " + "you should stand in position " + current.getNum()); } } } // Question1Suitor

2. /** * WordLinkedList.java * * The program implements a linked list of words using a class that * contains data and reference to the next element. The program * displays a menu with all possible operations which the user can perform * on the linked list. * * Created: Feb 7, 2016 * * @author * @version 1 */ import java.util.Scanner; public class WordLinkedList { private Node head; /** * Default constructor that sets null to the Head of the linked * list */ public WordLinkedList() { head = null; }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

/** * Adds the specified data item to a new node and places the node * at the start of the linked list * * @param itemName * String value to be stored in the node */ public void addToStart(String itemName) { head = new Node(itemName, head); } /** * Adds a new node with specified data item at the specified * position * * @param itemName * String value to be stored in the node * @param pos * Position at which the node has to be inserted */ public void addAtAPosition(String itemName, int pos) { if (pos < 1 || pos > size() + 1) System.out.println("Position is out of Range !!!"); else if (pos == 1) { addToStart(itemName); System.out.println("\nWord has been added to the list"); } else { Node temp = head, temp1 = new Node(); for (int index = 1; index < pos - 1; index++) temp = temp.getLink(); temp1.setItem(itemName); temp1.setLink(temp.getLink()); temp.setLink(temp1); System.out.println("\nWord has been added to the list"); } } /** * Deleted the first node in the linked list * * @return True of the item is deleted. False if the linked list * is empty */ public boolean deleteHeadNode() { if (head != null) { head = head.getLink(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

return true; } else return false; } /** * Deletes the node at the specified position in the linked list * * @param pos * Position at which the node has to be removed from */ public void deleteFromAPosition(int pos) { if (pos < 1 || pos > size()) System.out.println("Position is out of Range !!!"); else if (pos == 1) deleteHeadNode(); else { Node temp = head; for (int index = 1; index < pos - 1; index++) temp = temp.getLink(); temp.setLink(temp.getLink().getLink()); System.out.println("\nWord has been deleted from the list"); } } /** * Returns the size of the linked list * * @return Size of the linked list */ public int size() { int count = 0; Node position = head; while (position != null) { count++; position = position.getLink(); } return count; } /** * Checks whether the specified element exists in the linked list * * @param item * Item to be searched for * @return True if the item found in the list. False otherwise. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

*/ public boolean contains(String item) { return (find(item) != null); } private Node find(String target) { Node position = head; String itemAtPosition; while (position != null) { itemAtPosition = position.getItem(); if (itemAtPosition.equals(target)) return position; position = position.getLink(); } return null; //target was not found } /** * Displays the items in the list along with their position */ public void outputList() { Node position = head; int index = 1; if (size() == 0) System.out.println("\n List is Empty"); else { while (position != null) { System.out.println(index + "\t" + position.getItem()); position = position.getLink(); index++; } } } public static void main(String s[]) { WordLinkedList list = new WordLinkedList(); boolean flag = true; int choice; Scanner keyboard = new Scanner(System.in); while (flag) { System.out.println(" 1. Insert word in the beginning"); System.out.println(" 2. Insert word at a given position"); System.out.println(" 3. Delete word from the beginning"); System.out.println(" 4. Delete word from a given position"); System.out.println(" 5. Display complete List"); System.out.println(" 6. Search a specific word"); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

System.out.println(" 7. Exit"); System.out.print("Enter your choice : "); choice = keyboard.nextInt(); switch (choice) { case 1: System.out.print("\nEnter the word to add : "); list.addToStart(keyboard.next()); System.out.println("\nWord has been added to the list"); break; case 2: System.out.print("\nEnter the word to add : "); String term = keyboard.next(); System.out.print("\nEnter the position : "); int pos = keyboard.nextInt(); list.addAtAPosition(term, pos); break; case 3: if (list.deleteHeadNode() == false) System.out.println("\nList is already Empty !"); else System.out.println("\nHead Node deleted !"); break; case 4: System.out.print("\nEnter the position : "); pos = keyboard.nextInt(); list.deleteFromAPosition(pos); break; case 5: list.outputList(); break; case 6: System.out.print("\nEnter the word to search : "); term = keyboard.next(); if (list.contains(term) == true) System.out.println("\n Word has been found in the list"); else System.out.println("\n Has not been found in the list"); break; case 7: flag = false; break; default: System.out.println("\nInput Correct Option! Try Again "); } } } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

} /** * Class that contains data item and link to the next element in the * linked list */ class Node { private String item; private Node link; /** * Default constructor that sets null to the data item and link */ public Node() { link = null; item = null; } /** * Constructor that initializes data and link with the specified * values * * @param newItem * Data to be stored in the node * @param linkValue * Link to the next element */ public Node(String newItem, Node linkValue) { this.item = newItem; link = linkValue; } //Accessor and mutators public void setItem(String newItem) { item = newItem; } public void setLink(Node newLink) { link = newLink; } public String getItem() { return item; }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

public Node getLink() { return link; } } 3. /** * IntegerStack.java * * The program implements a Stack data structure that stores integer * values. The program displays a menu with all possible operations which * the user can perform on the Stack of integers. * * Created: Feb 7, 2016 * * @author * @version 1 */ import java.util.Scanner; public class IntegerStack { private NewNode head; /** * Default constructor */ public IntegerStack() { head = null; } /** * Method that inserts the specified value at the top of the stack * * @param itemValue * Value to be inserted */ public void push(int itemValue) { head = new NewNode(itemValue, head); } /** * Method that removes the top element from the stack * * @return Value at the top of the stack */ public boolean pop() { if (head != null) { head = head.getLink(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

return true; } else return false; } /** * Returns the size of the Stack * * @return Size of the Stack */ public int size() { int count = 0; NewNode position = head; while (position != null) { count++; position = position.getLink(); } return count; } /** * Prints the elements in the Stack along with their position */ public void outputStack() { NewNode position = head; int index = 1; if (size() == 0) System.out.println("\n The List is Empty"); else { while (position != null) { System.out.println(index + "\t" + position.getItem()); position = position.getLink(); index++; } } } public static void main(String s[]) { IntegerStack stk = new IntegerStack(); boolean flag = true; int choice; Scanner keyboard = new Scanner(System.in); while (flag) { System.out.println(" 1. PUSH"); System.out.println(" 2. POP"); System.out.println(" 3. Display"); System.out.println(" 4. Exit"); System.out.print("Enter your choice : "); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

choice = keyboard.nextInt(); switch (choice) { case 1: System.out.print("\nEnter the value to add : "); stk.push(keyboard.nextInt()); System.out.println("\nValue has been pushed to the Stack"); break; case 2: if (stk.pop() == false) System.out.println("\nStack is already Empty !"); else System.out.println("\nValue Popped !"); break; case 3: stk.outputStack(); break; case 4: flag = false; break; default: System.out.println("\n Input Correct Option ! Try Again "); } } } } /** * Class that stores the integer value and the link to the next * element in the stack */ class NewNode { private int item; private NewNode link; /** * Default constructor that sets null to the data item and link */ public NewNode() { link = null; } /** * Constructor that initializes data and link with the specified * values * * @param newItem * Data to be stored in the node Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

* @param linkValue * Link to the next element */ public NewNode(int newItem, NewNode linkValue) { this.item = newItem; link = linkValue; } public void setItem(int newItem) { item = newItem; } public void setLink(NewNode newLink) { link = newLink; } public int getItem() { return item; } public NewNode getLink() { return link; } } 4. /** * * The program implements a double ended Queue in which data can be * inserted and removed from both the ends. The program displays a * menu with all possible operations the user can perform on the * double ended Queue. * * Created: Feb 7, 2016 * * @author * @version 1 */ import java.util.Scanner; public class IntegerDQueue { private NewNode front; /** * Default constructor */ public IntegerDQueue() { front = null; }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

/** * Add an element from the front * * @param itemValue * The value to be added */ public void addFromFront(int itemValue) { front = new NewNode(itemValue, front); System.out.println("\nValue has been added from the Front"); } /** * Add an element from the rear end of the queue * * @param itemValue * The value to be added */ public void addFromRear(int itemValue) { if (front == null) addFromFront(itemValue); else { NewNode temp = new NewNode(), rear; for (rear = front; rear.getLink() != null; rear = rear.getLink()) ; temp.setItem(itemValue); rear.setLink(temp); System.out.println("\nValue has been added from the rear"); } } /** * Delete the item at the front end of the Queue * * @return True if the item is deleted. False if the list is * empty. */ public boolean deleteFromFront() { if (front != null) { front = front.getLink(); return true; } else return false; } /** Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

* Delete the item at the rear end of the Queue * * @return True if the item is deleted. False if the list is * empty. */ public void deleteFromRear() { if (front == null) System.out.println("De-Queue is already Empty !!!"); else { NewNode rear = front, previous = front; for (rear = front; rear.getLink() != null; rear = rear.getLink()) previous = rear; if (front == rear) front = null; else { previous.setLink(null); System.out.println("\nData has been deleted from the list"); } } } /** * Returns the size of the Queue * * @return Size of the Queue */ public int size() { int count = 0; NewNode position = front; while (position != null) { count++; position = position.getLink(); } return count; } /** * Displays the items in the Queue along with their positions */ public void outputDQueue() { NewNode position = front; if (size() == 0) System.out.println("\n The List is Empty"); else { while (position != null) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

System.out.print(position.getItem() + ", "); position = position.getLink(); } } } public static void main(String s[]) { IntegerDQueue queue = new IntegerDQueue(); boolean flag = true; int choice; Scanner keyboard = new Scanner(System.in); while (flag) { System.out.println("\n 1. Add from Front"); System.out.println(" 2. Add from Rear"); System.out.println(" 3. Delete from Front"); System.out.println(" 4. Delete from Rear"); System.out.println(" 5. Display"); System.out.println(" 6. Exit"); System.out.print("Enter your choice : "); choice = keyboard.nextInt(); switch (choice) { case 1: System.out.print("\nEnter the value to add : "); queue.addFromFront(keyboard.nextInt()); break; case 2: System.out.print("\nEnter the value to add : "); queue.addFromRear(keyboard.nextInt()); break; case 3: if (queue.deleteFromFront() == false) System.out.println("De-Queue is already Empty !!!"); break; case 4: queue.deleteFromRear(); break; case 5: queue.outputDQueue(); break; case 6: flag = false; break; default: System.out.println("\n Input Correct Option ! Try Again "); } } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

} } /** * Class that stores the integer value and the link to the next * element in the stack. */ class NewNode { private int item; private NewNode link; /** * Default constructor that sets null to the data item and link */ public NewNode() { link = null; } /** * Constructor that initializes data and link with the specified * values * * @param newItem * Data to be stored in the node * @param linkValue * Link to the next element */ public NewNode(int newItem, NewNode linkValue) { this.item = newItem; link = linkValue; } //Accessor and mutators public void setItem(int newItem) { item = newItem; } public void setLink(NewNode newLink) { link = newLink; } public int getItem() { return item; } public NewNode getLink() { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

return link; } } 5. No solution given. 6. /** * Question6.java * * This program is essentially the same as GenericLinkedList.java from the * textbook. The code has been modified slightly to call the addSorted * method and to put the data in an unsorted order to illustrate that * they are added in sorted order. * * Created: Thu Mar 22 2007 * * @author Kenrick Mock * @version 1 */ public class Question6 { public static void main(String[] args) { LinkedList3<Entry> list = new LinkedList3<Entry>( ); Entry entry2 = new Entry("Bananas", 2); list.addSorted(entry2); Entry entry1 = new Entry("Apples", 1); list.addSorted(entry1); Entry entry3 = new Entry("Cantaloupe", 3); list.addSorted(entry3); System.out.println("List has " + list.size( ) + " nodes."); list.outputList( ); System.out.println("End of list."); } } // Question 6

// We must implement comparable so the LinkedList3 class Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

// can compare two Entry objects. public class Entry implements Comparable { private String item; private int count; public Entry(String itemData, int countData) { item = itemData; count = countData; } public String toString( ) { return (item + " " + count); } /** * compareTo * This method must be implemented since Entry implements Comparable. * It simply compares the two strings stored in "item". * @param otherObject item to compare to this object */ public int compareTo(Object otherObject) throws ClassCastException { if (otherObject == null) throw new ClassCastException("A Entry object expected."); else if (getClass( ) != otherObject.getClass( )) throw new ClassCastException("A Entry object expected."); else { Entry otherEntry = (Entry) otherObject; return (item.compareTo(otherEntry.item)); } } public boolean equals(Object otherObject) { if (otherObject == null) return false; else if (getClass( ) != otherObject.getClass( )) return false; else { Entry otherEntry = (Entry)otherObject; return (item.equals(otherEntry.item) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

&& (count == otherEntry.count)); } } // <There should be other constructors and methods, including accessor and // mutator methods, but we do not use them in this demonstration.> } // Entry for Question 6

/** * The addSorted method is the only new method added * to this class from the chapter. T has been modified * to extend Comparable. */ public class LinkedList3<T extends Comparable> { private class Node<T> { private T data; private Node<T> link; public Node( ) { data = null; link = null; } public Node(T newData, Node<T> linkValue) { data = newData; link = linkValue; } }//End of Node<T> inner class private Node<T> head; public LinkedList3( ) { head = null; } /** Adds a node at the start of the list with the specified data. The added node will be the first node in the list. */ Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

public void addToStart(T itemData) { head = new Node<T>(itemData, head); } /** * addSorted * Adds a node to the list so the list is in sorted order. * This is done by searching for a node whose value is * greater than the new item to insert. The new item is * then placed before the greater node. * @param itemData new data to add to the list. It must * be a class that implements Comparable. */ public void addSorted(T itemData) { if (head == null) { // Adding first node head = new Node<T>(itemData, head); } else { // Search for a node where the new data // is greater than the current data // and insert in between Node<T> previous = null; Node<T> current = head; T itemAtPosition; while (current != null) { itemAtPosition = current.data; if (itemAtPosition.compareTo(itemData) >= 0) { // The item to insert should go before // itemAtPosition. But check if this is // the head of the list. if (previous == null) { // Insert at the head head = new Node<T>(itemData, head); break; } else { // Insert somewhere in the middle Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

Node<T> newNode = new Node<T>(itemData, previous.link); previous.link = newNode; break; } } // Move to next node previous = current; current = current.link; } // If we reach the end of the list, add to the end if (current == null) { Node<T> newNode = new Node<T>(itemData, null); previous.link = newNode; } } } /** Removes the head node and returns true if the list contains at least one node. Returns false if the list is empty. */ public boolean deleteHeadNode( ) { if (head != null) { head = head.link; return true; } else return false; } /** Returns the number of nodes in the list. */ public int size( ) { int count = 0; Node<T> position = head; while (position != null) { count++; position = position.link; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

} return count; } public boolean contains(T item) { return (find(item) != null); } /** Finds the first node containing the target item, and returns a reference to that node. If target is not in the list, null is returned. */ private Node<T> find(T target) { Node<T> position = head; T itemAtPosition; while (position != null) { itemAtPosition = position.data; if (itemAtPosition.equals(target)) return position; position = position.link; } return null; //target was not found } /** Finds the first node containing the target and returns a reference to the data in that node. If target is not in the list, null is returned. */ public T findData(T target) { return find(target).data; } public void outputList( ) { Node<T> position = head; while (position != null) { System.out.println(position.data); position = position.link; } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

public boolean isEmpty( ) { return (head == null); } public void clear( ) { head = null; } /* For two lists to be equal they must contain the same data items in the same order. The equals method of T is used to compare data items. */ public boolean equals(Object otherObject) { if (otherObject == null) return false; else if (getClass( ) != otherObject.getClass( )) return false; else { LinkedList3<T> otherList = (LinkedList3<T>)otherObject; if (size( ) != otherList.size( )) return false; Node<T> position = head; Node<T> otherPosition = otherList.head; while (position != null) { if (!(position.data.equals(otherPosition.data))) return false; position = position.link; otherPosition = otherPosition.link; } return true; //no mismatch was not found } } } // LinkedList3 for Question 6

7. /** * Question7.java * * This program tests the modified Set class. The modified Set class Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

* implements a remove method and an iterator. * * Created: Fri Mar 22 2007 * * @author Kenrick Mock * @version 1 */ public class Question7 { public static void main(String[] args) { // Round things Set round = new Set<String>(); // Add some data to the set round.add("peas"); round.add("ball"); round.add("pie"); round.add("grapes"); System.out.println("Contents of set 'round': "); round.output(); // Delete some round things round.remove("peas"); round.remove("grapes"); System.out.println("Contents of set 'round' after removing" + " grapes and peas: "); // Output the data using the iterator Set<String>.SetIterator i = round.iterator( ); i.restart(); while(i.hasNext( )) System.out.println(i.next( )); System.out.println( ); } } // Question 7

// Uses a linked list as the internal data structure // to store items in a set. import java.util.NoSuchElementException; public class Set<T> { private class Node<T> Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

{ private T data; private Node<T> link; public Node( ) { data = null; link = null; } public Node(T newData, Node<T> linkValue) { data = newData; link = linkValue; } }//End of Node<T> inner class

/** A simple forward iterator for the Set class. It is essentially the same as the List2Iterator from the textbook. */ public class SetIterator { private Node<T> position; private Node<T> previous; //previous value of position public SetIterator( ) { position = Set.this.head; //Instance variable head of outer class. previous = null; } public void restart( ) { position = head; //Instance variable head of outer class. previous = null; } public T next( ) { if (!hasNext( )) throw new NoSuchElementException( ); T toReturn = position.data; previous = position; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

position = position.link; return toReturn; } public boolean hasNext( ) { return (position != null); } /** Adds a node before the node at location position. previous is placed at the new node. If hasNext( ) is false, then the node is added to the end of the list. If the list is empty, inserts node as the only node. */ public void addHere(T newData) { if (position == null && previous != null) //if at end of list previous.link = new Node<T>(newData, null); else if (position == null || previous == null) //else if list is empty or position is at head node. Set.this.add(newData); else//previous and position are located //at two consecutive nodes. { Node<T> temp = new Node<T>(newData, position); previous.link = temp; previous = temp; } } /** Changes the String in the node at location position. Throws an IllegalStateException if position is not at a node, */ public void changeHere(T newData) { if (position == null) throw new IllegalStateException( ); else position.data = newData; } /** Deletes the node at location position and Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

moves position to the "next" node. Throws an IllegalStateException if the list is empty. */ public void delete( ) { if (position == null) throw new IllegalStateException( ); else if (previous == null) {//remove node at head head = head.link; position = head; } else //previous and position are at two nodes. { previous.link = position.link; position = position.link; } } }//End of SetIterator inner class //********** Set Class Methods ****************** private Node<T> head; // Head of the list that implements the set public Set() { head = null; } /** * iterator * Returns an iterator to the set. */ public SetIterator iterator( ) { return new SetIterator( ); } /** * remove * This method iterates through the list and removes the * first one it finds that equals item. It assumes that * the equals() method has been implemented by class T. * @param item data item to remove from the list */ public void remove(T item) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

Node<T> position = head; Node<T> previous = null; T itemAtPosition; while (position != null) { itemAtPosition = position.data; if (itemAtPosition.equals(item)) { // Delete this item if (previous == null) { // We're delete the head head = head.link; } else { // We're deleting something past the head. // Link past it. previous.link = position.link; } return; } previous = position; position = position.link; } } /** Add a new item to the set. If the item is already in the set, false is returned, otherwise true is returned. */ public boolean add(T newItem) { if (!contains(newItem)) { head = new Node<T>(newItem, head); return true; } return false; } public boolean contains(T item) { Node<T> position = head; T itemAtPosition; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

while (position != null) { itemAtPosition = position.data; if (itemAtPosition.equals(item)) return true; position = position.link; } return false; //target was not found } public void output( ) { Node position = head; while (position != null) { System.out.print(position.data.toString() + " "); position = position.link; } System.out.println(); } /** Returns a new set that is the union of this set and the input set. */ public Set<T> union(Set<T> otherSet) { Set<T> unionSet = new Set<T>(); // Copy this set to unionSet Node<T> position = head; while (position != null) { unionSet.add(position.data); position = position.link; } // Copy otherSet items to unionSet. // The add method eliminates any duplicates. position = otherSet.head; while (position != null) { unionSet.add(position.data); position = position.link; } return unionSet; }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

/** Returns a new that is the intersection of this set and the input set. */ public Set<T> intersection(Set<T> otherSet) { Set<T> interSet = new Set<T>(); // Copy only items in both sets Node<T> position = head; while (position != null) { if (otherSet.contains(position.data)) interSet.add(position.data); position = position.link; } return interSet; } /** The clear, size, and isEmpty methods are identical to those in Display 15.8 for the LinkedList3 class. */ } // Set class for Question 7 8. /** * Question8.java * * This program creates a hash table of Employee objects * and tests it by retrieving several objects. This uses the Date * class defined in Chapter 5. The source code for this class is * not repeated again here. * * Created: Fri Mar 22 2007 * * @author Kenrick Mock * @version 1 */ public class Question8 { public static void main(String[] args) { HashTable h = new HashTable<Employee>();

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

System.out.println("Adding Parker Kelly, John Jones, and Kelly Parker"); h.put("Parker Kelly", new Employee("Parker Kelly", new Date(4,18,1968))); h.put("John Jones", new Employee("John Jones", new Date(3,22,1989))); h.put("Kelly Parker", new Employee("Kelly Parker", new Date(2,13,1977))); // The get method looks strange. The first parameter is the hash // key while the second is an object that can be used for comparison // to the objects stored in the hash table. In this case, the equals() // method checks to see if the names match, so the second parameter // serves as a query object to match Employees to the query. // We only need to fill in the name since that is the only variable used. System.out.println("Parker Kelly in hash table? "); Employee e1 = (Employee) h.get("Parker Kelly", new Employee("Parker Kelly")); if (e1 != null) System.out.println("True"); else System.out.println("False"); System.out.println("John Adams in hash table? "); Employee e2 = (Employee) h.get("John Adams", new Employee("John Adams")); if (e2 != null) System.out.println("True"); else System.out.println("False"); // Retrieve just using the name, but output the date from the // retrieved object. Employee e3 = (Employee) h.get("Kelly Parker", new Employee("Kelly Parker")); System.out.println("Details for Kelly Parker: " + e3.toString()); System.out.println(); } } // Question 8

/** Almost the same as the class defined in Chapter 7, with the addition of an equals method to override that defined in class Object. */ public class Employee { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

private String name; private Date hireDate; public Employee( ) { name = "No name"; hireDate = new Date("Jan", 1, 1000); //Just a placeholder. } /** * Another constructor that sets the name but * uses the default date */ public Employee(String theName) { name = theName; hireDate = new Date(); } /** Precondition: Neither theName nor theDate is null. */ public Employee(String theName, Date theDate) { if (theName == null || theDate == null) { System.out.println("Fatal Error creating employee."); System.exit(0); } name = theName; hireDate = new Date(theDate); } public Employee(Employee originalObject) { name = originalObject.name; hireDate = new Date(originalObject.hireDate); } public String getName( ) { return name; } public Date getHireDate( ) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

return new Date(hireDate); } /** Precondition newName is not null. */ public void setName(String newName) { if (newName == null) { System.out.println("Fatal Error setting employee name."); System.exit(0); } else name = newName; } /** Precondition newDate is not null. */ public void setHireDate(Date newDate) { if (newDate == null) { System.out.println("Fatal Error setting employee hire date."); System.exit(0); } else hireDate = new Date(newDate); } public String toString( ) { return (name + " " + hireDate.toString( )); } public boolean equals(Employee otherEmployee) { return (name.equals(otherEmployee.name) && hireDate.equals(otherEmployee.hireDate)); } /** * equals * We must override the equals method inherited from Object. * In this case we are only checking for the names to be equal. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

*/ public boolean equals(Object otherObject) { Employee otherEmp = (Employee) otherObject; return (name.equals(otherEmp.name)); } } // Employee class for Question 8

// Generic Linked List class public class LinkedList3<T> { private class Node<T> { private T data; private Node<T> link; public Node( ) { data = null; link = null; } public Node(T newData, Node<T> linkValue) { data = newData; link = linkValue; } }//End of Node<T> inner class private Node<T> head; public LinkedList3( ) { head = null; } /** Adds a node at the start of the list with the specified data. The added node will be the first node in the list. */ public void addToStart(T itemData) { head = new Node<T>(itemData, head); }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

/** Removes the head node and returns true if the list contains at least one node. Returns false if the list is empty. */ public boolean deleteHeadNode( ) { if (head != null) { head = head.link; return true; } else return false; } /** Returns the number of nodes in the list. */ public int size( ) { int count = 0; Node<T> position = head; while (position != null) { count++; position = position.link; } return count; } public boolean contains(T item) { return (find(item) != null); } /** Finds the first node containing the target item, and returns a reference to that node. If target is not in the list, null is returned. */ private Node<T> find(T target) { Node<T> position = head; T itemAtPosition; while (position != null) { itemAtPosition = position.data; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

if (itemAtPosition.equals(target)) { return position; } position = position.link; } return null; //target was not found } /** Finds the first node containing the target and returns a reference to the data in that node. If target is not in the list, null is returned. */ public T findData(T target) { Node<T> result = find(target); if (result == null) return null; else return result.data; } public void outputList( ) { Node<T> position = head; while (position != null) { System.out.println(position.data); position = position.link; } } public boolean isEmpty( ) { return (head == null); } public void clear( ) { head = null; } /* For two lists to be equal they must contain the same data items in the same order. The equals method of T is used to compare data items. */ Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

public boolean equals(Object otherObject) { if (otherObject == null) return false; else if (getClass( ) != otherObject.getClass( )) return false; else { LinkedList3<T> otherList = (LinkedList3<T>)otherObject; if (size( ) != otherList.size( )) return false; Node<T> position = head; Node<T> otherPosition = otherList.head; while (position != null) { if (!(position.data.equals(otherPosition.data))) return false; position = position.link; otherPosition = otherPosition.link; } return true; //no mismatch was not found } } } // LinkedList3 class for Question 8

/** * The HashTable class has been modified to use a type parameter * and a separate String variable to serve as the key. */ public class HashTable<T> { // Uses the generic LinkedList3 class from Display 15.8 private LinkedList3[] hashArray; private static final int SIZE = 10; public HashTable() { hashArray = new LinkedList3[SIZE]; for (int i=0; i < SIZE; i++) hashArray[i] = new LinkedList3<T>(); } private int computeHash(String s) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

int hash = 0; for (int i = 0; i < s.length(); i++) { hash += s.charAt(i); } return hash % SIZE; } /** * get * Retrieves the object in the hash table that matches * the input query object. * @param key String used as the hash code for the query object * @param queryObject : An object with minimal data so that * it can be compared to objects in the hash table using the * equals method. For example, the Employee class uses * name and date in the equals method. So a query object for * the Employee class should have the name and date filled in * and the get method will return the actual object in the * hash table that matches the name and date in queryObject. * @return T null if no match or the object that matches the queryObject. */ public T get(String key, T queryObject) { int hash = computeHash(key); LinkedList3 list = hashArray[hash]; return ((T) list.findData(queryObject)); } /** * put * Stores target newItem into the hash table * Requires that T correctly implements the toString method. * @param key String that is used as the hashcode for the item * @param newItem The item to add to the hash table */ public void put(String key, T newItem) { int hash = computeHash(key); // Get hash value LinkedList3 list = hashArray[hash]; if (!list.contains(newItem)) { // Only add the target if it's not already // on the list. hashArray[hash].addToStart(newItem); } } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

} // HashTable class for Question 8

9. /** * Question9.java * * This program creates a hash table of Strings that forms the * basis for a dictionary. It uses the hash table class from * chapter 15. It uses the hash table to spell check a text file. * * This program requires the HashTable and LinkedList2 * classes defined in chapter 15. They are not reproduced here. * * Created: Fri Mar 22 2007 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; import java.util.StringTokenizer; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class Question9 { public static void main(String[] args) { HashTable dictionary = new HashTable(); // First load in the dictionary System.out.println("Wait, loading dictionary..."); try { Scanner inputStream = new Scanner(new FileInputStream("words.txt")); // CHANGE // Read in each line, which is a single word while (inputStream.hasNextLine()) { String dictWord = inputStream.nextLine( ); dictWord = dictWord.toLowerCase(); dictWord = removePunct(dictWord); dictionary.put(dictWord); // Add a single word Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

} inputStream.close(); } catch(FileNotFoundException e) { System.out.println("File was not found"); System.out.println("or could not be opened."); } catch(IOException e) { System.out.println("Error reading from file."); }

// Load in the file to spell check, and then check it System.out.println("Checking file"); try { Scanner inputStream = new Scanner(new FileInputStream("checkme.txt")); // CHANGE // Read in each line int lineNum = 1; while (inputStream.hasNextLine()) { String line = inputStream.nextLine( ); // Tokenize the string, removing punctuation StringTokenizer wordFactory = new StringTokenizer(line); while (wordFactory.hasMoreTokens()) { String word = wordFactory.nextToken(); word = word.toLowerCase(); word = removePunct(word); checkWord(word, lineNum, dictionary); } lineNum++; } inputStream.close( ); } catch(FileNotFoundException e) { System.out.println("File was not found"); System.out.println("or could not be opened."); } catch(IOException e) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

System.out.println("Error reading from file."); } } // Returns the input string with any punctuation // removed. public static String removePunct(String s) { String noPunct = ""; //initialized to empty string int sLength = s.length( ); for (int i = 0; i < sLength; i++) { char c = s.charAt(i); if (((c>='a') && (c<='z')) || ((c>='A') && (c<='Z')) || ((c>='0') && (c<='9'))) { noPunct = noPunct + c; } } return noPunct; } // Checks the spelling of word and outputs it // if the word is not found in the dictionary. public static void checkWord (String word, int lineNum, HashTable dictionary) { String tempWord; tempWord = word.toLowerCase(); tempWord = removePunct(tempWord); if ((tempWord.length() > 0) && (!dictionary.containsString(tempWord))) { System.out.println("'" + tempWord + "'" + " may be misspelled on line " + lineNum); } return; } } // Question 9 Sample File for checkme.txt: The quick brown fox jumpz over the lazy dogs. Were there some typoos in there somewhere? Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

There should be one pur line. 10. /** * Question10.java * * This is the same code as SetDemo.java from Chapter 15. * The Set class has been modified to use a hash table internally rather * than a linked list. * * Created: Fri Mar 22 2007 * * @author Kenrick Mock * @version 1 */ public class Question10 { public static void main(String[] args) { // Round things Set round = new Set<String>(); // Green things Set green = new Set<String>(); // Add some data to both sets round.add("peas"); round.add("ball"); round.add("pie"); round.add("grapes"); green.add("peas"); green.add("grapes"); green.add("garden hose"); green.add("grass"); System.out.println("Contents of set 'round': "); round.output(); System.out.println("Contents of set 'green': "); green.output(); System.out.println(); System.out.println("ball in set 'round'? " + round.contains("ball")); System.out.println("ball in set 'green'? " + green.contains("ball")); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

System.out.println("ball and peas in same set? " + ((round.contains("ball") && (round.contains("peas"))) || (green.contains("ball") && (green.contains("peas"))))); System.out.println("pie and grass in same set? " + ((round.contains("pie") && (round.contains("grass"))) || (green.contains("pie") && (green.contains("grass"))))); System.out.print("Union of 'green' and 'round': "); round.union(green).output(); System.out.print("Intersection of 'green' and 'round': "); round.intersection(green).output(); } } // Question 10

/** * LinkedList3 * This is almost the same LinkedList3 class from the text. * I made the internal Node<T> class public so it could be * iterated upon in the Set class. * */ public class LinkedList3<T> { public class Node<T> { private T data; private Node<T> link; public Node( ) { data = null; link = null; } public Node(T newData, Node<T> linkValue) { data = newData; link = linkValue; } public T getData() { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

return data; } public Node<T> getLink() { return link; } }//End of Node<T> inner class private Node<T> head; public LinkedList3( ) { head = null; } /** * Returns the head node which allows * the beginnings of an iterator */ public Node<T> getHead() { return head; } /** Adds a node at the start of the list with the specified data. The added node will be the first node in the list. */ public void addToStart(T itemData) { head = new Node<T>(itemData, head); } /** Removes the head node and returns true if the list contains at least one node. Returns false if the list is empty. */ public boolean deleteHeadNode( ) { if (head != null) { head = head.link; return true; } else Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

return false; } /** Returns the number of nodes in the list. */ public int size( ) { int count = 0; Node<T> position = head; while (position != null) { count++; position = position.link; } return count; } public boolean contains(T item) { return (find(item) != null); } /** Finds the first node containing the target item, and returns a reference to that node. If target is not in the list, null is returned. */ private Node<T> find(T target) { Node<T> position = head; T itemAtPosition; while (position != null) { itemAtPosition = position.data; if (itemAtPosition.equals(target)) { return position; } position = position.link; } return null; //target was not found } /** Finds the first node containing the target and returns a reference to the data in that node. If target is not in the list, null is returned. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

*/ public T findData(T target) { Node<T> result = find(target); if (result == null) return null; else return result.data; } public void outputList( ) { Node<T> position = head; while (position != null) { System.out.println(position.data); position = position.link; } } public boolean isEmpty( ) { return (head == null); } public void clear( ) { head = null; } /* For two lists to be equal they must contain the same data items in the same order. The equals method of T is used to compare data items. */ public boolean equals(Object otherObject) { if (otherObject == null) return false; else if (getClass( ) != otherObject.getClass( )) return false; else { LinkedList3<T> otherList = (LinkedList3<T>)otherObject; if (size( ) != otherList.size( )) return false; Node<T> position = head; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

Node<T> otherPosition = otherList.head; while (position != null) { if (!(position.data.equals(otherPosition.data))) return false; position = position.link; otherPosition = otherPosition.link; } return true; //no mismatch was not found } } } // LinkedList3 for Question 10

// The set class uses a hash table as the internal data structure. public class Set<T> { // Uses the generic LinkedList3 class from Display 15.8 private LinkedList3[] hashArray; private int size = 10; // This is now a settable parameter

public Set() { hashArray = new LinkedList3[size]; for (int i=0; i < size; i++) hashArray[i] = new LinkedList3<T>(); } public Set(int initialSize) { size = initialSize; hashArray = new LinkedList3[size]; for (int i=0; i < size; i++) hashArray[i] = new LinkedList3<T>(); } /** Add a new item to the set. If the item is already in the set, false is returned, otherwise true is returned. Requires that T implement toString() correctly. */ public boolean add(T newItem) { int hash = computeHash(newItem.toString()); Copyright © 2016 Pearson Education Ltd. All rights reserved.

// Get hash value


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

LinkedList3 list = hashArray[hash]; if (!list.contains(newItem)) { // Only add the target if it's not already // on the list. hashArray[hash].addToStart(newItem); return true; } return false; } /** Returns true if item is in the set, false otherwise. Requires that toString be defined. */ public boolean contains(T item) { int hash = computeHash(item.toString()); LinkedList3 list = hashArray[hash]; if (list.findData(item) == null) return false; return true; } /** * Outputs the entire contents of the hash table. */ public void output( ) { for (int i=0; i < size; i++) { LinkedList3 list = hashArray[i]; if (list != null) { list.outputList(); } } } /** Returns a new set that is the union of this set and the input set. */ public Set<T> union(Set<T> otherSet) { Set<T> unionSet = new Set<T>(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

// Copy this set to unionSet for (int i=0; i< size; i++) { LinkedList3 list = hashArray[i]; LinkedList3<T>.Node<T> iter = list.getHead( ); while (iter != null) { unionSet.add(iter.getData()); iter = iter.getLink(); } } // Copy otherSet items to unionSet. // The add method eliminates any duplicates. for (int i=0; i< size; i++) { LinkedList3 list = otherSet.hashArray[i]; LinkedList3<T>.Node<T> iter = list.getHead(); while (iter != null) { unionSet.add(iter.getData()); iter = iter.getLink(); } } return unionSet; } /** Returns a new that is the intersection of this set and the input set. */ public Set<T> intersection(Set<T> otherSet) { Set<T> interSet = new Set<T>(); // Copy only items in both sets for (int i=0; i< size; i++) { LinkedList3 list = hashArray[i]; LinkedList3<T>.Node<T> iter = list.getHead( ); while (iter != null) { if (otherSet.contains(iter.getData())) { interSet.add(iter.getData()); } iter = iter.getLink(); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

} return interSet; } /** * Compute a simple hash function */ private int computeHash(String s) { int hash = 0; for (int i = 0; i < s.length(); i++) { hash += s.charAt(i); } return hash % size; } } // Set for Question 10

11. /** * Question 11 * * Maze game implemented with references to * Node classes. * * Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; class Node { char ID; Node north, south, east, west; public Node() { } public Node(char newID) { ID = newID; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

public char getID() { return ID; } public Node getNorth() { return north; } public Node getSouth() { return south; } public Node getEast() { return east; } public Node getWest() { return west; } public void setConnections(Node north, Node south, Node east, Node west) { this.north = north; this.south = south; this.east = east; this.west = west; } } public class Question11 { public static void main(String[] args) { Node A = new Node('A'); Node B = new Node('B'); Node C = new Node('C'); Node D = new Node('D'); Node E = new Node('E'); Node F = new Node('F'); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

Node G = new Node('G'); Node H = new Node('H'); Node I = new Node('I'); Node J = new Node('J'); Node K = new Node('K'); Node L = new Node('L'); A.setConnections(null, E, B, null); B.setConnections(null, F, null, A); C.setConnections(null, G, D, null); D.setConnections(null, null, null, C); E.setConnections(A, I, null, null); F.setConnections(B, null, G, null); G.setConnections(C, K, H, F); H.setConnections(null, L, null, G); I.setConnections(E, null, J, null); J.setConnections(null, null, null, I); K.setConnections(G, null, null, null); L.setConnections(H, null, null, null); Node current = A; while (current != L) { System.out.println("You are in room " + current.getID() + " of a maze of twisty " + "passages, all alike."); System.out.println("You can go: "); if (current.getNorth() != null) System.out.println(" North"); if (current.getSouth() != null) System.out.println(" South"); if (current.getEast() != null) System.out.println(" East"); if (current.getWest() != null) System.out.println(" West"); Scanner kbd = new Scanner(System.in); String s; s = kbd.next(); if ((s.charAt(0) == 'N') && (current.getNorth() != null)) current = current.getNorth(); else if ((s.charAt(0) == 'S') && (current.getSouth() != null)) current = current.getSouth(); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 15, Instructor’s Manual

else if ((s.charAt(0) == 'E') && (current.getEast() != null)) current = current.getEast(); else if ((s.charAt(0) == 'W') && (current.getWest() != null)) current = current.getWest(); } System.out.println("You reached the exit of the maze!"); } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

Chapter 16

Collections, Maps and Iterators Key Terms collection iterator wildcard <?> extends super Set<T> interface List<T> interface AbstractSet<T> AbstractList<T> AbstractCollection<T> HashSet<T> Vector<T> AbstractSequentialList<T> LinkedList<T> SortedSet<T> TreeSet<T> map AbstractMap<K,V> interface HashMap<K,V>interface Map<K,V> interface initial capacity load factor rehashing Iterator Iterator<T> interface ListIterator<T> cursor Brief Outline 16.1 Collections Wildcards The Collection Framework Concrete Collection Classes HashSet<T> Class Differences between ArrayList<T> and Vector<T> Nonparameterized Version of the Collection Framework 16.2 Maps The Map Framework Concrete Map Classes

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

HashMap<K,V> Class 16.3 Iterators The Iterator Concept The Iterator<T> Interface List Iterators

List of Displays Teaching Suggestions This chapter discusses the Java Collections Framework and the use of iterators. The structure of the Collections Framework and important classes and interfaces are discussed. This is followed in the third section by a discussion of iterators and the Iterator interface built into Java. With the changes for Java 5, all of the Collections classes use Generics and therefore the new for-each loop will work on each of them. There is an optional section in this chapter about using the nonparameterized version of the collection framework, which is still available in Java 5 for backwards compatibility reasons. These chapters are good for students who are learning Java as a second language as they are key features built into Java to make using and managing collections easier. They also provide a way for students who have not yet had formal training in data structures become exposed to the different types that are available. The students can use these structures without needing to understand the underlying issues with the structures. In the reverse direction, students that have studied Chapter 15 are shown list-based implementations of many data structures presented in Chapter 16. By covering Chapter 15 first, students may gain a greater appreciation for abstraction and a better understanding of the impact of implementation on efficiency.

Key Points Collection Interfaces. The main interfaces of Set<T> and List<T> help differentiate collections that do not allow duplicates and impose no order on their elements (sets) from those that do allow duplicates and can impose order on their elements (lists). The HashSet<T> class is a common implementation of the Set<T> interface. For-each loops. The new Java 5 feature of the for-each loop can be used with any of the collections in the Java Collections framework. Map Interfaces. The main interface of Map<K,V> associates a key K with a value V. A comparison can be made to the hash table implemented in Chapter 15. Maps are common when an in-memory ‘database’ is required. The HashMap<K,V> class is a common implementation of the Map<K,V> interface.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

Iterators. Allow us to go through an entire collection looking at one element at a time. The Iterator<T> and ListIterator<T> interface are already defined inside Java to help us write our own iterators. The ListIterator<T> Interface. This interface allows you to mutate the collection you are iterating over as well as moving both forwards and backwards through the collection.

Tips Dealing with All Those Exceptions. If you are deriving a collection from one of the previously defined collection or simply using them, there are many exceptions to deal with. You can simply not catch the exceptions and allow them to propagate up to be run-time exceptions. If you are creating your own collections and wish to use some of the same exceptions they are available for use, many are defined in the java.lang package. For-Each Loops as Iterators. In most cases, you can use the for-each loop in place of an iterator on a collection. A for-each loop mimics an iterator in its capability to cycle through all elements of a collection. However, it is not an iterator in the purest sense because the for-each loop is not an object. Defining Your Own Iterator Classes. If you need to define your own iterator for a collection that does not inherit from one of the other already defined collection classes, you should create the iterator as an inner class of your collection.

Pitfalls Optional Operations. There are methods in the interfaces for the Collection classes that are optional, but still must have some sort of implementation because you are implementing an interface. These types of methods can throw the UnsupportedOperationException if they do not wish to implement that functionality. Omitting the <T>. If you do not use the generics properly when working with the collections framework, you may or may not get compiler errors or run-time errors with your code. This is due to the fact that when generics were implemented, Java maintained backwards compatibility with Java release 1.4. Collections without the generic type simply have the type Object substituted in. This may or may not cause problems in the code you have written. It is important to be extremely careful about inserting the appropriate generic types when needed. next Can Return a Reference. In fact the method next from an Iterator does return a reference to an element, which allows us to modify the elements in a collection while iterating over it if we so choose.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

Programming Projects Answers 1. /** * BubbleSort.java */ import java.util.Vector; public class BubbleSort { /**Based on SelectionSort given in Chapter 6 **/ /** Action: Sorts Vector a so that its strings are lexiographically sorted. */ public static void sort(Vector a) { int index; for ( int i = 0; i < a.size(); i++ ) { for ( index = 0; index < a.size() - 1; index++ ) { String s = (String) a.get(index); String t = (String) a.get(index + 1); if ( s.compareTo(t) > 0) { a.set(index+1, s); a.set(index, t); } // end of if () } // end of for () } // end of for () } } /** * Question1.java * * * Created: Fri Jan 09 20:06:28 2004 * * @author Adrienne Decker * @version */ import java.util.Vector; public class Question1 Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

{ public static void main(String[] args) { Vector v1 = new Vector(); v1.add("Aaa"); v1.add("Ccc"); v1.add("Bbb"); BubbleSort.sort(v1); System.out.println(v1); Vector v2 = new Vector(); v2.add("Arrays"); v2.add("Hashsets"); v2.add("Vectors"); v2.add("Maps"); v2.add("Collections"); v2.add("Hashmaps"); v2.add("Oranges"); BubbleSort.sort(v2); System.out.println(v2); } } // Question1

2. /** * Question2Sieve.java * * This program implements the sieve of eratosthenes to generate * prime numbers from 2 to 100. * * Created: Sat Apr 16 2005 * * @author Kenrick Mock * @version 1 */ import java.util.ArrayList; import java.util.Iterator; class Question2Sieve { /* * Main method Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

*/ public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<Integer>(); // Generate numbers from 2 to 100 for (int i=2; i<=100; i++) { numbers.add(i); } // Start the sieve for (int i=0; i < numbers.size()-1; i++) { // Get the number at position i int currentVal = numbers.get(i); // Get an iterator for the next number Iterator<Integer> scanIterator = numbers.listIterator(i+1); // Scan through remainder of list for multiples, removing // the element if it is a multiple if currentVal while (scanIterator.hasNext()) { int candidateVal = scanIterator.next(); // Remove if a multiple of the currentVal if ((candidateVal % currentVal) == 0) { scanIterator.remove(); } } } // Output all values remaining in the ArrayList System.out.println("Prime numbers from 2 to 100:"); for (Integer n : numbers) { System.out.print(n + " "); } System.out.println(); } } // Question2Sieve

3. /** * Question3Birthday.java Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

* * This program computes the probability that two people have the * same birthday, out of N people in a room. It uses a HashSet * to keep track of birthdays and whether or not someone has the * same birthday. * * Created: Sat Apr 16 2005 * * @author Kenrick Mock * @version 1 */ import java.util.HashSet; class Question3Birthday { // Number of random trials to run per room size public static final int NUMTRIALS = 5000; // Max number of people in a room public static final int MAXROOMSIZE = 50; /* * Main method */ public static void main(String[] args) { // Birthdays of people in the room, from 1-365 HashSet<Integer> birthdays; int trial; int people; int numMatches; for (people=2; people <= MAXROOMSIZE; people++) { // Run trials to see if people have the same birthday // Reset number of matches numMatches = 0; for (trial =0; trial < NUMTRIALS; trial++) { // Create new HashSet to store birthday birthdays = new HashSet<Integer>(); boolean foundMatch = false; // Randomly generate up to "people" birthdays for (int i=0; (i<people && !foundMatch); i++) { // Get random birthday int birthday = (int) (Math.random() * 365) + 1; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

// Check if someone has this birthday if (birthdays.contains(birthday)) { numMatches++; foundMatch = true; } else { // Add this birthday to the set birthdays.add(birthday); } } } System.out.println("For " + people + " people, the probability of two " + "birthdays is about " + (double) numMatches / NUMTRIALS); } } } // Question3Birthday

4. /** * Question4Names.java * * This program reads through a list of names and finds * the names that are common to both boys and girls. * * Created: Sat Apr 16 2005 * * @author Kenrick Mock * @version 1 */ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.ArrayList; class Question4Names { // Number of names in the file Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

public static final int NUMNAMES = 1000; /* * Main method */ public static void main(String[] args) { // Names read in so far HashSet<String> names = new HashSet<String>(); // Names in common between boys and girls ArrayList<String> commonNames = new ArrayList<String>(); BufferedReader inputStream = null; int i; // First process the girlnames.txt file // by reading each name into the HashSet try { inputStream = new BufferedReader( new FileReader("girlnames.txt")); for (i=0; i< NUMNAMES; i++) { String line = inputStream.readLine(); // Parse out first name and number int space = line.indexOf(" ",0); String first = line.substring(0,space); String number = line.substring(space+1); // Store value in HashSet. No need to check for duplicates // since each name is unique in the girlnames.txt file. // Convert name to lowercase to avoid case sensitivity first = first.toLowerCase(); // Add this name to the HashSet names.add(first); } inputStream.close(); } catch (FileNotFoundException e) { System.out.println ("File not found!"); System.exit (0); } catch (IOException e) { System.out.println("Error reading from file."); System.exit(0); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

}

// Next read in the boyNames.txt file and // if it already exists in the // HashSet, add it to a vector so they can be output later try { inputStream = new BufferedReader( new FileReader("boynames.txt")); for (i=0; i< NUMNAMES; i++) { String line = inputStream.readLine(); // Parse out first name and number int space = line.indexOf(" ",0); String first = line.substring(0,space); String number = line.substring(space+1); // Store value in HashSet. No need to check for duplicates // since each name is unique in the girlnames.txt file. // Convert name to lowercase to avoid case sensitivity first = first.toLowerCase(); // See if name exists already if (names.contains(first)) { commonNames.add(first); // Found name on both lists } } inputStream.close(); } catch (FileNotFoundException e) { System.out.println ("File not found!"); System.exit (0); } catch (IOException e) { System.out.println("Error reading from file."); System.exit(0); } // Output all of the common names System.out.println("Here are the " + commonNames.size() + " names on both the boys and girls list."); for (i=0; i<commonNames.size(); i++) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

System.out.println(commonNames.get(i)); } } } // Question4Names 5. /** * Question5Names.java * * This program reads through a list of names and finds * the names that are common to both boys and girls. It uses * a HashMap to store the names. * * Created: Sat Apr 16 2005 * * @author Kenrick Mock * @version 1 */ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.ArrayList; /** * The Name class stores a name and the number * of namings for boys and girls. */ class Name { private String name; private int boyNamings; private int girlNamings; /** * Constructors */ Name() { this.name = ""; boyNamings = 0; girlNamings = 0; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

Name(String name, int boyNamings, int girlNamings) { this.name = name; this.boyNamings = boyNamings; this.girlNamings = girlNamings; } /** * Accessor/Mutator methods */ public int getBoyNamings() { return boyNamings; } public void setBoyNamings(int n) { boyNamings = n; } public int getGirlNamings() { return girlNamings; } public void setGirlNamings(int n) { girlNamings = n; } public void setName(String s) { name = s; } public String getName(String s) { return name; } /** * The equals method is invoked by the Collection * functions for determing equality * of two Name objects. Here we compare the name and * ignore the number of namings. */ public boolean equals(Object other) { Name otherName = (Name) other; return this.name.equals(otherName.name); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

} /** * Returns the name and number of namings as a string. */ public String toString() { return name + " boy namings: " + boyNamings + " girl namings: " + girlNamings; } } // Name

class Question5Names { // Number of names in the file public static final int NUMNAMES = 1000; /* * Main method */ public static void main(String[] args) { // Names read in so far. Map a string to the name object HashMap<String,Name> names = new HashMap<String,Name>(); // Names in common between boys and girls ArrayList<Name> commonNames = new ArrayList<Name>(); BufferedReader inputStream = null; int i; // First process the girlnames.txt file by reading // each name into the HashSet try { inputStream = new BufferedReader(new FileReader("girlnames.txt")); for (i=0; i< NUMNAMES; i++) { String line = inputStream.readLine(); // Parse out first name and number int space = line.indexOf(" ",0); String first = line.substring(0,space); String number = line.substring(space+1); // Store value in HashSet. No need to check for duplicates // since each name is unique in the girlnames.txt file. // Convert name to lowercase to avoid case sensitivity Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

first = first.toLowerCase(); // Add this name to the HashMap. Don't // know boy namings yet, so set to zero names.put(first, new Name(first,0,Integer.parseInt(number))); } inputStream.close(); } catch (FileNotFoundException e) { System.out.println ("File not found!"); System.exit (0); } catch (IOException e) { System.out.println("Error reading from file."); System.exit(0); }

// Next read in the boyNames.txt file and if it already exists in the // HashSet, add it to a vector so they can be output later try { inputStream = new BufferedReader(new FileReader("boynames.txt")); for (i=0; i< NUMNAMES; i++) { String line = inputStream.readLine(); // Parse out first name and number int space = line.indexOf(" ",0); String first = line.substring(0,space); String number = line.substring(space+1); // Convert name to lowercase to avoid case sensitivity first = first.toLowerCase(); // See if name exists already if (names.containsKey(first)) { // Retrieve object from the HashMap. // Pass in a Name object with // the same name to retrieve the matching name. // The name counts are not needed. Name commonName = names.get(first); // Set the number of boy namings commonName.setBoyNamings(Integer.parseInt(number)); // Add to the vector of common names // Found name on both lists Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

commonNames.add(commonName); } } inputStream.close(); } catch (FileNotFoundException e) { System.out.println ("File not found!"); System.exit (0); } catch (IOException e) { System.out.println("Error reading from file."); System.exit(0); } // Output all of the common names with number of namings System.out.println("Here are the " + commonNames.size() + " names on both the boys and girls list."); for (i=0; i<commonNames.size(); i++) { System.out.println((commonNames.get(i)).toString()); } } } // Question5Names 6. /** * Fairyland.java * * Fairyland is a math game in which one winner element is picked from * an n-elements list by repeatedly removing every 5th element until * only one element is left in the list. * * Created: Feb 7, 2016 * * @author * @version 1 */ import java.util.ArrayList; public class Fairyland { public static void main(String args[]) { ArrayList<Integer> admirers = new ArrayList<Integer>(9); System.out.println("All admirers have been given " Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

+ "their designated places"); for (int index = 0; index < 9; index++) admirers.add(index + 1); System.out.println("Lets Play the game" + admirers.size()); int index = 0, count = 1; do { System.out.println(index + "," + count + "," + admirers.size()); if (count == 5) { int ad = admirers.remove(index); index--; System.out.println("Admirers " + ad + " has been eliminated " + admirers.size()); count = 1; } else count++; if (index == admirers.size() - 1) index = 0; else index++; } while (admirers.size() > 1); System.out.println("The Winner is :" + admirers.get(0)); } } 7. /** * Question7.java * * This program creates a hash map from a username to a User object. * The User object contains a HashSet of friends (other users) for * that user. We can use this list to compute a "neighborhood" of friends * in this case, everyone within two links from a target user. * * Created: Fri Mar 22 2007 * * @author Kenrick Mock * @version 1 */ import java.util.HashMap; import java.util.Scanner; import java.util.StringTokenizer; import java.io.FileInputStream; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

import java.io.FileNotFoundException; import java.io.IOException; public class Question7 { public static void main(String[] args) { // The users HashMap maps from a username to a User object HashMap<String,User> users = new HashMap<String,User>(); // First load the social network from the file to the map try { Scanner inputStream = new Scanner(new FileInputStream("network.txt")); // CHANGE // Read in each line, which is a source user and friend user while (inputStream.hasNextLine()) { String line = inputStream.nextLine( ); StringTokenizer wordFactory = new StringTokenizer(line); // Read in two tokens from line String srcUserName = wordFactory.nextToken(); String friendUserName = wordFactory.nextToken(); // Add users to the map if not already there if (!users.containsKey(srcUserName)) { users.put(srcUserName, new User(srcUserName)); } if (!users.containsKey(friendUserName)) { users.put(friendUserName, new User(friendUserName)); } // Retrieve user object and add friend User srcUser = users.get(srcUserName); User friendUser = users.get(friendUserName); srcUser.addFriend(friendUser); } inputStream.close(); } catch(FileNotFoundException e) { System.out.println("File was not found"); System.out.println("or could not be opened."); } catch(IOException e) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

{ System.out.println("Error reading from file."); } // Output what we loaded System.out.print("Users loaded: "); for (User u : users.values()) { System.out.print(u.getName() + " "); // Uncomment this section to show all friends // for each user /* for (Object f : u.getFriendsArray()) { User friendObj = (User) f; System.out.print(friendObj.getName() + " "); } System.out.println(); */ } System.out.println(); // Allow the user to input a name and then output the // friends that are up to 2 links away String name = ""; Scanner keyboard = new Scanner(System.in); do { System.out.println("Enter a username and all friends"); System.out.println("two links or less will be displayed."); System.out.println("Press enter to exit."); name = keyboard.nextLine(); if (users.containsKey(name)) { System.out.println("Friends for " + name); User u = users.get(name); u.showFriends(2); // Prints everyone up to 2 links away } else if (!name.equals("")) { System.out.println("Name not found."); } } while (!name.equals("")); } } // Question 7 Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

/** * User.java * * This class encapsulates user information. * It holds a username and a set of User objects * that this person links to as friends. * * Created: Fri Mar 22 2007 * * @author Kenrick Mock * @version 1 */ import java.util.HashSet; public class User { private String username; private HashSet<User> friends;

// User name // Set of friends

/* Constructors */ public User() { friends = new HashSet<User>(); } public User(String newName) { username = newName; friends = new HashSet<User>(); } /* Accessors and Mutators */ public void setName(String newName) { username = newName; } public String getName() { return username; } public HashSet<User> getFriends() { return friends; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

} public Object[] getFriendsArray() { return friends.toArray(); } /** * addFriend adds a new friend object to the set of friends. * @param newFriend User object to add to the set of friends * as a direct friend. */ public void addFriend(User newFriend) { friends.add(newFriend); } /** * removeFriend removes a friend object to the set of friends. * @param oldFriend User object to remove from the set of direct friends */ public void removeFriend(Object oldFriend) { friends.remove((User) oldFriend); } /** * showFriends is a wrapper method around the recursive routine * that shows all friends up to maxNumLinks away. * It adds a new variable to indicate the current number of links * away from the source, and it initialized to 1. * * @param maxNumLinks Max number of links to show friends */ public void showFriends(int maxNumLinks) { showFriendsRecursive(1,maxNumLinks); } /** * showFriendsRecursive does all the work in * recursively showing all friends up to maxNumLinks away. * It increments curNumLinks for each link traversed * away from the source. * * @param curNumLinks Current number of links from source user Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

* @param maxNumLinks Max number of links to show friends */ private void showFriendsRecursive(int curNumLinks, int maxNumLinks) { // Show all direct friends to this user for (User friend : friends) { System.out.println(username + " is friends with " + friend.getName() + " (" + curNumLinks + " links)"); // Recurse on each friend if we haven't reached the // maximum number of links if (curNumLinks < maxNumLinks) { friend.showFriendsRecursive(curNumLinks + 1, maxNumLinks); } } System.out.println(); } }

Sample network file with nonsensical usernames. The notation of the username indicates how many links away from user A or B. The last digit indicates the number of links away from user A or B. This can be used to test outputting friends to different distances. network.txt A A1_1 A A2_1 A A3_1 A1_1 A11_2 A1_1 A12_2 A2_1 A21_2 A11_2 A111_3 B B1_1 B B2_1 B B3_1 B1_1 B11_2 B1_1 B12_2 B2_1 B21_2 B11_2 B111_3 8. /** * FacultyRating.java Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

* * This program reads a file in which an university’s faculty ratings * are stored. There can be multiple ratings for a faculty with * unique ID. The program reads all the rating points of each faculty * and computes average rating for each faculty and prints the same on * the output console * * Created: Feb 8, 2016 * * @author * @version 1 */ import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class FacultyRating { public static void main(String[] args) { HashMap<String, Integer> activity = new HashMap<String, Integer>(15); ArrayList<String> key = new ArrayList<String>(5); ArrayList<Integer> count = new ArrayList<Integer>(5); ArrayList<Integer> sum = new ArrayList<Integer>(5); try { Scanner keyboard = new Scanner(new FileReader(new File("data.txt"))); String facultyID, key1; int facultyRating; int c, s = 0; double averageRating; int totalEntries = keyboard.nextInt(); for (int i = 0; i < totalEntries; i++) { facultyID = keyboard.next(); facultyRating = keyboard.nextInt(); if (i == 0) { key.add(facultyID); count.add(1); sum.add(facultyRating); } else { if (key.contains(facultyID)) { int index = key.indexOf(facultyID); count.add(index, count.get(index).intValue() + 1); sum.add(index, sum.get(index).intValue() + facultyRating);

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

} else { key.add(facultyID); count.add(1); sum.add(facultyRating); } } } } catch (IOException e) { System.out.println(e); } for (int index = 0; index < key.size(); index++) { System.out.println(key.get(index) + " : " + count.get(index) + " Criterias, average of " + (sum.get(index) / count.get(index) / 5.0)); } } } 9. /** * Question9.java * * Simple spell checker * * Created: Fri Apr 27 2012 * * @author Kenrick Mock * @version 1 */ import java.util.Scanner; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.HashSet; public class Question9 { public static void main(String[] args) { HashSet<String> wordHash = new HashSet<String>(); Scanner fileIn = null; // Initializes fileIn to an empty object try { // Attempt to open the file Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

fileIn = new Scanner( new FileInputStream("words.txt")); } catch (FileNotFoundException e) { // If the file could not be found, this code is executed // and then the program exits System.out.println("File not found."); System.exit(0); } // Add each word to the hash set while (fileIn.hasNext()) { String word = fileIn.next().toLowerCase(); wordHash.add(word); } fileIn.close(); // Open the file we would like to spell check try { // Attempt to open the file fileIn = new Scanner( new FileInputStream("ratings.txt")); } catch (FileNotFoundException e) { // If the file could not be found, this code is executed // and then the program exits System.out.println("File not found."); System.exit(0); } // Check each word System.out.println("The following words may be misspelled:"); while (fileIn.hasNext()) { String word = fileIn.next().toLowerCase(); // A more robust version would strip punctuation // or consider stemming the words if (!wordHash.contains(word)) System.out.println(word); } fileIn.close(); } } // Question 9

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

10. /** * Question 10 * * You have a list of student ID’s followed by the course number * (separated by a space) that the student is enrolled in. The listing is * in no particular order. For example, if student 1 is in CS100 and CS200 * while student 2 is in CS105 and MATH210 then the list might look like this: * * 1 CS100 * 2 MATH210 * 2 CS105 * 1 CS200 * * Write a program that reads data in this format from the console. If * the ID is -1 then stop inputting data. Use the HashMap class to map from * an Integer (the student ID) to an ArrayList of type String that holds each * class that the student is enrolled in. The declaration should look like this: * * HashMap<Integer, ArrayList<String>> * students = new HashMap<Integer, ArrayList<String>>(); * * After all data is input, iterate through the map and output the student ID * and all courses stored in the ArrayList for that student. The result * should be a list of courses organized by student ID. * * Created: Thu May 21 2015 * * @author Kenrick Mock * @version 1 */ import java.util.HashMap; import java.util.ArrayList; import java.util.Scanner; public class Question10 { public static void main(String[] args) { HashMap<Integer, ArrayList<String>> students = new HashMap<Integer, ArrayList<String>>(); String line; int studentID; String course; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 16, Instructor’s Manual

Scanner keyboard = new Scanner(System.in); System.out.println("Enter student ID followed by course number, -1 to exit."); do { line = keyboard.nextLine(); line = line.trim(); // remove any leading or trailing whitespace if (!line.equals("-1")) { // Extract the ID and the Class, separated by a space, // by using the split method, which creates an array of strings // delimited by the delimiter (specified as a space in this case) String[] parsedString = line.split(" "); studentID = Integer.parseInt(parsedString[0]); // the ID course = parsedString[1]; // Add to arraylist if student ID has been seen already if (students.containsKey(studentID)) { students.get(studentID).add(course); } else { // Add arraylist for the first time to the map ArrayList<String> courses = new ArrayList<String>(); courses.add(course); students.put(studentID, courses); } } } while (!line.equals("-1")); // Now iterate through the map and output the student ID and all courses // associated with the student System.out.println(); for (Integer key : students.keySet()) { System.out.println("For student: " + key); for (String cls : students.get(key)) { System.out.print(cls + " "); } System.out.println(); System.out.println(); } } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

Chapter 17

Swing I Key Terms Swing GUI AWT event-driven programming event listener firing an event event handler pixel JButton adding a button registering a listener addActionListener action event action listener ActionListener actionPerformed System.exit label JLabel getContentPane setBackground Color.BLUE content pane getContentPane color Color layout manager container class setLayout BorderLayout GridLayout panel Container container class component stub Model-View-Controller menu menu item listeners Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

menu bar action command setActionCommand text field JTextField text area JTextArea setLineWrap output-only setEditable

Brief Outline 17.1 Event-Driven Programming Events and Listeners 17.2 Buttons, Events, and Other Swing Basics Buttons Action Listeners and Action Events Labels Color 17.3 Containers and Layout Managers Border Layout Manager Flow Layout Manager Grid Layout Manager Panels The Container Class The Model-View-Controller Pattern 17.4 Menus and Buttons Menu Bars, Menus, and Menu Items Nested Menus The AbstractButton Class The setActionCommand Method Listeners as Inner Classes 17.5 Text Fields and Text Areas Text Areas and Text Fields A Swing Calculator

Teaching Suggestions This chapter discusses the creation of graphic user interfaces using the built in graphical components available inside the javax.swing package. In this chapter we begin by looking at graphical programming and the notion of events (user actions) and how they are handled by a graphical program.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

The basics components in swing are introduced such as buttons, menus, and text fields. With each of these components, events are reacted to through the use of action listeners. Putting menus on a GUI using menu bars are introduced later in the chapter. Text fields and text areas are also discussed. The JLabel class is also introduced for use in placing text directly on the GUI. Layout of graphical programs is discussed in the third section and the basic layout managers are introduced including FlowLayout, GridLayout, and BorderLayout. Instructors should note that there are other layouts available inside the java.awt package. These can also be introduced at this time.

Key Points GUI. Graphical User Interface. A program whose method of interaction is graphical. JFrame. This class represents a basic window. It has a title bar and buttons for minimizing/maximizing a window and a close button, which does not have the functionality to end the program by default. Pixel. Smallest unit of space on the screen. Pixels are used both for sizing and positioning items graphically. Resolution’s Relationship to Object Size. When a screen has higher resolution, an object will look smaller than on a screen with lower resolution. The reason is that on a higher resolution screen, the pixels are packed closer together. The setVisible Method. For the JFrame, the default visibility is hidden. The JFrame will not by default be shown to the screen. This is fixed by calling setVisible with the value true. Calling it again with the value false will hide the window again. The JButton Class. This is a class that creates a button on the screen that the user can click on. Buttons have text on them to describe what they do. Adding an action listener will allow the button to affect change in the program when pressed. The Close-Window Button is Not in the Class JButton. The buttons that are in the title bar of the JFrame are not buttons of type JButton. They are a special part of the JFrame class. JFrame Classes. In the chapter, a JFrame class is a class that extends from JFrame. When it is stated that an object is a JFrame, it is an instance of a JFrame. The JLabel Class. A class that represents a label (text) that can be inserted onto a GUI. Layout Managers. You can manage the look of a GUI by using a layout manager. Layout managers help organize the components on the screen. The three layout managers discussed in this chapter are FlowLayout, BorderLayout, and GridLayout.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

Adding Color. You can add color to a JFrame by using the setBackground method and passing in the color that you would like to the background set to. Menus. Menus can be added to a GUI program using the JMenu class. You can add action listeners to JMenu items as with buttons. There are a few steps for creating a menu, which involve needed a menu bar, adding a menu to it, and then adding menu items to the menu. These menu items will have action listeners to change the GUI. The Dimension Class. The dimension class is used to represent a width and a height with graphical components. setActionCommand and getActionCommand. You can use these methods to set and get the action command for components on the GUI. The Dimension Class. A class that models a dimension, a width and a height. getText and setText. These methods are used in text fields or areas to get or set the characters that appear in them. The Classes JTextField and JTextArea. The JTextField and JTextArea both are ways for the user to input text into a GUI. The programmer can both set and get the text. These elements can also have action listeners attached to them. Number of Characters per Line. You can specify upon creation the number of characters wide and high (for text area only) for text components on the screen. This number corresponds to the number of em spaces in the dimension. Scroll Bars. Scroll bars are available for text components and are discussed in Chapter 18. Uncaught Exceptions. Uncaught exceptions in GUIs can cause undeterminate states and actions. It is best to catch all exceptions in a graphical program.

Tips Ending a Swing Program. Swing programs do not end simply by closing the window. An explicit call to System.exit() is required to end the program. This is why it is important to either give the default operation to the close button EXIT_ON_CLOSE or to create another way for there to be a call to System.exit(). Code a GUI’s Look and Actions Separately. The look of the GUI and what the GUI does are really two separate things. It is helpful to have methods that strictly set up the look of the GUI and others to focus on what the GUI will do when the user interacts with it. Labeling a Text Field. It is a good idea to label text fields so that the user knows what to enter in the text fields and areas on the screen. You can use JLabels to help do this.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

Inputting and Outputting Numbers. The text components do not display numbers, but rather strings that contain numbers. Therefore all numbers must be converted to text and converted from text when using the text components on your GUI. Pitfalls Forgetting to Program the Close-Window Button. Forgetting to give a default operation to the close-window button can keep the program from actually exiting when the window is closed. The window will have disappeared, but the program will still be running. Changing the Heading for actionPerformed. Since actionPerformed is a method that is being implemented from an interface you can not change the method heading and have it work the same. Examples A Simple Window. In this example we see the creation of our first graphical program. This example illustrates just how many steps are needed to create just the simple window. We have not yet added any real user interaction for this program. A Better Version of Our First Swing GUI. An updated version of the first GUI created in this chapter, it includes many of the features that are needed in a real GUI program. A GUI with a Label and Color. This example uses both labels and the ability to change the colors of various components on a GUI. A Tricolor Built with Panels. This example uses buttons and panels to build a GUI that shows three colors on the screen. A GUI with a Menu. This examples uses the menu bar and menu classes to show a GUI that has drop-down menus that the user can interact with. Programming Projects Answers 1. /** * Question1PigLatin.java * * This program uses Swing to allow a user to input some English * text into a JTextArea and click a button to convert the text * to pig latin. The translated text is displayed in a separate * JTextArea. The FlowLayout is used. * * Created: Sat Apr 16 2005 * * @author Kenrick Mock * @version 1 */ Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTextArea; import java.awt.FlowLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.Scanner; /** * PigLatin conversion program. */ class Question1PigLatin extends JFrame implements ActionListener { public static final int WIDTH = 800; public static final int HEIGHT = 400; // Where user enters English text private JTextArea sourceText; // Where program displays translated text private JTextArea translatedText; /** * PigLatinGUI * The constructor creates the window * and the GUI widgets. The button click * is the only control with an action listener. */ public Question1PigLatin() { super(); this.setSize(WIDTH, HEIGHT); this.setTitle("Pig Latin Translator"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout()); sourceText = new JTextArea("Enter source text here", 10, 30); add(sourceText); translatedText = new JTextArea("Translated Pig Latin text will go here.", 10, 30); add(translatedText); JButton btn = new JButton("Translate"); // Invoke actionPerformed for PigLatinGUI class Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

btn.addActionListener(this); add(btn); } /** * When the button is clicked this event is invoked. * This method uses a Scanner to parse each word, * each word is converted * to pig latin, and concatenated onto a string that * is output in the translatedText area. */ public void actionPerformed(ActionEvent e) { String src = sourceText.getText(); String translated = ""; // Scan from a String instead of the console Scanner scan = new Scanner(src); // Iterates through each word while (scan.hasNext()) { String word = scan.next(); // Get the translated word translated += convert(word) + " "; } // Display translation in the JTextArea translatedText.setText(translated); } /** * @param word The input word to convert to pig latin. * @return String The input word converted to pig latin. * If the first letter is a vowel then add "way" to the end. * Otherwise move the first letter to the end of the word and add "ay". */ public String convert(String word) { char firstLetter = word.toLowerCase().charAt(0); if ((firstLetter =='a') || (firstLetter == 'e') || (firstLetter=='i') || (firstLetter=='o') || (firstLetter=='u')) { return word + "way"; } return word.substring(1) + word.substring(0,1).toLowerCase() + "ay"; } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

// Our main method just displays the window public static void main(String[] args) { Question1PigLatin piggy = new Question1PigLatin(); piggy.setVisible(true); } } // Question1PigLatin

2. /** * NumberGame.java * * The program simulates a number game on a JFrame window. The JFrame * shows a 9-cell 3x3 grid of buttons. On click of each button, a * random number in the range of 0 to 50 is displayed on the button. A * prize money is awarded to the user based on the number generated on * click of the buttons as per the following scenarios. * <ol> * <li>If one of the numbers is odd, player gets a prize of $20.</li> * <li>if two of the numbers are odd, player gets a prize of $50.</li> * <li>If all the three numbers are odd, player gets a prize of $100. * </li> * <li>If any of the three numbers is 50, then it’s a bumper prize of * $1000.</li> * </ol> * Created: Feb 8, 2016 * * @author * @version 1 */ import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class NumberGame extends JFrame implements ActionListener { int rows = 3; int columns = 3; int clickCount = 0, n1, n2, n3; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

int oddCount = 0; int frameWidth = 300; int frameHeight = 300; JLabel l1; JButton b[]; public static void main(String[] args) { NumberGame gui = new NumberGame(); gui.setVisible(true); } /** * Constructor that initializes a JFrame and sets its dimensions * and adds buttons in a 3x3 cell. */ public NumberGame() { super(); setSize(frameWidth, frameHeight); setTitle("Number Game"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); l1 = new JLabel("YOU WON : 0$"); add(l1, BorderLayout.NORTH); JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(rows, columns)); b = new JButton[rows * columns]; for (int i = 0; i < b.length; i++) { p1.add(b[i] = new JButton()); b[i].addActionListener(this); } this.add(p1, BorderLayout.CENTER); } /** * Resets the grid after every game is completed */ public void reset() { for (int i = 0; i < b.length; i++) b[i].setText(""); l1.setText("YOU WON : 0$"); oddCount = 0; clickCount = 0; } /** * Checks the numbers generated when the user clicks any button and * displays the amount won by the user immediately. */ public void check() { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

if (n1 == 50 || n2 == 50 || n3 == 50) l1.setText("YOU WON : 1000$"); else if (oddCount == 1) l1.setText("YOU WON : 20$"); else if (oddCount == 2) l1.setText("YOU WON : 50$"); else if (oddCount == 3) l1.setText("YOU WON : 100$"); } /** * For every action that takes place with a click, this method generates a random * number and displays it on the respective button. Once the user * clicks on 3 buttons, the 4th button click will reset the grid * to start the new game. */ public void actionPerformed(ActionEvent e) { Random r = new Random(); JButton b1 = (JButton) e.getSource(); if (clickCount == 0) { n1 = r.nextInt(50); b1.setText(n1 + ""); clickCount++; if (n1 % 2 != 0) oddCount++; } else if (clickCount == 1) { n2 = r.nextInt(50); b1.setText(n2 + ""); clickCount++; if (n2 % 2 != 0) oddCount++; } else if (clickCount == 2) { n3 = r.nextInt(50); b1.setText(n3 + ""); clickCount++; if (n3 % 2 != 0) oddCount++; check(); } else reset(); } } 3. /** * Calculator.java * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

* Created: Wed Jan 28 20:32:23 2004 * * @author Adrienne Decker * @version */ import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JLabel; import java.awt.Container; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.Color; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Calculator extends JFrame /*implements ActionListener*/ { private JTextField _result, _operand; private JButton _one, _two, _three, _four, _five, _six, _seven, _eight, _nine, _zero, _point, _add, _sub, _mult, _div; public Calculator () { setTitle("Question 3"); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new BorderLayout()); add(this.createTextFields(), BorderLayout.NORTH); add(this.createNumbers(), BorderLayout.CENTER); } public JPanel createTextFields() { JPanel text = new JPanel(); text.add(new JLabel("Result")); _result = new JTextField("0", 10); _result.setEditable(false); text.add(_result); text.add(new JLabel("Operand")); _operand = new JTextField(10); _operand.setEditable(false); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

text.add(_operand); return text; } public JPanel createNumbers() { JPanel nums = new JPanel(); nums.setLayout(new BorderLayout()); JPanel ops = new JPanel(); ops.setLayout(new GridLayout(4,1)); _add = new JButton("+"); _add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Calculator.this.operatorPressed("+"); } }); ops.add(_add); _sub = new JButton("-"); _sub.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Calculator.this.operatorPressed("-"); } }); ops.add(_sub); _mult = new JButton("*"); _mult.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Calculator.this.operatorPressed("*"); } }); ops.add(_mult); _div = new JButton("/"); _div.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

{ try { Calculator.this.divisionPressed(); } catch(DivisionByZeroException dbze) { _operand.setText("Error"); } } }); ops.add(_div); nums.add(ops, BorderLayout.EAST); JPanel numbers = new JPanel(); numbers.setLayout(new GridLayout(4,3)); _one = new JButton("1"); _one.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { _operand.setText(_operand.getText() + "1"); } }); numbers.add(_one); _two = new JButton("2"); _two.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { _operand.setText(_operand.getText() + "2"); } }); numbers.add(_two); _three = new JButton("3"); _three.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { _operand.setText(_operand.getText() + "3"); } }); numbers.add(_three); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

_four = new JButton("4"); _four.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { _operand.setText(_operand.getText() + "4"); } }); numbers.add(_four); _five = new JButton("5"); _five.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { _operand.setText(_operand.getText() + "5"); } }); numbers.add(_five); _six = new JButton("6"); _six.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { _operand.setText(_operand.getText() + "6"); } }); numbers.add(_six); _seven = new JButton("7"); _seven.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { _operand.setText(_operand.getText() + "7"); } }); numbers.add(_seven); _eight = new JButton("8"); _eight.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

_operand.setText(_operand.getText() + "8"); } }); numbers.add(_eight); _nine = new JButton("9"); _nine.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { _operand.setText(_operand.getText() + "9"); } }); numbers.add(_nine); _point = new JButton("."); _point.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { _operand.setText(_operand.getText() + "."); } }); numbers.add(_point); _zero = new JButton("0"); _zero.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { _operand.setText(_operand.getText() + "0"); } }); numbers.add(_zero);

nums.add(numbers, BorderLayout.CENTER); return nums; } private double getNumFromResult() { return Double.parseDouble(_result.getText()); } private double getNumFromOperand() Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

{ return Double.parseDouble(_operand.getText()); } private void divisionPressed() throws DivisionByZeroException { double result = getNumFromResult(); double num = getNumFromOperand(); if ( num < 1.0e-10 && num > -1.0e-10 ) { throw new DivisionByZeroException(); } // end of if () else { result /= num; _result.setText("" + result); _operand.setText(""); }//end of else } private void operatorPressed(String op) { double result = getNumFromResult(); double num = getNumFromOperand(); if ( op.equals("+") ) { result += num; } // end of if () else if ( op.equals("-") ) { result -= num; } // end of if () else if ( op.equals("*") ) { result *= num; } // end of if () _result.setText("" + result); _operand.setText(""); } public static void main (String[] args) { Calculator calc = new Calculator(); calc.pack(); calc.show(); } // end of main () }// Calculator Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

/** * DivisionByZeroException.java * * * Created: Wed Jan 28 21:21:54 2004 * * @author Adrienne Decker * @version */ public class DivisionByZeroException extends Exception{ public DivisionByZeroException (){ } }// DivisionByZeroException 4. /** * Driving.java * * This program creates a simple JFrame with a driver questionnaire. * Based on the answer given by the message i displayed on the * frame. * * Created: Feb 8, 2016 * * @author * @version 1 */ import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; public class Driving extends JFrame implements ActionListener { JLabel l1, l2; JButton b1, b2; int yesCount = 0, noCount = 0; public static void main(String[] args) { Driving gui = new Driving(); gui.setVisible(true); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

/** * Constructs the class by setting dimensions of the frame and * then adding the question label, yes/no buttons and on click * action listeners for both the buttons. */ public Driving() { super(); setSize(450, 150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new GridLayout(2, 2)); add(l1 = new JLabel("Are you an excellent driver?")); add(l2 = new JLabel("Yes : " + yesCount + " No : " + noCount)); add(b1 = new JButton("Yes")); add(b2 = new JButton("No")); b1.addActionListener(this); b2.addActionListener(this); } /** * Displays a label with a message based on the action event once * the user clicks on any of the two buttons. */ public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Yes")) { l1.setText("We need you!!!!"); yesCount++; l2.setText("Yes : " + yesCount + " No : " + noCount); } else { l1.setText("You need to practice!!!"); noCount++; l2.setText("Yes : " + yesCount + " No : " + noCount); } } } 5. /** * Question 5 * * Trivia game with 5 hard-coded questions. Uses a single array * of trivia objects. Requires the Trivia class from PP 6.13. * A GUI has been added with a GridLayout for the current * question and a button. * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

* Created: Sat Mar 15 2009 * * @author Kenrick Mock * @version 1 */ import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JButton; import java.awt.GridLayout; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Color; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class TriviaGame extends JFrame implements ActionListener { // GUI Elements public static final int WIDTH = 500; public static final int HEIGHT = 200; public static final int NUMBER_OF_CHAR = 30; private JTextField answer; private JLabel question; private JLabel info; // Game Elements private Trivia[] trivia; private int score = 0; // Overall score private int questionNum = 0; // Track if question 0 - 4 private static int NUMQUESTIONS = 5; public TriviaGame() { super("Trivia Game");

// Constructor

trivia = new Trivia[NUMQUESTIONS]; // Manually copy in questions, answers, and values // Note that we need to use NEW to create the instance of each // object to store in the array trivia[0] = new Trivia("The first Pokemon that Ash receives from Professor Oak", "pikachu",1); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

trivia[1] = new Trivia("Erling Kagge skiied into here alone on January 7, 1993", "south pole", 2); trivia[2] = new Trivia("1997 British band that produced 'Tub Thumper'", "chumbawumba", 2); trivia[3] = new Trivia("Who is the tallest person on record (8 ft. 11 in) that has lived?", "Robert Wadlow", 3); trivia[4] = new Trivia("PT Barnum said 'This way to the _______' to attract people to the exit.", "egress", 1); // GUI Setup setSize(WIDTH, HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new GridLayout(2, 1)); JPanel triviaPanel = new JPanel( ); triviaPanel.setLayout(new BorderLayout( )); triviaPanel.setBackground(Color.WHITE); answer = new JTextField(NUMBER_OF_CHAR); question = new JLabel("Question:"); info = new JLabel(""); triviaPanel.add(answer, BorderLayout.SOUTH); triviaPanel.add(question, BorderLayout.CENTER); triviaPanel.add(info, BorderLayout.NORTH); add(triviaPanel); JButton actionButton = new JButton("Submit"); actionButton.addActionListener(this); add(actionButton); // Show first question question.setText("Question " + (questionNum + 1) + ". " + trivia[questionNum].getQuestion()); } public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand( ); String guess; if (actionCommand.equals("Submit")) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

if (questionNum >= trivia.length) { return; // Do nothing if game over } // Check if the answer is correct or not guess = answer.getText().toLowerCase(); String answer = trivia[questionNum].getAnswer().toLowerCase(); if (guess.equals(answer)) { info.setText("That is correct!"); score += trivia[questionNum].getValue(); } else { info.setText("Wrong. The correct answer is " + trivia[questionNum].getAnswer() + "."); } // Show score info.setText(info.getText() + " Your score is " + score); // Show next question or game over questionNum++; if (questionNum >= trivia.length) { info.setText(info.getText() + ". Game over."); return; } question.setText("Question " + (questionNum + 1) + ". " + trivia[questionNum].getQuestion()); } else System.out.println("Unexpected error."); } // Main method public static void main(String[] args) { TriviaGame gui = new TriviaGame( ); gui.setVisible(true); } } // Question 5

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

6. /** * TextEditor.java * * The program creates a simple text editor, that allows the user to * enter text, and two buttons namely Save and Clear. The Save button * saves the contents in the text editor to a file. Whereas the Clear * button clears the contents from the text editor. * * * Created: Feb 8, 2016 * * @author * @version 1 */ import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; public class TextEditor extends JFrame implements ActionListener { private JTextArea textArea; private JButton save, clear; private JPanel p1; /** * Creates a text editor window with dimensions and adds a * JTextArea component which lets the user input text. */ public TextEditor() { super(); setSize(500, 500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); textArea = new JTextArea(10, 20); add(textArea, BorderLayout.CENTER); p1 = new JPanel(); p1.setLayout(new FlowLayout()); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 17, Instructor’s Manual

p1.add(save = new JButton("Save")); p1.add(clear = new JButton("Clear")); add(p1, BorderLayout.SOUTH); save.addActionListener(this); clear.addActionListener(this); } public static void main(String[] args) { TextEditor gui = new TextEditor(); gui.setVisible(true); } /** * Based on the button that user clicks, respective action is * performed. When the user clicks on Save button, the contents in * the text editor are stored in a file named temp.txt. */ public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Save")) { try { PrintWriter out = new PrintWriter(new File("temp.txt")); out.println(textArea.getText()); } catch (IOException ex) { System.out.println(ex.getMessage()); } } else textArea.setText(""); } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

Chapter 18

Swing II Key Terms window event window listener WindowEvent WindowListener dispose icon ImageIcon setIcon setText button with only an icon view port JScrollPane setting scroll bar policies origin (x,y) bounding box paint Graphics drawOval drawLine drawOval drawArc rounded rectangle repaint repaint manager validate pack setColor RGB color system Color constructor setFont Font point size

Brief Outline 18.1 Window Listeners The dispose Method The WindowAdapter Class 18.2 Icons and Scroll Bars Icons Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

Scroll Bars 18.3 The Graphics Class Coordinate System for Graphics Objects The Method paint and the Class Graphics Drawing Ovals Drawing Arcs Rounded Rectangles paintComponent for Panels Action Drawings and repaint Some More Details on Updating a GUI 18.4 Colors Specifying a Drawing Color Defining Colors The JColorChooser Dialog Window 18.5 Fonts and the drawString Method The drawString method Fonts Teaching Suggestions This chapter discusses some of the rest of the features available when creating graphical programs using swing. The first section talks about how to gain control over the events registering on the buttons of the JFrame by implementing the WindowListener interface. We are introduced to icons and scroll bars and the tools for drawing graphics on the screen. These sections also tell us how to update the look of the GUI while the program is running by using the paintComponent and repaint methods. Section 4 introduces colors and the JColorChooser Dialog window for helping the user to choose colors for an application. Lastly, we are shown how to use different font styles and sizes using the Font and drawString methods. This chapter may be covered immediately after Chapter 17 or the topics can be merged in some cases, like covering scroll bars and icons right after the discussions of the JButton and JTextArea in Chapter 17.

Key Points The WindowListener Interface. To have a GUI react when the user clicks the JFrame buttons, it must implement the WindowListener interface. The dispose Method. This method can be used to destroy one window from a multi-window program. It is only when all the windows of a program are closed that it will end. Icons and the Class ImageIcon. An icon is a picture. An ImageIcon is the component that turns an image into a component in your GUI in swing.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

The Insets Class. Insets are used to set the margins of a button or menu item. setIcon and setText. You can add an icon to a JButton, JMenu, or a JLabel. You can also set the text of any of these components. Scroll Bars. You can add scroll bars to a text area and some other components to allow the user to scroll within the area. The Graphics Class. Every element that can be drawn on the screen has an associated Graphics object to help it be drawn correctly. When using a Graphics object as a parameter to a method it specifies what the area is that the drawing will take place in. The repaint and paint Methods. When wanting the graphics on the screen to refresh, we normally call the repaint method. We do not redefine the repaint method, but simply call it when we want to refresh the screen. The setColor Method. You can use the setColor method to set the color for the drawing of the graphics object you are drawing to the screen. RGB Colors. The class color uses colors specified by their red, green, blue components. The drawString method. This method draws text at a particular point on the screen.

Pitfalls Forgetting to Invoke setDefaultCloseOperation. Even when you create a WindowListener for your JFrame, you should still give a default close operation. If the listener will take care of closing, then set the default close operation to DO_NOTHING_ON_CLOSE. This value will have a default that may or may not be what is desired if you do not reset the default operation. Using doubles to Define a Color. You can create a color with a fractional amount of red, green, or blue, but you must use float values. To ensure that the compiler knows that it is a float value, you need to use a typecast.

Examples A Window Listener Inner Class. In this example we see using a class that implements the WindowListener interface as an inner class. This example shows an action more than just closing when the user selects to close a window. Components with Changing Visibility. This example shows components who appear and disappear throughout the course of the program depending upon the users actions with the program.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

Programming Projects Answers 1. /** * Question1Gasket.java * * This program uses the Graphics drawLine method to create a * single pixel and plot a Sierpinski gasket. * * Created: Sun Apr 17 2005 * * @author Kenrick Mock * @version 1 */ import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.Color; import java.awt.Graphics; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; class Question1Gasket extends JFrame { private static final int NUMPOINTS = 3; private int vertex_x[] = new int[NUMPOINTS]; private int vertex_y[] = new int[NUMPOINTS]; private JPanel mainPanel;

// Holds x,y coordinates // of the three triangle corners // All drawing in this panel

// In the constructor, set our size, title, add a JPanel, // and set up coordinates of where the vertices are for the triangle public Question1Gasket() { super(); this.setSize(800, 600); this.setTitle("Sierpinski Gasket"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); mainPanel = new JPanel(); // The panel we will draw on mainPanel.setBackground(Color.PINK); add(mainPanel, BorderLayout.CENTER); vertex_x[0] = 400; vertex_y[0] = 50; // Top of triangle Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

vertex_x[1] = 20; vertex_y[1] = 550; // Bottom left corner vertex_x[2] = 780; vertex_y[2] = 550; // Bottom right corner } /** * paint draws pixels according to the Sierpinksi gasket algorithm. * It loops 50,000 times and randomly selects a target point, either * point 0, 1, or 2. Compute the midpoint between the current point and * a randomly selected point, draw a pixel there, and repeat. */ public void paint(Graphics g) { int targetVertex; int target_x, target_y; super.paint(g); // Initialize our current coordinates to the top of the triangle int current_x = vertex_x[0]; int current_y = vertex_y[0]; g.setColor(Color.black); // Loop many times to draw the gasket, plotting a single point // each time for (int i = 0; i < 50000; i++) { // Select a random vertex as our target, either 0,1, or 2 targetVertex = (int) (Math.random() * NUMPOINTS); target_x = vertex_x[targetVertex]; target_y = vertex_y[targetVertex]; current_x = (current_x + target_x)/2; current_y = (current_y + target_y)/2; g.drawLine(current_x, current_y, current_x, current_y); } } // Our main method just displays the window public static void main(String[] args) { Question1Gasket sierpinski = new Question1Gasket(); sierpinski.setVisible(true); } } // Question1Gasket

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

2. Part A) /** * Question2MarsA.java * * This program reads a file containing image data from the * Martian rover Spirit and plots it on the screen in a JPanel. * * Created: Sun Apr 17 2005 * * @author Kenrick Mock * @version 1 */ import javax.swing.JFrame; import javax.swing.JPanel; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.FileNotFoundException; import java.awt.Color; import java.awt.Graphics; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.Scanner; public class Question2MarsA extends JFrame { // Filename to load private static final String filename = "humphrey-img.txt"; private static final int WIDTH = 480; private static final int HEIGHT = 520; private int[][] imgData = null; private int imgSize;

// 2D array to hold greyscale of each pixel // as read in from the file // Height and Width of the image

/** * In the constructor, set our size, title, and load the * contents of the file into the array. */ public Question2MarsA() { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

super(); this.setSize(WIDTH, HEIGHT); this.setTitle("Raw Martian Image"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); add(new JPanel(), BorderLayout.CENTER); // The panel we will draw on // Load the file BufferedReader inData = null; try { inData = new BufferedReader(new FileReader(filename)); String s = inData.readLine(); imgSize = Integer.parseInt(s); // Height/width from first line imgData = new int[imgSize][imgSize];// Allocate array to hold data // Loop over the dimensions of the image // and read in each value into the array for (int i=0; i<imgSize; i++) { s = inData.readLine(); // Create a scanner to parse the file Scanner scan = new Scanner(s); for (int j=0; j<imgSize; j++) { imgData[j][i] = scan.nextInt(); } } inData.close(); } catch (Exception e) { System.out.println(e); System.exit(0); } }

/** * The paint method merely loops through the array data and * plots each pixel on the screen using drawLine. */ public void paint(Graphics g) { super.paint(g); int i,j,c; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

for (i=0; i<imgSize; i++) { for (j=0; j<imgSize; j++) { c = imgData[j][i]; // Set the RGB color to a shade of grey g.setColor(new Color(c,c,c)); // Draw pixel offset from the upper left corner by 10,35 g.drawLine(j+10,i+35,j+10,i+35); } } } // Our main method just displays the window public static void main(String[] args) { Question2MarsA marsImage = new Question2MarsA(); marsImage.setVisible(true); } } // Question2MarsA

Part B) /** * Question2MarsB.java * * This program reads a file containing image data from the * Martian rover Spirit and plots it on the screen in a JPanel. * The plotted image is enhanced by scaling the color histogram * to the range from 0 to 255. * * Created: Sun Apr 17 2005 * * @author Kenrick Mock * @version 1 */ import javax.swing.JFrame; import javax.swing.JPanel; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.FileNotFoundException; import java.awt.Color; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

import java.awt.Graphics; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.Scanner; public class Question2MarsB extends JFrame { // Filename to load private static final String filename = "humphrey-img.txt"; private static final int WIDTH = 480; private static final int HEIGHT = 520; private int[][] imgData = null; private int imgSize;

// 2D array to hold greyscale of each pixel // as read in from the file // Height and Width of the image

/** * In the constructor, set our size, title, and load the * contents of the file into the array. After we load the * contents of the file into the array, find the min and max * intensity values so we can scale the histogram. */ public Question2MarsB() { super(); this.setSize(WIDTH, HEIGHT); this.setTitle("Enhanced Martian Image"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); add(new JPanel(), BorderLayout.CENTER); // The panel we will draw on // Load the file BufferedReader inData = null; try { inData = new BufferedReader(new FileReader(filename)); String s = inData.readLine(); imgSize = Integer.parseInt(s); // Height/width from first line imgData = new int[imgSize][imgSize];// Allocate array to hold data // Loop over the dimensions of the image and read // in each value into the array for (int i=0; i<imgSize; i++) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

s = inData.readLine(); // Create a scanner to parse the file Scanner scan = new Scanner(s); for (int j=0; j<imgSize; j++) { imgData[j][i] = scan.nextInt(); } } inData.close(); } catch (Exception e) { System.out.println(e); System.exit(0); } // Find minimum and maximum value int min = 9999; int max = -9999; for (int i=0; i<imgSize; i++) for (int j=0; j<imgSize; j++) { if (imgData[j][i]>max) max=imgData[j][i]; if (imgData[j][i]<min) min=imgData[j][i]; } // We found the minimum and maximum. // Now scale each pixel color so we have colors // in the full range from 0-255. for (int i=0; i<imgSize; i++) for (int j=0; j<imgSize; j++) { imgData[j][i] = (255*(imgData[j][i]-min)) / (max-min); } }

/** * The paint method merely loops through the array data and * plots each pixel on the screen using drawLine. */ public void paint(Graphics g) { super.paint(g); int i,j,c; for (i=0; i<imgSize; i++) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

{ for (j=0; j<imgSize; j++) { c = imgData[j][i]; // Set the RGB color to a shade of grey g.setColor(new Color(c,c,c)); // Draw pixel offset from the upper left corner by 10,35 g.drawLine(j+10,i+35,j+10,i+35); } } } // Our main method just displays the window public static void main(String[] args) { Question2MarsB marsImage = new Question2MarsB(); marsImage.setVisible(true); } } // Question2MarsB

3. /** * Gesture.java * * The program displays JFrame window with three buttons, namely * Happy, Sad and Shocking, to display respective gestures using * images. Gesture images are generated by using the methods available * in the Graphics class. * * Created: Feb 8, 2016 * * @author * @version 1 */ import javax.swing.JFrame; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

import java.awt.Graphics; import java.awt.Color; import java.awt.FlowLayout; public class Gesture extends JFrame { public static final int WINDOW_WIDTH = 400; public static final int WINDOW_HEIGHT = 400; public static final int FACE_DIAMETER = 200; public static final int X_FACE = 100; public static final int Y_FACE = 100; public static final int EYE_WIDTH = 20; public static final int EYE_HEIGHT = 10; public static final int X_RIGHT_EYE = X_FACE + 55; public static final int Y_RIGHT_EYE = Y_FACE + 60; public static final int X_LEFT_EYE = X_FACE + 130; public static final int Y_LEFT_EYE = Y_FACE + 60; public static final int MOUTH_WIDTH = 100; public static final int MOUTH_HEIGHT = 50; public static final int X_MOUTH = X_FACE + 50; public static final int Y_MOUTH = Y_FACE + 100; public static final int MOUTH_START_ANGLE = 180; public static final int MOUTH_ARC_SWEEP = 180; private int expression; /** * Gesture action listener that captures the expression chosen by * the user and repaints the expression graphic image. */ private class GestureAction implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Happy")) expression = 1; else if (e.getActionCommand().equals("Sad")) expression = 2; else Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

expression = 3; repaint(); } } public static void main(String[] args) { Gesture drawing = new Gesture(); drawing.setVisible(true); } /** * Constructor that sets dimensions to the JFrame window, adds * three buttons Happy, Sad and Shocking and sets action listeners * to them. */ public Gesture() { setSize(WINDOW_WIDTH, WINDOW_HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("Hello There!"); setLayout(new FlowLayout()); getContentPane().setBackground(Color.white); JButton happyButton = new JButton("Happy"); happyButton.addActionListener(new GestureAction()); add(happyButton); JButton angryButton = new JButton("Sad"); angryButton.addActionListener(new GestureAction()); add(angryButton); JButton shockingButton = new JButton("Socking"); shockingButton.addActionListener(new GestureAction()); add(shockingButton); } /** Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

* Method that draws the expression graphic. */ @Override public void paint(Graphics g) { super.paint(g); final int MID = 150; final int TOP = 50; g.drawOval(X_FACE, Y_FACE, FACE_DIAMETER, FACE_DIAMETER); if (expression == 1) { //Draw Eyes: g.clearRect(X_RIGHT_EYE, Y_RIGHT_EYE, EYE_WIDTH, EYE_HEIGHT); g.fillOval(X_RIGHT_EYE, Y_RIGHT_EYE, EYE_WIDTH, EYE_HEIGHT); g.fillOval(X_LEFT_EYE, Y_LEFT_EYE, EYE_WIDTH, EYE_HEIGHT); g.drawArc(X_MOUTH, Y_MOUTH, MOUTH_WIDTH, MOUTH_HEIGHT, MOUTH_START_ANGLE, MOUTH_ARC_SWEEP); } else if (expression == 2) { g.clearRect(X_RIGHT_EYE, Y_RIGHT_EYE, EYE_WIDTH, EYE_HEIGHT); g.fillOval(X_RIGHT_EYE, Y_RIGHT_EYE, EYE_WIDTH, EYE_HEIGHT); g.fillOval(X_LEFT_EYE, Y_LEFT_EYE, EYE_WIDTH, EYE_HEIGHT); g.drawArc(X_MOUTH, Y_MOUTH, MOUTH_WIDTH, MOUTH_HEIGHT, 0, 180); } else { g.clearRect(X_RIGHT_EYE, Y_RIGHT_EYE, EYE_WIDTH, EYE_HEIGHT); g.fillOval(X_RIGHT_EYE, Y_RIGHT_EYE, EYE_WIDTH, EYE_HEIGHT); g.fillOval(X_LEFT_EYE, Y_LEFT_EYE, EYE_WIDTH, EYE_HEIGHT); g.drawArc(X_MOUTH, Y_MOUTH, MOUTH_WIDTH, MOUTH_HEIGHT, 0, 360); } } } 4. /** * Question4.java * Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

* * Created: Thu Jan 29 21:02:51 2004 * * @author Adrienne Decker * @version */ import java.awt.event.WindowListener; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JLabel; import java.awt.Container; import java.awt.Color; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Question4 extends JFrame implements ActionListener, WindowListener { private JTextField _message; private JButton _exit; public Question4 (){ setTitle("Question 4"); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowListener(this); add(this.createGUIComponents()); } private JPanel createGUIComponents() { JPanel panel = new JPanel(); _message = new JTextField(25); panel.add(_message); _exit = new JButton("Exit"); _exit.addActionListener(this); panel.add(_exit); return panel; } public void actionPerformed(ActionEvent e) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

this.dispose(); System.exit(0); } public void windowOpened(WindowEvent e) { _message.setText("Window opening event."); } public void windowClosing(WindowEvent e) { _message.setText("Window closing event."); } public void windowClosed(WindowEvent e) { _message.setText("Window closed event."); } public void windowIconified(WindowEvent e) { _message.setText("Window iconified event."); } public void windowDeiconified(WindowEvent e) { _message.setText("Window deiconified event."); } public void windowActivated(WindowEvent e) { _message.setText("Window activated event."); } public void windowDeactivated(WindowEvent e) { _message.setText("Window deactivated event."); } public static void main(String[] args){ Question4 converter = new Question4(); converter.pack(); converter.show(); } } // Question4

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

5. import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.FlowLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.WindowListener; import java.awt.event.WindowEvent; import java.awt.Container; import java.awt.BorderLayout; import java.awt.Graphics; import java.awt.Color; public class ActionFace extends JFrame { public static final int WINDOW_WIDTH = 400; public static final int WINDOW_HEIGHT = 400; public static final int SMALL_WIDTH = 200; //for confirm window public static final int SMALL_HEIGHT = 100;//for confirm window public static final int FACE_DIAMETER = 200; public static final int X_FACE = 100; public static final int Y_FACE = 100; public static final int EYE_WIDTH = 20; public static final int EYE_HEIGHT = 10; public static final int X_RIGHT_EYE = X_FACE + 55; public static final int Y_RIGHT_EYE = Y_FACE + 60; public static final int X_LEFT_EYE = X_FACE + 130; public static final int Y_LEFT_EYE = Y_FACE + 60; public static final int MOUTH_WIDTH = 100; public static final int MOUTH_HEIGHT = 50; public static final int X_MOUTH = X_FACE + 50; public static final int Y_MOUTH = Y_FACE + 100; public static final int MOUTH_START_ANGLE = 180; public static final int MOUTH_ARC_SWEEP = 180; public static final int NOSE_DIAMETER = 15; public static final int X_NOSE = X_FACE + (FACE_DIAMETER/2 - 7); public static final int Y_NOSE = Y_FACE + (FACE_DIAMETER/2 - 7);

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

public static final int MUST_WIDTH = 60; public static final int X_MUST = X_FACE + (FACE_DIAMETER/2 - 30); public static final int Y_MUST = Y_FACE + (FACE_DIAMETER/2 + 9); private boolean wink; private boolean smile = true; private class WinkAction implements ActionListener { public void actionPerformed(ActionEvent e) { wink = true; repaint( ); } } // End of WinkAction inner class private class SmileAction implements ActionListener { public void actionPerformed(ActionEvent e) { smile = true; repaint(); } } private class FrownAction implements ActionListener { public void actionPerformed(ActionEvent e) { smile = false; repaint(); } } private class CheckOnExit implements WindowListener { public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) { ConfirmWindow checkers = new ConfirmWindow( ); checkers.setVisible(true); } public void windowClosed(WindowEvent e) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

{} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} } //End of inner class CheckOnExit

private class ConfirmWindow extends JFrame implements ActionListener { public ConfirmWindow( ) { setSize(SMALL_WIDTH, SMALL_HEIGHT); Container confirmContent = getContentPane( ); confirmContent.setBackground(Color.YELLOW); confirmContent.setLayout(new BorderLayout( )); JLabel confirmLabel = new JLabel( "Are you sure you want to exit?"); confirmContent.add(confirmLabel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel( ); buttonPanel.setBackground(Color.ORANGE); buttonPanel.setLayout(new FlowLayout( )); JButton exitButton = new JButton("Yes"); exitButton.addActionListener(this); buttonPanel.add(exitButton); JButton cancelButton = new JButton("No"); cancelButton.addActionListener(this); buttonPanel.add(cancelButton); confirmContent.add(buttonPanel, BorderLayout.SOUTH); } public void actionPerformed(ActionEvent e) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

String actionCommand = e.getActionCommand( ); if (actionCommand.equals("Yes")) System.exit(0); else if (actionCommand.equals("No")) dispose( );//Destroys only the ConfirmWindow. else System.out.println("Unexpected Error in Confirm Window."); } } //End of inner class ConfirmWindow

public static void main(String[] args) { ActionFace drawing = new ActionFace( ); drawing.setVisible(true); } public ActionFace( ) { setSize(WINDOW_WIDTH, WINDOW_HEIGHT); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowListener(new CheckOnExit()); setTitle("Hello There!"); setLayout(new BorderLayout( )); setBackground(Color.white); JPanel buttons = new JPanel(); JButton winkButton = new JButton("Click for a Wink."); winkButton.addActionListener(new WinkAction( )); buttons.add(winkButton); wink = false; JButton smile = new JButton("Smile"); smile.addActionListener(new SmileAction()); buttons.add(smile); JButton frown = new JButton("Frown"); frown.addActionListener(new FrownAction()); buttons.add(frown); add(buttons, BorderLayout.SOUTH); } public void paint(Graphics g) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

super.paint(g); g.drawOval(X_FACE, Y_FACE, FACE_DIAMETER, FACE_DIAMETER); //Draw Right Eye: g.setColor(java.awt.Color.BLUE); g.fillOval(X_RIGHT_EYE, Y_RIGHT_EYE, EYE_WIDTH, EYE_HEIGHT); //Draw Left Eye: if (wink) { g.setColor(java.awt.Color.BLACK); g.drawLine(X_LEFT_EYE, Y_LEFT_EYE, X_LEFT_EYE + EYE_WIDTH, Y_LEFT_EYE); } else { g.setColor(java.awt.Color.BLUE); g.fillOval(X_LEFT_EYE, Y_LEFT_EYE, EYE_WIDTH, EYE_HEIGHT); } //Draw Mouth if ( smile ) { g.setColor(java.awt.Color.RED); g.drawArc(X_MOUTH, Y_MOUTH, MOUTH_WIDTH, MOUTH_HEIGHT, MOUTH_START_ANGLE, MOUTH_ARC_SWEEP); } // end of if () else { g.setColor(java.awt.Color.RED); g.drawArc(X_MOUTH, Y_MOUTH + MOUTH_HEIGHT, MOUTH_WIDTH, MOUTH_HEIGHT, MOUTH_START_ANGLE, -MOUTH_ARC_SWEEP); } // end of else //Draw Nose: g.setColor(java.awt.Color.BLACK); g.fillOval(X_NOSE, Y_NOSE, NOSE_DIAMETER, NOSE_DIAMETER); //Draw Mustache: g.setColor(new java.awt.Color(119, 68, 28)); g.drawLine(X_MUST, Y_MUST, MUST_WIDTH + X_MUST, Y_MUST); } } // ActionFace

6. /** * FontDemo.java * * The program uses the Font class to display the user entered text in Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

* three different font styles (SansSerif Plain, Arial Bold and Serif * Italic) * * Created: Feb 8, 2016 * * @author * @version 1 */ import javax.swing.JFrame; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Graphics; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Font; import javax.swing.JLabel; import javax.swing.JTextField; public class FontDemo extends JFrame implements ActionListener { public static final int WIDTH = 500; public static final int HEIGHT = 300; private String theText; private JLabel l1; private JTextField t1; private JButton b1; private Font fontObj; public static void main(String[] args) { FontDemo gui = new FontDemo(); gui.setVisible(true); } /** * Sets dimensions to the frame, adds text field and a Preview * button on click of which the text in the text field is shown in * 3 different font styles. */ public FontDemo() { setSize(WIDTH, HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("Font Box"); getContentPane().setBackground(Color.WHITE); setLayout(new FlowLayout());

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

add(l1 = new JLabel("Enter Text")); add(t1 = new JTextField(20)); b1 = new JButton("Preview"); b1.addActionListener(this); add(b1); } public void actionPerformed(ActionEvent e) { Graphics g = getGraphics(); int point_size = 10; String fontDetails; fontObj = new Font("SansSerif", Font.PLAIN, point_size); g.setFont(fontObj); fontDetails = fontObj.getFontName() + "," + fontObj.getStyle() + "," + fontObj.getSize(); g.drawString(t1.getText() + ":" + fontDetails, 50, 100); point_size = 14; fontObj = new Font("Arial", Font.BOLD, point_size); g.setFont(fontObj); g.drawString(t1.getText() + ":" + fontDetails, 50, 150); point_size = 18; fontObj = new Font("Serif", Font.ITALIC, point_size); g.setFont(fontObj); g.drawString(t1.getText() + ":" + fontDetails, 50, 200); } } 7. /** * Question7.java * * This program uses the MouseListener interface * to draw circles at click points in a JFrame. * * Created: Fri Mar 22 2007 * * @author Kenrick Mock * @version 1 */ import javax.swing.JFrame; import java.awt.event.MouseListener; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

import java.awt.event.MouseEvent; import java.awt.Graphics; import java.awt.Color; import java.util.ArrayList; public class MouseDraw extends JFrame implements MouseListener { private int lastX = -1, lastY = -1; private ArrayList<Integer> xCoords; private ArrayList<Integer> yCoords;

public void mouseClicked (MouseEvent e) { System.out.println(e.getX() + " " + e.getY()); lastX = e.getX(); lastY = e.getY(); xCoords.add(e.getX()); yCoords.add(e.getY()); repaint(); } public void mouseEntered (MouseEvent e) {} public void mousePressed (MouseEvent e) {} public void mouseReleased (MouseEvent e) {} public void mouseExited (MouseEvent e) {} public MouseDraw() { super(); setSize(600,400); setTitle("Mouse Demo"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); addMouseListener(this); xCoords = new ArrayList<Integer>(); yCoords = new ArrayList<Integer>(); } public void paint(Graphics g) { super.paint(g); g.setColor(Color.blue); if (lastX != -1) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

} for (int i = 0; i < xCoords.size(); i++) { g.fillOval(xCoords.get(i)-3,yCoords.get(i)-3, 6, 6); } } public static void main(String[] args) { MouseDraw m = new MouseDraw(); m.setVisible(true); } } // Question 7 8. /** * Billing.java * * Displays window with Show Graph button, on click of which, a Bar * graph with its x-axis being the name of the month and y-axis being * the phone bill amount of the user is displayed on the frame. Sample * data is used for 5 months with name of the months and phone bill * amount for each month. * * Created: Feb 8, 2016 * * @author * @version 1 */ import java.awt.Color; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class Billing extends JFrame implements ActionListener { String months[] = { "January", "February", "March", "April", "May" }; double bill[] = { 230.5, 310.7, 370.0, 245.9, 117.1 }; final int FWIDTH = 450; final int FHEIGHT = 550; Graphics g;

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 18, Instructor’s Manual

public static void main(String[] args) { Billing gui = new Billing(); } /** * Sets dimensions to the frame and adds a button named Show Graph * on click of which the Bar Graph is displayed */ public Billing() { super(); setSize(FWIDTH, FHEIGHT); setTitle("Bill Analysis"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout()); JButton b1 = new JButton("Show Graph"); b1.addActionListener(this); add(b1); setVisible(true); } /** * Draws the bar graph according to the scale of the graph */ public void draw() { g = this.getGraphics(); int x = 50, y = 50, x1 = FWIDTH - 50, y1 = FHEIGHT - 50, tx1 = x, ty1 = y; g.setColor(Color.blue); g.drawLine(x, y, x, y1); g.drawLine(x, y1, x1, y1); for (int i = 0; tx1 < FWIDTH - 50; tx1 += 80, i++) { g.drawString(months[i], tx1, y1 + 10); int data = (int) bill[i]; g.fillRect(tx1 + 5, y1 - data, 30, data); } for (int i = 400; i >= 0; i -= 100) g.drawString(i + "", x - 25, y1 - i); } public void actionPerformed(ActionEvent e) { draw(); } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

Chapter 19

Java Never Ends Key Terms thread Thread.sleep getGraphics Thread run() start() run() TCP synchronized critical region server client UDP sockets port localhost blocking JavaBeans event handling persistence introspection database management system (DBMS) relational database Java DB / Apache Derby SQL Java applet Java servlet Java Server Pages HTML Form Common Gateway Interface JSP elements Declaration Expression Scriptlet Directive Page Import

Brief Outline 19.1 Multithreading Thread.sleep Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

The getGraphics Method Fixing a Nonresponsive Program Using Threads The Class Thread The Runnable Interface 19.2 Networking with Stream Sockets Sockets Sockets and Threading 19.3 JavaBeans The Component Model The JavaBeans Model 19.4 Java and Database Connections Relational Databases Java DB and JDBC SQL 19.5 Web Programming with Java Server Pages Applets, Servlets, and Java Server Pages Sun GlassFish Enterprise Server HTML Forms – The Common Gateway Interface JSP Declarations, Expressions, Scriptlets, and Directives 19.6 Introduction to Functional Programming in Java 8 19.7 Introduction to JavaFX

Teaching Suggestions This chapter discusses topics that may be beyond the scope of a CS1, but shows what interesting other things are available within Java. Sections 19.1 and 19.2 give enough information for students to create useful programs that use threading and networking. Section 19.3 serves mainly to introduce topics in JavaBeans, but not enough information is presented for students to write their own programs without additional resources. Sections 19.4 and 19.5 present examples for students to use as starting points to create database programs or JSP programs, but additional study is needed for more sophisticated programs. Section 19.6 is a brief introduction to the ideas behind functional programming and Section 19.7 is a brief introduction to JavaFX. Additional references are required for further details. The first section on threads can actually be incorporated into the discussion on GUIs as it is a GUI issue. The second section on Networking shows how to create a TCP client/server program. The implementation of sockets is much like the code required to read or write to text files, so this section should be familiar to students that have read Chapter 10. Threads can be used to allow multiple clients to connect to a server, or to prevent a client from locking up. The third section on JavaBeans introduces Component technology and architecture. The fourth section ends with the facilities in Java to allow for database connectivity. To connect to the database, you will need access to a database to create tables. The chapter uses Java DB, also known as Derby. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

The fifth section introduces web programming using JSP. The student should already know basic HTML. This is introduced in Chapter 20.

Key Points Thread.sleep. Method in the Thread class that pauses the current program for a certain number of milliseconds specified by the parameter passed into the method. getGraphics. This method gets the Graphics object that is associated with a particular JComponent. The Thread Class. You can define objects of type thread by creating a class that derives from the Thread class. Sockets. TCP is implemented via sockets. A server listens and waits on a port for a client to connect. Data is read through a BufferedReader and sent through a DataOutputStream. What is a JavaBean? A reusable software component that satisfies the requirements of the JavaBeans framework. What are Enterprise JavaBeans? Using the Enterprise JavaBeans framework makes the framework easier to adapt for business applications. A relational database organizes data in related tables. Fields are stored as columns and records as rows. Java DB or Derby is a database that runs in client/server or embedded mode. JDBC allows you to insert SQL commands into your Java code to access and manipulate databases. The SQL SELECT, UPDATE, CREATE TABLE, and INSERT commands allow data to be retrieved, modified created or inserted into a database. JSP refers to a framework that allows a programmer to create web-based Java applications that run on the server. Java code is added to a JSP page through directive, expression, declaration, and scriptlet tags.

Examples A Nonresponsive GUI. In this example we a GUI that performs a task that will not allow the user to end the program or close the window until the task of drawing the circles is complete. The chapter introduces threads as a solution to this type of problem. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

A Multithreaded Program. The second example in this chapter is a fix to the nonresponsive GUI looked at in the first example using multiple threads. Date and Time Server. A TCP server waits for a client to connect on port 7654 and sends back the current date and time.

Programming Projects Answers 1. /** * MovingBall.java * * The program displays a frame with its contents being a rectangular * box and a moving ball inside the box. When the moving ball collides * with the border of the box, it bounces back and starts moving in * the other direction. * * Created: Feb 8, 2016 * * @author * @version 1 */ import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class MovingBall extends JFrame implements ActionListener { public static final int FWIDTH = 500; public static final int FHEIGHT = 500; public static final int RWIDTH = FWIDTH - 40; public static final int RHEIGHT = FHEIGHT - 100; public static final int CIRCLE_SIZE = 50; public static final int PAUSE = 30; //milliseconds private JPanel box; public static void main(String[] args) { MovingBall gui = new MovingBall(); gui.setVisible(true); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

} /** * Constructs MovingBall class by setting frame dimensions, adding * a rectangular JPanel with a border and button on click of which * the box and moving ball are shown to the user. */ public MovingBall() { setSize(FWIDTH, FHEIGHT); setTitle("Moving Ball"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); box = new JPanel(); add(box, "Center"); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout()); JButton startButton = new JButton("Start"); startButton.addActionListener(this); buttonPanel.add(startButton); add(buttonPanel, "South"); } /** * When the user clicks on Start button a Ball graphic is created * and movement is started. */ public void actionPerformed(ActionEvent e) { Ball ballThread = new Ball(); ballThread.start(); } /** * Class that creates a graphic in the shape of a Ball. * */ private class Ball extends Thread { int x = 100, y = 100, radius = CIRCLE_SIZE / 2; int xmultiplier = 1, ymultiplier = 1; Graphics g = box.getGraphics(); @Override public void run() { while (true) { if (x <= 10 || x >= (RWIDTH - radius - 15)) xmultiplier = xmultiplier * -1; if (y <= 10 || y >= (RHEIGHT - radius - 15)) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

ymultiplier = ymultiplier * -1; g.drawRect(10, 10, RWIDTH, RHEIGHT); x = x + (xmultiplier) * 2; y = y + (ymultiplier) * 2; g.fillOval(x, y, 2 * radius, 2 * radius); doNothing(PAUSE); g.clearRect(x, y, 2 * radius + 5, 2 * radius + 5); } } } public void doNothing(int milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException e) { System.out.println("Unexpected interruption"); System.exit(0); } } } 2. /** * WheelRotation.java * * This program simulates the movement of a Bicycle wheel. The wheel * consists of a rim represented by a circle and several spokes * represented by a line connecting the centre of the circle to its * perimeter. The wheel should move from one end of the frame to * another end on the click of the start button which is present on the * frame. * * Created: Feb 8, 2016 * * @author * @version 1 */ import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

public class WheelRotation extends JFrame implements ActionListener { public static final int FWIDTH = 500; public static final int FHEIGHT = 300; public static final int CIRCLE_SIZE = 100; public static final int PAUSE = 100; //milliseconds private JPanel box; public static void main(String[] args) { WheelRotation gui = new WheelRotation(); gui.setVisible(true); } /** * Constructs the class by setting dimensions to the frame, adding * a box in which the wheel moves from one end to another end and * finally a Start button on the click of which the wheel starts * moving. */ public WheelRotation() { setSize(FWIDTH, FHEIGHT); setTitle("Moving Wheel"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); box = new JPanel(); add(box, "Center"); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout()); JButton startButton = new JButton("Start"); startButton.addActionListener(this); buttonPanel.add(startButton); add(buttonPanel, "South"); } /** * The Wheel starts moving on click of the Start button */ public void actionPerformed(ActionEvent e) { Wheel wheelThread = new Wheel(); wheelThread.start(); } /** * Class that draws a Wheel graphic with rim(circle) and spokes * (lines connecting the centre and perimeter of the circle) and * Thread implementation that is used for the movement of the Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

* Wheel. */ private class Wheel extends Thread { int x = 20, y = 50, x1, y1, radius = CIRCLE_SIZE / 2; double angle = 0, angle1 = 0; Graphics g = box.getGraphics(); @Override public void run() { while (true) { if (x >= (FWIDTH - CIRCLE_SIZE - 20)) x = 20; else x = x + 5; angle = angle1; angle1 = angle1 + 6; if (angle1 == 30) angle1 = 0; for (int i = 0; i < 12; angle = angle + 30, i++) { x1 = (int) ((x + radius) + (radius) * Math.cos(angle * (3.14 / 180))); y1 = (int) ((y + radius) + (radius) * Math.sin(angle * (3.14 / 180))); g.drawLine(x + radius, y + radius, x1, y1); } angle = 0; g.drawOval(x, y, 2 * radius, 2 * radius); g.drawLine(10, y + CIRCLE_SIZE, FWIDTH - 10, y + CIRCLE_SIZE); doNothing(PAUSE); g.clearRect(x, y, 2 * radius + 5, 2 * radius + 5); } } } public void doNothing(int milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException e) { System.out.println("Unexpected interruption"); System.exit(0); } } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

3. /** * BuzzerGame.java * * The program simulates a Buzzer. The time delay between each buzzer, * and the buzzer repetition count values are read from the user * input. Based on the values entered by the user, the buzzer is blown * by displaying "!!!! Buzzer !!!" on the console. * * Created: Feb 8, 2016 * * @author * @version 1 */ import java.util.Scanner; public class BuzzerGame { public static void main(String[] args) { Buzzer bz = new Buzzer(); Scanner keyboard = new Scanner(System.in); System.out.print("Enter time delay for the Buzzer :"); int timeDelay = keyboard.nextInt(); System.out.print("Enter no of repetition : "); int no = keyboard.nextInt(); bz.setBuzzerTime(timeDelay, no); bz.blowBuzzer(); } } /** * * Interface that provides methods to set the buzzer time and blow the * buzzer */ interface MonitorTime { public void setBuzzerTime(int bTimeDelay, int noOfTimes); public void blowBuzzer(); } /** * Buzzer class that uses a thread and MonitorTime interface to start * the buzzer and blow the buzzer at the interval set by the user. * */ Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

class Buzzer extends Thread implements MonitorTime { private int buzzerTime; private int noOfTimes; boolean flag = true; @Override public void run() { int i = 0; while (i < noOfTimes) { System.out.println("!!!! Buzzer !!!"); this.doNothing(buzzerTime); i++; } } public void setBuzzerTime(int bTime, int no) { buzzerTime = bTime; noOfTimes = no; } public void blowBuzzer() { start(); } public void doNothing(int milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException e) { System.out.println("Unexpected interruption"); System.exit(0); } } } 4. import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton; import java.awt.Container; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.event.ActionListener; import java.awt.event.ActionEvent;

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

public class ThreadedFillDemo extends JFrame implements ActionListener { public static final int WIDTH = 300; public static final int HEIGHT = 200; public static final int FILL_WIDTH = 300; public static final int FILL_HEIGHT = 100; public static final int CIRCLE_SIZE = 10; public static final int PAUSE = 100; //milliseconds private JPanel box; public static void main(String[] args) { ThreadedFillDemo gui = new ThreadedFillDemo( ); gui.setVisible(true); } public ThreadedFillDemo( ) { setSize(WIDTH, HEIGHT); setTitle("Threaded Fill Demo"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout( )); box = new JPanel( ); add(box, BorderLayout.CENTER); JPanel buttonPanel = new JPanel( ); buttonPanel.setLayout(new FlowLayout( )); JButton startButton = new JButton("Start"); startButton.addActionListener(this); buttonPanel.add(startButton); add(buttonPanel, BorderLayout.SOUTH); } public void actionPerformed(ActionEvent e) { Packer packerThread = new Packer( ); packerThread.start( ); } private class Packer extends Thread { private int _colorInt = 0; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

public void run( ) { Graphics g = box.getGraphics( ); for (int y = FILL_HEIGHT; y >= 0; y = y - CIRCLE_SIZE) for (int x = FILL_WIDTH; x >= 0; x = x - CIRCLE_SIZE) { g.setColor(this.getNextColor()); g.fillOval(x, y, CIRCLE_SIZE, CIRCLE_SIZE); doNothing(PAUSE); } } private java.awt.Color getNextColor() { if ( _colorInt == 0 ) { _colorInt = 1; return java.awt.Color.RED; } // end of if () else if ( _colorInt == 1 ) { _colorInt = 2; return java.awt.Color.WHITE; } // end of if () else if ( _colorInt == 2) { _colorInt = 0; return java.awt.Color.BLUE; } // end of if () return null; } public void doNothing(int milliseconds) { try { Thread.sleep(milliseconds); } catch(InterruptedException e) { System.out.println("Unexpected interrupt"); System.exit(0); } } } //End Packer inner class } // ThreadedFillDemo

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

5. import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton; import java.awt.Container; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Question5 extends JFrame implements ActionListener { public static final int WIDTH = 300; public static final int HEIGHT = 200; public static final int FILL_WIDTH = 300; public static final int FILL_HEIGHT = 100; public static final int CIRCLE_SIZE = 10; public static final int PAUSE = 100; //milliseconds private JPanel box; public static void main(String[] args) { Question5 gui = new Question5( ); gui.setVisible(true); } public Question5( ) { setSize(WIDTH, HEIGHT); setTitle("Bouncing Ball"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout( )); box = new JPanel( ); add(box, BorderLayout.CENTER); JPanel buttonPanel = new JPanel( ); buttonPanel.setLayout(new FlowLayout( )); JButton startButton = new JButton("Start"); startButton.addActionListener(this); buttonPanel.add(startButton); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

add(buttonPanel, BorderLayout.SOUTH); } public void actionPerformed(ActionEvent e) { Packer packerThread = new Packer( ); packerThread.start(); } private class Packer extends Thread { private int startX = 0; private int startY = 0; private int _dx = 2; private int _dy = 2; public void run( ) { Graphics g = box.getGraphics( ); g.setXORMode(java.awt.Color.GREEN); while ( true ) { g.fillOval(startX, startY, CIRCLE_SIZE, CIRCLE_SIZE); doNothing(PAUSE/2); g.fillOval(startX, startY, CIRCLE_SIZE, CIRCLE_SIZE); doNothing(PAUSE/2); startX += _dx; startY += _dy; if ( startX < 0 ) { startX = 0; _dx = -_dx; } // end of if () if ( startY < 0 ) { startY = 0; _dy = -_dy; } // end of if () if ( startX >= FILL_WIDTH ) { startX = FILL_WIDTH - CIRCLE_SIZE; _dx = -_dx; } // end of if () if ( startY >= FILL_HEIGHT ) { startY = FILL_HEIGHT - CIRCLE_SIZE; _dy = -_dy; } // end of if ()

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

} // end of while () } public void doNothing(int milliseconds) { try { Thread.sleep(milliseconds); } catch(InterruptedException e) { System.out.println("Unexpected interrupt"); System.exit(0); } } } //End Packer inner class } // Question5 6. /** * Question6.java * * This program implements a simple web server that always transmits the same * "web page." It listens on port 8000 so one must navigate to * http://localhost:8000 to access it. * * Created: Fri Mar 23 2007 * * @author Kenrick Mock * @version 1 */ import java.net.ServerSocket; import java.net.Socket; import java.io.DataOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class Question6 { public static void main(String[] args) { try { System.out.println("Waiting for a connection on port 8000."); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

ServerSocket serverSock = new ServerSocket(8000); Socket connectionSock = serverSock.accept(); BufferedReader clientInput = new BufferedReader( new InputStreamReader(connectionSock.getInputStream())); DataOutputStream clientOutput = new DataOutputStream( connectionSock.getOutputStream()); System.out.println("Connection made!"); String body = "<HTML><TITLE>Java Server</TITLE>This web " + "page was sent by our simple <B>Java" + " Server</B></HTML>"; String replyText = "HTTP/1.0 200 OK\n\n" + body; clientOutput.writeBytes(replyText); clientOutput.close(); connectionSock.close(); serverSock.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } } // Question 6 7. /** * Question7.java * * This program implements a simple web server that always transmits the same * "web page." The web page is loaded from a file on disk. * It listens on port 8000 so one must navigate to * http://localhost:8000 to access it, but does use multiple threads to allow * multiple web browsers to access the page. * * Created: Fri Mar 23 2007 * * @author Kenrick Mock * @version 1 */ import java.net.ServerSocket; import java.net.Socket; import java.io.DataOutputStream; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class Question7 { public static void main(String[] args) { // Wait for a connection from the client try { System.out.println("Waiting for a connection on port 8000."); ServerSocket serverSock = new ServerSocket(8000); // This is an infinite loop, the user will have to shut it down // using control-c while (true) { Socket connectionSock = serverSock.accept(); ClientHandler handler = new ClientHandler(connectionSock); Thread theThread = new Thread(handler); theThread.start(); } // Will never get here, but if the above loop is given // an exit condition then we'll go ahead and close the socket //serverSock.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } } // Question 7 /** * ClientHandler.java * * This class opens the file named "index.html" and sends it * to its registered socket. This runs in a separate thread * for greater autonomy. * * Created: Fri Mar 23 2007 * * @author Kenrick Mock * @version 1 */ import java.net.Socket; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

import java.io.DataOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.Scanner; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class ClientHandler implements Runnable { private Socket connectionSock = null; ClientHandler(Socket sock) { connectionSock = sock; } public void run() { // First read the body contents of the index.html file String body = ""; try { Scanner inputStream = new Scanner(new FileInputStream("index.html")); // CHANGE // Read in each line while (inputStream.hasNextLine()) { body += inputStream.nextLine( ); } inputStream.close(); } catch(FileNotFoundException e) { System.out.println("File was not found"); System.out.println("or could not be opened."); } catch(Exception e) { System.out.println("Error reading from file." + e.toString()); } // Send data to the client web browser try { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

BufferedReader clientInput = new BufferedReader( new InputStreamReader(connectionSock.getInputStream())); DataOutputStream clientOutput = new DataOutputStream( connectionSock.getOutputStream()); System.out.println("Connection made!"); String replyText = "HTTP/1.0 200 OK\n\n" + body; clientOutput.writeBytes(replyText); clientOutput.close(); connectionSock.close(); } catch (IOException e) { System.out.println("Error: " + e.toString()); } } } // ClientHandler for Question7

Contents of index.html: <HTML> <TITLE>Java Server</TITLE> This web page was sent by our simple <B>Java Server</B>. </HTML> 8. /** * Question8Server.java * * This program implements a simple chat server. Every client that * connects to the server can broadcast data to all other clients. * The server stores an ArrayList of sockets to perform the broadcast. * * The code is set up so all clients and servers must be run on the same * machine. That is easily changed by setting “localhost” to the desired hostname. * * To test, start the server first, then start multiple clients and type messages * in the client windows. * * Created: Fri Mar 23 2007 * * @author Kenrick Mock Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

* @version 1 */ import java.net.ServerSocket; import java.net.Socket; import java.io.DataOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.ArrayList; public class Question8Server { // Maintain list of all client sockets for broadcast private ArrayList<Socket> socketList; public Question8Server() { socketList = new ArrayList<Socket>(); } private void getConnection() { // Wait for a connection from the client try { System.out.println("Waiting for client connections on port 7654."); ServerSocket serverSock = new ServerSocket(7654); // This is an infinite loop, the user will have to shut it down // using control-c while (true) { Socket connectionSock = serverSock.accept(); // Add this socket to the list socketList.add(connectionSock); // Send to ClientHandler the socket and arraylist of all sockets ClientHandler handler = new ClientHandler(connectionSock, this.socketList); Thread theThread = new Thread(handler); theThread.start(); } // Will never get here, but if the above loop is given // an exit condition then we'll go ahead and close the socket //serverSock.close(); } catch (IOException e) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

System.out.println(e.getMessage()); } } public static void main(String[] args) { Question8Server server = new Question8Server(); server.getConnection(); } } // Question8Server /** * ClientHandler.java * * This class handles communication between the client * and the server. It runs in a separate thread but has a * link to a common list of sockets to handle broadcast. * * Created: Fri Mar 23 2007 * * @author Kenrick Mock * @version 1 */ import java.net.Socket; import java.io.DataOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.Scanner; import java.util.ArrayList; public class ClientHandler implements Runnable { private Socket connectionSock = null; private ArrayList<Socket> socketList; ClientHandler(Socket sock, ArrayList<Socket> socketList) { this.connectionSock = sock; this.socketList = socketList; // Keep reference to master list } public void run() { // Get data from a client and send it to everyone else try Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

{ System.out.println("Connection made with socket " + connectionSock); BufferedReader clientInput = new BufferedReader( new InputStreamReader(connectionSock.getInputStream())); while (true) { // Get data sent from a client String clientText = clientInput.readLine(); if (clientText != null) { System.out.println("Received: " + clientText); // Turn around and output this data // to all other clients except the one // that sent us this information for (Socket s : socketList) { if (s != connectionSock) { DataOutputStream clientOutput = new DataOutputStream( s.getOutputStream()); clientOutput.writeBytes(clientText + "\n"); } } } else { // Connection was lost System.out.println("Closing connection for socket " + connectionSock); // Remove from arraylist socketList.remove(connectionSock); connectionSock.close(); break; } } } catch (Exception e) { System.out.println("Error: " + e.toString()); // Remove from arraylist socketList.remove(connectionSock); } } } // ClientHandler for Question8Server.java

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

/** * Question8Client.java * * This program implements a simple chat client. It connects to the * server (assumed to be localhost on port 7654) and starts two threads: * one for listening for data sent from the server, and another that waits * for the user to type something in that will be sent to the server. * Anything sent to the server is broadcast to all clients. * * Data received is sent to the output screen, so it is possible that as * a user is typing in information a message from the server will be * inserted. This can be disconcerting - a better approach would be to * use a GUI with separate windows or textareas for user input and * messages sent by the server. * * Created: Fri Mar 23 2007 * * @author Kenrick Mock * @version 1 */ import java.net.Socket; import java.io.DataOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.Scanner; public class Question8Client { public static void main(String[] args) { try { String hostname = "localhost"; int port = 7654; System.out.println("Connecting to server on port " + port); Socket connectionSock = new Socket(hostname, port); DataOutputStream serverOutput = new DataOutputStream( connectionSock.getOutputStream()); System.out.println("Connection made."); // Start a thread to listen and display data sent by the server ClientListener listener = new ClientListener(connectionSock); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

Thread theThread = new Thread(listener); theThread.start(); // Read input from the keyboard and send it to everyone else. // The only way to quit is to hit control-c, but a quit command // could easily be added. Scanner keyboard = new Scanner(System.in); while (true) { String data = keyboard.nextLine(); serverOutput.writeBytes(data + "\n"); } } catch (IOException e) { System.out.println(e.getMessage()); } } } // Question8Client /** * ClientListener.java * * This class runs on the client end and just * displays any text received from the server. * * Created: Fri Mar 23 2007 * * @author Kenrick Mock * @version 1 */ import java.net.Socket; import java.io.DataOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.Scanner; import java.util.ArrayList; public class ClientListener implements Runnable { private Socket connectionSock = null; ClientListener(Socket sock) { this.connectionSock = sock; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

} public void run() { // Wait for data from the server. If received, output it. try { BufferedReader serverInput = new BufferedReader( new InputStreamReader(connectionSock.getInputStream())); while (true) { // Get data sent from the server String serverText = serverInput.readLine(); if (serverInput != null) { System.out.println(serverText); } else { // Connection was lost System.out.println("Closing connection for socket " + connectionSock); connectionSock.close(); break; } } } catch (Exception e) { System.out.println("Error: " + e.toString()); } } } // ClientListener for Question8Client

9. /** * Question 9 * * Database extension to Display 19.10 that adds * the tables from Display 19.8. The second * class outputs all matching titles given * an author. * * Created: Sat Mar 22 2009 Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

* * @author Kenrick Mock * @version 1 */ import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.sql.ResultSet; import java.util.Scanner; // This program creates the Database Tables class CreateDB { private static final String driver = "org.apache.derby.jdbc.EmbeddedDriver"; private static final String protocol = "jdbc:derby:"; public static void main(String[] args) { // First load the embedded driver try { Class.forName(driver).newInstance(); System.out.println("Loaded the embedded driver."); } catch (Exception err) // Must catch ClassNotFoundException, InstantiationException, IllegalAccessException { System.err.println("Unable to load the embedded driver."); err.printStackTrace(System.err); System.exit(0); } // Create a new database and connect to it // In the connection string we could also supply a username and password // if applicable by adding "user=username;password=dbuserpwd". // This will create a folder named "BookDatabase" in the // program's directory that contains the database files String dbName = "BookDatabase"; Connection conn = null; try { System.out.println("Connecting to and creating the database..."); conn = DriverManager.getConnection(protocol + dbName + ";create=true"); System.out.println("Database created."); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

// Create a statement object for running SQL statements Statement s = conn.createStatement(); // Create a table named "names" with three fields. // One is for author, which holds a string up to 50 characters. // author_id is a numeric ID number for each author. // url is a varchar, which is a String that holds 80 characters s.execute("CREATE TABLE names" + "(author varchar(50), author_id int, url varchar(80))"); System.out.println("Created 'names' table."); // Add some sample data System.out.println("Inserting authors."); s.execute("INSERT INTO names " + "VALUES ('Adams, Douglas', 1, 'http://www.douglasadams.com')"); s.execute("INSERT INTO names " + "VALUES ('Simmons, Dan', 2, 'http://www.dansimmons.com')"); s.execute("INSERT INTO names " + "VALUES ('Stephenson, Neal', 3, 'http://www.nealstephenson.com')"); System.out.println("Authors inserted."); // Create a table named "titles" with two fields. // One is for title, which holds a string up to 80 characters. // ISBN holds a string up to 20 characters s.execute("CREATE TABLE titles" + "(title varchar(80), isbn varchar(20))"); System.out.println("Created 'titles' table."); // Add some sample data System.out.println("Inserting titles."); s.execute("INSERT INTO titles " + "VALUES ('Snow Crash', '0-553-38095-8')"); s.execute("INSERT INTO titles " + "VALUES ('Endymion', '0-553-57294-6')"); s.execute("INSERT INTO titles " + "VALUES ('Hitchhikers Guide to the Galaxy','0-671-46149-4')"); s.execute("INSERT INTO titles " + "VALUES ('The Rise of Endymion','0-553-57298-9')"); System.out.println("Titles inserted."); // Create a table named "booksauthors" with two fields. // author_id is a numeric ID number for each author. // ISBN holds a string up to 20 characters for the book // written by the author s.execute("CREATE TABLE booksauthors" + Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

"(author_id int, isbn varchar(20))"); System.out.println("Created 'booksauthors' table."); // Add some sample data System.out.println("Inserting titles."); s.execute("INSERT INTO booksauthors " + "VALUES (3, '0-553-38095-8')"); s.execute("INSERT INTO booksauthors " + "VALUES (2, '0-553-57294-6')"); s.execute("INSERT INTO booksauthors " + "VALUES (1,'0-671-46149-4')"); s.execute("INSERT INTO booksauthors " + "VALUES (2,'0-553-57298-9')"); System.out.println("Book authors inserted.");

conn.close(); } catch (SQLException err) { System.err.println("SQL error."); err.printStackTrace(System.err); System.exit(0); } } } // This program connects to the database created by the prior program // and outputs all matching titles given an author. class Question9 { private static final String driver = "org.apache.derby.jdbc.EmbeddedDriver"; private static final String protocol = "jdbc:derby:"; public static void main(String[] args) { try { Class.forName(driver).newInstance(); System.out.println("Loaded the embedded driver."); } catch (Exception err) { System.err.println("Unable to load the embedded driver."); err.printStackTrace(System.err); System.exit(0); } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

String dbName = "BookDatabase"; Connection conn = null; try { System.out.println("Connecting to the database..."); conn = DriverManager.getConnection(protocol + dbName); System.out.println("Connected."); Scanner kbd = new Scanner(System.in); System.out.println("Enter an author (Lastname, Firstname)."); String author = kbd.nextLine(); Statement s = conn.createStatement(); ResultSet rs = null; System.out.println("Matching titles:"); rs = s.executeQuery("SELECT Titles.title FROM names, titles, booksauthors WHERE names.author ='" + author + "' AND names.author_id = booksauthors.author_id AND titles.isbn = booksauthors.isbn"); while( rs.next() ) { System.out.println(rs.getString("title")); } rs.close(); conn.close(); } catch (SQLException err) { System.err.println("SQL error."); err.printStackTrace(System.err); System.exit(0); } } } // Question 9

10. /** * Question 10 *JSP and HTML form to convert feet to inches * Created: Feb 8, 2016 * * @author * @version 1 Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

*/ File: Input.html <HTML> <HEAD> <!-convert feet to inches --> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <form method="POST" action="conversion.jsp"> Height in feet : <input type="text" name="height"> <br/> <input type="submit" value="Convert to Inches"> </form> </body> </html> Conversion.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <% double height = Double.parseDouble(request.getParameter("height")); double heightInInches = height*12; out.println("\n Height in Inches : "+heightInInches); %> </body> </html>

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

11. /** * Question 11 * * JSP and HTML form to randomly generate baby names. * * Created: Sat Mar 22 2009 * * @author Kenrick Mock * @version 1 */ File: NameGen.html <html> <head> <title> Baby Name Generator </title> </head> <body> <form action="GenerateName.jsp" method=post> Enter your last name: <input type=text name=lastname> <input type=submit value="Submit"> </form> </body> </html>

File: GenerateName.jsp <%@ page import="java.io.*, java.util.Scanner" %> <html> <head> <title> Your baby's name </title> </head> <body> <% String boyName = "", girlName = "";

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

Scanner inputStream = null; int choice = (int) (Math.random() * 1000); try { inputStream = new Scanner(new FileInputStream("C:\\Sun\\SDK\\domains\\domain1\\docroot\\boynames.txt")); for (int i=0; i<= choice; i++) { boyName = inputStream.next(); inputStream.nextInt(); // read Number of namings } inputStream.close(); } catch (Exception e) { out.println ("Error: " + e); return; } choice = (int) (Math.random() * 1000); try { inputStream = new Scanner(new FileInputStream("C:\\Sun\\SDK\\domains\\domain1\\docroot\\girlnames.txt")); for (int i=0; i<= choice; i++) { girlName = inputStream.next(); inputStream.nextInt(); } inputStream.close(); } catch (Exception e) { out.println ("Error: " + e); return; } boyName += " " + request.getParameter("lastname"); girlName += " " + request.getParameter("lastname"); out.println("If your baby is a boy, consider the name " + boyName); out.println("<br/>"); out.println("If your baby is a girl, consider the name " + girlName); %> </body> </html> <!—End of Question 11 --> Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

12. /** * Question 12 * * Programming Project 19.9 (book database) * as a HTML and JSP program. * * Created: Sat Mar 22 2009 * * @author Kenrick Mock * @version 1 */ File: CreateDB2.jsp This program should be run first to create the database. <%@ page import="java.sql.*" %> <html> <title>Create New Database</title> <body> <H2>Create New Database</h2> <p> This program creates a new Derby database named 'BookDatabase' and puts sample data into the 'person', 'titles', and 'booksauthors' tables. </p> <% String driver = "org.apache.derby.jdbc.EmbeddedDriver"; String protocol = "jdbc:derby:"; try { Class.forName(driver).newInstance(); out.println("Loaded the embedded driver.<br>"); } catch (Exception err) { out.println("Unable to load the embedded driver.</body></html>"); return; } String dbName = "BookDatabase"; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

Connection conn = null; try { out.println("Connecting to and creating the database...<br />"); conn = DriverManager.getConnection(protocol + dbName + ";create=true"); out.println("Connected.<br />"); Statement s = conn.createStatement(); s.execute("CREATE TABLE names" + "(author varchar(50), author_id int, url varchar(80))"); out.println("Created 'names' table.<br />"); out.println("Inserting authors.<br />"); s.execute("INSERT INTO names " + "VALUES ('Adams, Douglas', 1, 'http://www.douglasadams.com')"); s.execute("INSERT INTO names " + "VALUES ('Simmons, Dan', 2, 'http://www.dansimmons.com')"); s.execute("INSERT INTO names " + "VALUES ('Stephenson, Neal', 3, 'http://www.nealstephenson.com')"); out.println("Authors inserted.<br />"); // Create title table s.execute("CREATE TABLE titles" + "(title varchar(80), isbn varchar(20))"); out.println("Created 'titles' table."); out.println("Inserting titles."); s.execute("INSERT INTO titles " + "VALUES ('Snow Crash', '0-553-38095-8')"); s.execute("INSERT INTO titles " + "VALUES ('Endymion', '0-553-57294-6')"); s.execute("INSERT INTO titles " + "VALUES ('Hitchhikers Guide to the Galaxy','0-671-46149-4')"); s.execute("INSERT INTO titles " + "VALUES ('The Rise of Endymion','0-553-57298-9')"); out.println("Titles inserted."); // Create booksauthors table s.execute("CREATE TABLE booksauthors" + "(author_id int, isbn varchar(20))"); out.println("Created 'booksauthors' table."); out.println("Inserting titles."); s.execute("INSERT INTO booksauthors " + "VALUES (3, '0-553-38095-8')"); s.execute("INSERT INTO booksauthors " + "VALUES (2, '0-553-57294-6')"); s.execute("INSERT INTO booksauthors " + Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

"VALUES (1,'0-671-46149-4')"); s.execute("INSERT INTO booksauthors " + "VALUES (2,'0-553-57298-9')"); out.println("Book authors inserted."); conn.close(); } catch (Exception err) { out.println("SQL error.<br />" + err.toString()); } %> </body> </html>

File: EnterAuthor.html. <html> <head> <title> Book Author Database </title> </head> <body> <form action="ShowTitles.jsp" method=post> Enter author (Lastname, Firstname): <input type=text name=author> <input type=submit value="Submit"> </form> </body> </html>

File: ShowTitles.jsp <%@ page import="java.sql.*" %> <HTML> <BODY> Matching titles:<br> <% String framework = "embedded"; String driver = "org.apache.derby.jdbc.EmbeddedDriver"; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

String protocol = "jdbc:derby:"; try { Class.forName(driver).newInstance(); out.println("Loaded the embedded driver.<br>"); } catch (Exception err) { out.println("Unable to load the embedded driver."); System.exit(0); } String dbName = "BookDatabase"; Connection conn = null; try { out.println("Connecting to the database...<br/>"); conn = DriverManager.getConnection(protocol + dbName); out.println("Connected.<br/>"); String author = request.getParameter("author"); Statement s = conn.createStatement(); ResultSet rs = null; out.println("Matching titles:<br/>"); rs = s.executeQuery("SELECT Titles.title FROM names, titles, booksauthors WHERE names.author ='" + author + "' AND names.author_id = booksauthors.author_id AND titles.isbn = booksauthors.isbn"); out.println("<UL>"); while( rs.next() ) { out.println("<LI>" + rs.getString("title") + "</LI>"); } out.println("</UL>"); rs.close(); conn.close(); } catch (Exception err) { out.println("SQL error."); System.exit(0); } %> <!—End of Question 12 --></HTML>

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

/** * Question 13 * * Demonstration of race conditions to a bank account. * * Created: Fri Apr 27 2012 * * @author Kenrick Mock * @version 1 */ public class BankAccount { private int balance; public BankAccount() { balance = 0; } // Uncomment "synchronized" in the following methods // to avoid the race condition public /* synchronized */ void deposit(int amount) { balance += amount; } public /* synchronized */ void withdraw(int amount) { balance -= amount; } public int getBalance() { return balance; } } public class RaceConditionTest extends Thread { private BankAccount bank; private int id; public RaceConditionTest(BankAccount bank, int id) { this.bank = bank; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

this.id = id; } public void run() { if (id % 2 == 0) bank.deposit(1); else bank.withdraw(1); } public static void main(String[] args) { int i; BankAccount masterAccount = new BankAccount(); RaceConditionTest[] threads = new RaceConditionTest[30000]; for (i = 0; i < threads.length; i++) { threads[i] = new RaceConditionTest(masterAccount, i); threads[i].start(); } // Wait for the threads to finish for (i = 0; i < threads.length; i++) { try { threads[i].join(); } catch (InterruptedException e) { System.out.println(e.getMessage()); } } System.out.println("The value in the account is " + masterAccount.getBalance()); } } // Question 13 14. /** * Question 14 * * Link JavaFX with the URL class and lambda expression * to handle the action listener Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

* * Created: Fri May 22 2015 * * @author Kenrick Mock * @version 1 */ import java.net.URL; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.TextArea; import javafx.scene.control.Button; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class Question14 extends Application { public void start(Stage primaryStage) { TextArea txt = new TextArea(); Button btn = new Button(); txt.setText(""); btn.setText("Get HTML"); // Lambda Expression to set the action // for the button click btn.setOnAction(e -> { // Read the URL into the string html String html = ""; try { URL website = new URL("http://www.pearsonhighered.com/savitch"); Scanner inputStream = new Scanner(new InputStreamReader( website.openStream())); while (inputStream.hasNextLine()) { String s = inputStream.nextLine(); html = html + s + "\n"; } inputStream.close(); txt.setText(html); // Put HTML into the textarea } Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 19, Instructor’s Manual

catch (Exception ex) { System.out.println(ex.toString()); } }); // Use a vertical layout VBox root = new VBox(); root.getChildren().add(txt); root.getChildren().add(btn); Scene scene = new Scene(root, 500, 300); primaryStage.setTitle("JavaFX URL and Lambda Exercise"); primaryStage.setScene(scene); primaryStage.show(); } }

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

Chapter 20

Applets Key Terms application applet HTML hypertext links home page <h1> <h2> <hr> line breaks <br> <center> uppercase lowercase file names <html> <head> <title> <body> comment hyperlink JApplet init applet viewer ImageIcon setIcon applet tag sizing an applet applet viewer

Brief Outline 20.1 A Brief Introduction to HTML HTML Formatting Commands Outline of an HTML document Hyperlinks Inserting a Picture 20.2 Programming Applets Defining an Applet Running an Applet Menus in a JApplet Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

Adding Icons to an Applet 20.3 Applets in HTML Documents Inserting an Applet in an HTML Document Running an Applet over the Internet Applets and Security

Teaching Suggestions This chapter is not included with the printed textbook. It is included as a PDF file online and on the CD attached to the book. This chapter discusses Applets as another type of Java program that you can create. Applets are Java programs that can be embedded inside of web pages and viewed over the Internet. This chapter requires the material of Chapter 17, but does not need to follow it. The sections on HTML may or may not be appropriate for the class. You can use the applet viewer that comes with the SDK and you do not need to create an entire web page to view your programs. You will still need an HTML file to view the program however. The differences that one may encounter when creating an Applet as opposed to an application program are discussed in section 2. However, many of these difficulties are easily overcome and may not be viewed by some as difficulties, just differences in how Applets behave. The last chapter discusses how to actually run an Applet over the Internet. This section may be entirely skipped if instructors do not wish to go into HTML in great detail. The issue of security with Applets is addressed, however, and probably should be discussed. Applets do not have permission to directly just start manipulating files on a system, so there are sometimes special permission files that are needed when creating an applet as a program.

Key Points URL. The name of an HTML document on the web. The URL includes the protocol that is used to transfer the information as well as its location on the web. Inserting a Hyperlink. A hyperlink is the way one HTML document can be connected to another and allows the user to navigate between the pages. There is a special tag that is used to designate a hyperlink in an HTML document. Inserting a Picture in an HTML Document. You can insert images into your HTML documents using the <image> tag. The JApplet Class. This class is normally used to create an applet. You do not use a JFrame when creating an applet.

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

Icons. Icons are typically pictures that are small in size and can be used in Containers. They are displayed as other graphical components and can be used with an action listener or in combination with other components as an interactive part of the program. Applet Tag. When trying to get an Applet into an HTML document a special <applet> tag is used.

Tips Comments. Comments are important when coding HTML too. They have a special comment tag that is used to indicate that this text should be ignored by the web browser when displaying the page. Other Languages for Authoring Web Pages. There are many programs that are available to help you edit HTML and create new HTML pages. It is advisable that if you plan to create many HTML pages that you learn how to use at least one of these tools. Converting a Swing Application to an Applet. This tip gives a quick list of steps for easily converting an application into an applet.

Pitfalls Not Using Your Browser’s Refresh Command. When developing a web page it is important to refresh your page in the browser to see the changes. Web browsers often keep a copy of recently viewed web pages in easy access and do not go back to the web each time the page is called for. If changes have been made, they will not be reflected unless you refresh the page. Using an Old Web Browser. If you have an old browser on your system it may not support the running of applets. This problem can be solved by simply updating your version of your browser. If that is not possible, you can use applet viewer to view your applets.

Programming Projects Answers 1. /** * Question1.java * * This applet cycles through three images (hard coded) displayed * in a JLabel. * * Created: Sat Apr 16 2005 * * @author Kenrick Mock * @version 1 Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

*/ import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.ImageIcon; import java.awt.FlowLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; /** * ImageCycleApplet loads three images into an ImageIcon array and * attaches an action listener to a JButton to cycle to the next image. */ public class Question1 extends JApplet implements ActionListener { public static final int NUMIMAGES = 3; private JLabel imageLabel; // Label used to display images private JButton btnCycleImage; // Button to cycle through images // Array to hold three images private ImageIcon[] imgArray = new ImageIcon[NUMIMAGES]; private int currentImage = 0; // Index into array of current image public void init() { setLayout(new FlowLayout()); // Load three images imgArray[0] = new ImageIcon("image1.gif"); imgArray[1] = new ImageIcon("image2.gif"); imgArray[2] = new ImageIcon("image3.gif"); // Attach first image currentImage = 0; imageLabel = new JLabel(""); imageLabel.setIcon(imgArray[currentImage]); add(imageLabel); // Add button btnCycleImage = new JButton("Press for Next Image"); btnCycleImage.addActionListener(this); add(btnCycleImage); } public void actionPerformed(ActionEvent e) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

// Button click is the only event that invokes this method. // Display the next image. currentImage++; if (currentImage >= NUMIMAGES) { currentImage=0; } // Display image imageLabel.setIcon(imgArray[currentImage]); } } // Question1

2. /** * TicTacToeApplet.java * * This applet uses Swing to play a simple game of Tic Tac Toe * (noughts and crosses). It uses a GridLayout of JButton's to * play the game. Each JButton has its own ButtonListener class * that updates an internal 2D game board and checks to see if the * game is over. * Applets do not have security permissions to exit, so when the * game is over a flag is set to indicate that no further play * should occur. * * Created: Sat Apr 16 2005 * * @author Kenrick Mock * @version 1 */ import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JLabel; import java.awt.GridLayout; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; /** * TicTacToe GUI to play the game */ public class TicTacToeApplet extends JApplet Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

{ public static final int WIDTH = 300; public static final int HEIGHT = 300; // Dimensions of the game board, must be square public static final int BOARDSIZE = 3; // Current player's turn, either X or O private char whoseturn; // 2D array to store pieces placed on the board, ' ', 'X', 'O' private char[][] board; // Indicates if the game is over or not, if over do nothing on button click private boolean gameOver; // Label to display messages to the players private JLabel messageLabel; /** * This class is the ActionListener for one of the button clicks. * The constructor takes the X and Y coordinate for the entry in the game board * that corresponds to where this button is located. */ private class ButtonListener implements ActionListener { private int x,y; // Coordinate on the game board for this button JButton but; // Reference to the JButton object for this ActionListener /** * The constructor stores references to the caller and the game object. * @param x X coordinate on the game board for this button * @param y Y coordinate on the game board for this button * @param but The actual button object so we can change the text * @param game The game object so we can check for a win and update the board */ ButtonListener(int x, int y, JButton but) { this.x = x; this.y = y; this.but = but; } /** * The actionPerformed event is invoked when a button is clicked. * Check to see if the cell that corresponds to this button is clear; if not it is an * invalid move. If clear, put a piece there, update the button text with the * piece label, update the game board, and see if someone won. */ public void actionPerformed(ActionEvent e) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

{ // Check to see if the game is over if (TicTacToeApplet.this.gameIsOver()) { messageLabel.setText("The game is over. Reload to play again."); return; } // Check to see if the cell is occupied if (TicTacToeApplet.this.getBoard(x,y)!=' ') { messageLabel.setText("That location is occupied. Try again."); } // Otherwise put a piece there else { String whomoved = new Character(TicTacToeApplet.this.getTurn()).toString(); but.setText(whomoved); TicTacToeApplet.this.setBoard(x,y, TicTacToeApplet.this.getTurn()); TicTacToeApplet.this.playerMoved(); TicTacToeApplet.this.checkGameOver(); } } } /** * The init method creates the JFrame and adds 9 JButtons to the grid layout. * A 2D board array is also set up with the pieces that are placed; initially it is blank. * The action listener is created using the ButtonListener class described above. */ public void init() { // Label to store messages messageLabel = new JLabel("Welcome to Tic Tac Toe"); setLayout(new BorderLayout()); // Main layout is a border layout add(messageLabel, BorderLayout.NORTH); // Messages go on top // Make a panel to store the game board buttons JPanel buttonPanel = new JPanel(); // Organized using a grid layout add(buttonPanel, BorderLayout.CENTER); buttonPanel.setLayout(new GridLayout(BOARDSIZE, BOARDSIZE)); // Create game board board = new char[BOARDSIZE][BOARDSIZE]; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

gameOver = false; // Create buttons for each board and link each button back to a coordinate for (int y=0; y<BOARDSIZE; y++) { for (int x=0; x<BOARDSIZE; x++) { board[x][y]=' '; // Initially no piece on each board location JButton but = new JButton(" "); but.addActionListener(new ButtonListener(x,y,but)); buttonPanel.add(but); } } whoseturn = 'X'; // X goes first; } /** * @return char 'X' or 'Y' depending on whoseturn it is. */ public char getTurn() { return whoseturn; } /** * @param x The x coordinate of the board location we want to set * @param y The y coordinate of the board location we want to set * @param newValue the char to store at board[x][y] */ public void setBoard(int x, int y, char newValue) { board[x][y] = newValue; } /** * @return char The character (' ', 'X', or 'Y') stored at board[x][y] */ public char getBoard(int x, int y) { return (board[x][y]); } /** * Notifies the game that a player moved, so the current player should be toggled * to the other player. */ Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

public void playerMoved() { if (whoseturn=='X') whoseturn='O'; else whoseturn = 'X'; } /** * Accessor if game over */ public boolean gameIsOver() { return gameOver; } /** * Checks if a player won the game or if there was a draw. In either case the * program exits after displaying a message. If the game is not over then the * method exits. */ public void checkGameOver() { boolean win; char first; // Check all rows across. There is a winner if all entries are the same // character, but not ' ' for (int y=0; y<BOARDSIZE; y++) { win = true; first = board[0][y]; if (first != ' ') { for (int x=1; x<BOARDSIZE; x++) { if (board[x][y]!=first) win=false; } if (win) { messageLabel.setText(first + " is the winner!"); gameOver = true; } } } // Check all rows down. There is a winner if all entries are the same // character, but not ' ' for (int x=0; x<BOARDSIZE; x++) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

win = true; first = board[x][0]; if (first != ' ') { for (int y=1; y<BOARDSIZE; y++) { if (board[x][y]!=first) win=false; } if (win) { messageLabel.setText(first + " is the winner!"); gameOver = true; } } } // Check diagonal top left to bottom right first = board[0][0]; win = true; if (first != ' ') { for (int x=1; x<BOARDSIZE; x++) { if (board[x][x]!=first) win=false; } if (win) { messageLabel.setText(first + " is the winner!"); gameOver = true; } } // Check diagonal bottom left to top right first = board[0][BOARDSIZE-1]; win = true; if (first != ' ') { for (int x=1; x<BOARDSIZE; x++) { if (board[x][BOARDSIZE-1-x]!=first) win=false; } if (win) { messageLabel.setText(first + " is the winner!"); gameOver = true; } } // Check if board is full. If so, there is a draw. if (!gameOver) { Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

int numpieces = 0; for (int x=0; x<BOARDSIZE; x++) for (int y=0; y<BOARDSIZE; y++) { if (board[x][y]!=' ') numpieces++; } if (numpieces==BOARDSIZE*BOARDSIZE) { messageLabel.setText("The game is a draw!"); gameOver = true; } } } } // TicTacToeApplet

3. import javax.swing.JApplet; import javax.swing.JTextField; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JButton; import java.awt.Container; import java.awt.GridLayout; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Color; import java.awt.event.ActionListener; import java.awt.event.ActionEvent;

public class TextFieldDemo extends JApplet implements ActionListener { public static final int WIDTH = 400; public static final int HEIGHT = 200; public static final int NUMBER_OF_CHAR = 30; private JTextField name; public void init( ) { setLayout(new GridLayout(2, 1)); JPanel namePanel = new JPanel( ); namePanel.setLayout(new BorderLayout( )); Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

namePanel.setBackground(Color.WHITE); name = new JTextField(NUMBER_OF_CHAR); namePanel.add(name, BorderLayout.SOUTH); JLabel nameLabel = new JLabel("Enter your name here:"); namePanel.add(nameLabel, BorderLayout.CENTER); add(namePanel); JPanel buttonPanel = new JPanel( ); buttonPanel.setLayout(new FlowLayout( )); buttonPanel.setBackground(Color.PINK); JButton actionButton = new JButton("Click me"); actionButton.addActionListener(this); buttonPanel.add(actionButton); JButton clearButton = new JButton("Clear"); clearButton.addActionListener(this); buttonPanel.add(clearButton); add(buttonPanel); }

public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand( ); if (actionCommand.equals("Click me")) name.setText("Hello " + name.getText( )); else if (actionCommand.equals("Clear")) name.setText(""); else name.setText("Unexpected error."); } } <html> <head> <title>Question 3 Chapter 17</title> </head> <body> <h1> Here is the program for Question 3 </h1> Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

<p></p> <applet code="TextFieldDemo.class" width=300 height=200></applet> </body> </html>

4. /** * Converter.java * * * Created: Thu Jan 29 21:02:51 2004 * * @author Adrienne Decker * @version */ import javax.swing.JApplet; import javax.swing.JTextField; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JLabel; import java.awt.Container; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.Color; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Converter extends JApplet { private JTextField _input, _result; private JButton _convert, _clear; public void init (){ Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); contentPane.add(this.createTextFields(), BorderLayout.NORTH); contentPane.add(this.createButtons(), BorderLayout.CENTER); } private JPanel createTextFields() Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

{ JPanel text = new JPanel(); text.add(new JLabel("Input a number in base ten:")); _input = new JTextField(10); text.add(_input); text.add(new JLabel("Your number in base two:")); _result = new JTextField(10); text.add(_result); return text; } private JPanel createButtons() { JPanel buttons = new JPanel(); _convert = new JButton("Convert"); _convert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Converter.this.convertNumber(); } }); buttons.add(_convert); _clear = new JButton("Clear"); _clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Converter.this.clearTextFields(); } }); buttons.add(_clear); return buttons; } private void convertNumber() { int input = Integer.parseInt(_input.getText()); _result.setText(baseTwo(input)); } private String baseTwo(int input) Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

{ if ( input == 0 ) { return "" + 0; } // end of if () if ( input < 0 ) { return "error"; } // end of if () String result = ""; while ( input != 0 ) { result = "" + input % 2 + result; input /= 2; } // end of while () return result; } private void clearTextFields() { _input.setText(""); _result.setText(""); } } // Converter

3. /** * Question3.java * * * Created: Thu Jan 29 21:02:51 2004 * * @author Adrienne Decker * @version */ import javax.swing.JApplet; import javax.swing.JTextField; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JLabel; import java.awt.Container; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.Color; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Question3 extends JApplet { private JTextField _input, _result; private JButton _convert, _clear; public void init(){ Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); contentPane.add(this.createTextFields(), BorderLayout.NORTH); contentPane.add(this.createButtons(), BorderLayout.CENTER); } private JPanel createTextFields() { JPanel text = new JPanel(); text.add(new JLabel("Input a number in base two:")); _input = new JTextField(10); text.add(_input); text.add(new JLabel("Your number in base ten:")); _result = new JTextField(10); text.add(_result); return text; } private JPanel createButtons() { JPanel buttons = new JPanel(); _convert = new JButton("Convert"); _convert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Question3.this.convertNumber(); } }); buttons.add(_convert); _clear = new JButton("Clear"); _clear.addActionListener(new ActionListener() Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

{ public void actionPerformed(ActionEvent e) { Question3.this.clearTextFields(); } }); buttons.add(_clear); return buttons; } private void convertNumber() { String baseTwo = _input.getText(); _result.setText("" + baseTen(baseTwo)); } private int baseTen(String input) { if ( input.equals("0") ) { return 0; } // end of if () int result = 0; for ( int i = input.length() - 1, powersOfTwo = 1; i >= 0; i--, powersOfTwo *= 2) { char digit = input.charAt(i); if ( digit == '1' ) { result += powersOfTwo; } // end of if () } // end of for () return result; } private void clearTextFields() { _input.setText(""); _result.setText(""); } } // Question3

4. Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

/** * Question4Converter.java * * Created: Thu Jan 29 21:02:51 2004 * Modified: Sat Apr 16 2005, Kenrick Mock * * @author Adrienne Decker * @version 2 */ import javax.swing.JApplet; import javax.swing.JTextField; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JLabel; import java.awt.Container; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.Color; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Question4Converter extends JApplet { private JTextField _input, _result; private JButton _convert, _clear; public void init (){ setLayout(new BorderLayout()); add(this.createTextFields(), BorderLayout.NORTH); add(this.createButtons(), BorderLayout.CENTER); } private JPanel createTextFields() { JPanel text = new JPanel(); text.add(new JLabel("Input a number in base ten:")); _input = new JTextField(10); text.add(_input); text.add(new JLabel("Your number in base two:")); _result = new JTextField(10); text.add(_result);

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

return text; } private JPanel createButtons() { JPanel buttons = new JPanel(); _convert = new JButton("Convert"); _convert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Question4Converter.this.convertNumber(); } }); buttons.add(_convert); _clear = new JButton("Clear"); _clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Question4Converter.this.clearTextFields(); } }); buttons.add(_clear); return buttons; } private void convertNumber() { int input = Integer.parseInt(_input.getText()); _result.setText(baseTwo(input)); } private String baseTwo(int input) { if ( input == 0 ) { return "" + 0; } // end of if () if ( input < 0 ) { return "error"; } // end of if () String result = ""; Copyright © 2016 Pearson Education Ltd. All rights reserved.


Savitch, Absolute Java 6/e, Global Edition: Chapter 20, Instructor’s Manual

while ( input != 0 ) { result = "" + input % 2 + result; input /= 2; } // end of while () return result; } private void clearTextFields() { _input.setText(""); _result.setText(""); } } // Question4Converter

Copyright © 2016 Pearson Education Ltd. All rights reserved.


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.