Java Foundations Introduction to Program Design and Data Structures, 5th edition John Lewis Solution

Page 1

Java Foundations Introduction to Program Design and Data Structures, 5th edition BY John Lewis

Email: Richard@qwconsultancy.com


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 1

Chapter 1 Exercise Solutions EX 1.1.

Give examples of the two types of Java comments and explain the differences between them. One kind of comment begins with a double slash (//) and continues to the end of the line: // This is a single line comment. A second kind of comment begins following an initiating slash-asterisk (/*) and terminates immediately preceding a terminating asterisk-slash (*/). The second type of comment can span multiple lines: /* This is a comment that spans multiple lines. */

EX 1.2.

Which of the following are not valid Java identifiers? Why?

a. Factorial Valid b. anExtremelyLongIdentifierIfYouAskMe Valid c. 2ndLevel Invalid because it begins with a digit d. level2 Valid e. MAX_SIZE Valid f.

highest$ Valid

g. hook&ladder Invalid because it contains an ampersand (&) EX 1.3.

Why are the following valid Java identifiers not considered good identifiers?

a. q The identifier q is a meaningless name. b. totVal The identifier totalValue would be more meaningful than the abbreviation. c. theNextValueInTheList Unnecessarily lengthy; nextValue would serve as well. EX 1.4.

Java is case sensitive. What does that mean? Uppercase characters are considered to be distinct from lowercase letters. Therefore the identifier HELLO is distinct from Hello which is distinct from hello.


Java Foundations, 5th Edtion EX 1.5.

Exercise Solutions, Ch. 1

What do we mean when we say that the English language is ambiguous? Give two examples of English ambiguity (other than the example used in this chapter) and explain the ambiguity. Why is ambiguity a problem for programming languages? Something is ambiguous if it has two or more possible meanings. For example, the statement, “Mary is the nicest teaching assistant who has helped me all day long” might mean 1) of all the teaching assistants who have helped me today, Mary is the nicest, or 2) of those teaching assistants who have helped me for an entire day, Mary is the nicest. As another example, the statement, “Bananas help those who help themselves” might mean 1) bananas are good for those who attend to their own welfare or 2) bananas are good for those who eat as many bananas as they please. If a programming language statement could be interpreted in two or more ways, it would be impossible to predict with certainty how it would be interpreted and what result would be produced.

EX 1.6.

Categorize each of the following situations as a compile-time error, run-time error, or logical error.

a. multiplying two numbers when you meant to add them A logical error b. dividing by zero A run-time error c. forgetting a semicolon at the end of a programming statement A compile-time error d. spelling a word wrong in the output A logical error e. producing inaccurate results A logical error f.

typing a { when you should have typed ( A compile-time error


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 2

Chapter 2 Exercise Solutions EX 2.1.

Explain the following programming statement in terms of objects and the services they provide. System.out.println("I gotta be me!"); The System.out object has a println method which accepts a character string as a parameter. The service the println method provides is to display the string on the monitor.

EX 2.2.

What output is produced by the following code fragment? Explain. System.out.print("Here we go!"); System.out.println("12345"); System.out.print("Test this if you are not sure."); System.out.print("Another."); System.out.println(); System.out.println("All done."); The output produced is: Here we go!12345 Test this if you are not sure.Another. All done. After printing its data, the println method moves to the next line of output, whereas the print method does not. A println statement with no data has the effect of moving down to the next line.

EX 2.3.

What is wrong with the following program statement? How can it be fixed? System.out.println("To be or not to be, that is the question."); The string to be printed is not all on one line. The problem can be fixed by splitting the long string into two and using the string concatenation operator (+) to reconstruct it, or by using a print statement for part of the string and a println statement for the remainder of the string.

EX 2.4.

What output is produced by the following statement? Explain. System.out.println("50 plus 25 is " + 50 + 25); The output produced is: 50 plus 25 is 5025 First the string “50 plus 25 is ” is concatenated with the integer 50; since one of the operands is a string, the result is a string. Then the string “50 plus 25 is 50” is concatenated with the integer 25, producing the final result.

EX 2.5.

What is the output produced by the following statement? Explain. System.out.println("He thrusts his fists\n\tagainst" + " the post\nand still insists\n\the sees the \"ghost\""); The output produced is: He thrusts his fists against the post and still insists


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 2

he sees the "ghost" Escape characters are used to go to the beginning of new lines (\n), to tab (\t), and to print quotation marks (\"). EX 2.6.

What value is contained in the integer variable size after the following statements are executed? size = 18; size = size + 12; size = size * 2; size = size / 4; The final value stored in size is 15.

EX 2.7.

What value is contained in the floating point variable depth after the following statements are executed? depth = 2.4; depth = 20 – depth * 4; depth = depth / 5; The final value stored in depth is 2.08.

EX 2.8.

What value is contained in the integer variable length after the following statements are executed? length = 5; length *= 2; length *= length; length /= 100; The final value stored in length is 1.

EX 2.9.

Write four different program statements that increment the value of an integer variable total. total = total + 1; total += 1; total++; ++total;

EX 2.10. Given the following declarations, what result is stored in each of the listed assignment statements? int iResult, num1 = 25, num2 = 40, num3 = 17, num4 = 5; double fResult, val1 = 17.0, val2 = 12.78; a. iResult = num1 / num4; iResult is assigned 5 b. fResult = num1 / num4; fResult is assigned 5.0 c. iResult = num3 / num4; iResult is assigned 3


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 2

d. fResult = num3 / num4; fResult is assigned 3.0 e. fResult = val1 / num4; fResult is assigned 3.4 f.

fResult = val1 / val2; fResult is assigned 1.3302034...

g. iResult = num1 / num2; iResult is assigned 0 h. fResult = (double) num1 / num2; fResult is assigned 0.625 i.

fResult = num1 / (double) num2; fResult is assigned 0.625

j.

fResult = (double) (num1 / num2); fResult is assigned 0.0

k. iResult = (int) (val1 / num4); iResult is assigned 3 l.

fResult = (int) (val1 / num4); fResult is assigned 3.0

m. fResult = (int) ((double) num1 / num2); fResult is assigned 0.0 n. iResult = num3 % num4; iResult is assigned 2 o. iResult = num 2 % num3; iResult is assigned 6 p. iResult = num3 % num2; iResult is assigned 17 q. iResult = num2 % num4; iResult is assigned 0 EX 2.11. For each of the following expressions, indicate the order in which the operators will be evaluated by writing a number beneath each operator. a. a – b – c – d 1 2 3 b. a – b + c – d 1 2 3 c. a + b / c / d 3 1 2 d. a + b / c * d


Java Foundations, 5th Edtion 3 1 2 e. a / b * c * d 1 2 3 f.

a%b/c*d 1 2 3

g. a % b % c % d 1 2 3 h. a – (b – c) – d 2 i.

3

(a – (b – c)) – d 2

j.

1

1

3

a – ((b – c) – d) 3

1

2

k. a % (b % c) * d * e 2 l.

1

3 4

a + (b – c) * d – e 3

1

2 4

m. (a + b) * c + d * e 1

2 4 3

n. (a + b) * (c / d) % e 1

3

2

4

Exercise Solutions, Ch. 2


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 3

Chapter 3 Exercise Solutions EX 3.1.

Write a statement that prints the number of characters in a String object called overview. System.out.println(overview.length());

EX 3.2.

Write a statement that prints the eighth character of a String object called introduction. System.out.println(introduction.charAt(7));

EX 3.3.

Write a declaration for a String variable called change and initialize it to the characters stored in another String object called original with all 'e' characters changed to 'j'. String change = original.replace('e', 'j');

EX 3.4.

What output is produced by the following code fragment? String m1, m2, m3; m1 = "Quest for the Holy Grail"; m2 = m1.toLowerCase(); m3 = m1 + " " + m2; System.out.println(m3.replace('h', 'z')); The output produced is: Quest for tze Holy Grail quest for tze zoly grail The original string is concatenated with a lowercase version of itself, then all lowercase ‘h’ characters are replaced with ‘z’.

EX 3.5.

What is the effect of the following import statement? import java.awt.*; This statement allows the program in which it is written to access all classes (because of the wildcard *) in the package java.awt without any further reference to the package name.

EX 3.6.

Assuming that a Random object has been created called generator, what is the range of the result of each of the following expressions?

a. generator.nextInt(20) 0 to 19, inclusive b. generator.nextInt(8) + 1 1 to 8, incluslive c. generator.nextInt(45) + 10 10 to 54, inclusive d. generator.nextInt(100) – 50 -50 to 49, inclusive


Java Foundations, 5th Edtion EX 3.7.

Exercise Solutions, Ch. 3

Write code to declare and instantiate an object of the Random class (call the object reference variable rand). Then write a list of expressions using the nextInt method that generate random numbers in the following specified ranges, including the endpoints. Use the version of the nextInt method that accepts a single integer parameter. Random rand = new Random();

a. 0 to 10 rand.nextInt(11) b. 0 to 500 rand.nextInt(501) c. 1 to 10 rand.nextInt(10) + 1 d. 1 to 500 rand.nextInt(500) + 1 e. 25 to 50 rand.nextInt(26) + 25 f.

EX 3.8.

–10 to 15 rand.nextInt(26) – 10 Write an assignment statement that computes the square root of the sum of num1 and num2 and assigns the result to num3. num3 = Math.sqrt(num1 + num2);

EX 3.9.

Write a single statement that computes and prints the absolute value of total. System.out.println(Math.abs(total));

EX 3.10. Write code statements to create a DecimalFormat object that will round a formatted value to 4 decimal places. Then write a statement that uses that object to print the value of result, properly formatted. DecimalFormat fmt = new DecimalFormat(“0.####”); System.out.println(fmt.format(result)); EX 3.11. Write code statements that prompt for and read a double value from the user, and then print the result of raising that value to the fourth power. Output the results to 3 decimal places. Scanner scan = new Scanner(System.in); DecimalFormat fmt = new DecimalFormat(“0.###”); System.out.println("Enter a value: "); double num = scan.nextDouble(); System.out.println(fmt.format(Math.pow(num, 4))); EX 3.12. Write a declaration for an enumerated type that represents the days of the week. enum Days {sunday, monday, tuesday, wednesday, thursday, friday, saturday}


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 4

Chapter 4 Exercise Solutions EX 4.1.

What happens in the MinOfThree program if two or more of the values are equal? If exactly two of the values are equal, does it matter whether the equal values are lower or higher than the third? If two or more values are equal, the program still prints the lowest value. Because only less than comparisons are made, the comparison of two equal values produces a false result. If two values are equal, and lower than the third value, then one of the two lower but equal values is printed. If all three values are equal, then this value is printed. Which “version” of the equal value is irrelevant. If only two values are equal, it does not matter whether the third is lower or higher. The correct result is determined in either case. If the two equal values are lower than the third, then one of the two lower but equal values is printed. If the two equal values are higher than the third, then the third value is printed.

EX 4.2.

What is wrong with the following code fragment? Rewrite it so that it produces correct output. if (total == MAX) if (total < sum) System.out.println("total == MAX and < sum."); else System.out.println("total is not equal to MAX"); Despite the indentation, the else clause is associated with the immediately preceding if rather than the first if. The program will produce the correct output if it is rewritten as: if (total == MAX) { if (total < sum) System.out.println("total == MAX and < sum."); } else System.out.println("total is not equal to MAX");

EX 4.3.

What is wrong with the following code fragment? Will this code compile if it is part of an otherwise valid program? Explain. if (length = MIN_LENGTH) System.out.println("The length is minimal."); The assignment operator (=) is used erroneously in place of the equality operator (==). Hence, it will not compile in an otherwise valid program.

EX 4.4.

What output is produced by the following code fragment? int num = 87, max = 25; if (num >= max * 2) System.out.println("apple"); System.out.println("orange"); System.out.println("pear"); The second println statement is improperly indented, so the output produced is:


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 4

apple orange pear EX 4.5.

What output is produced by the following code fragment? int limit = 100, num1 = 15, num2 = 40; if (limit <= limit) { if (num1 == num2) System.out.println("lemon"); System.out.println("lime"); } System.out.println("grape"); The output is: lime grape

EX 4.6.

Put the following list of strings in lexicographic order as if determined by the compareTo method of the String class. Consult the Unicode chart in Appendix C. "fred" "Ethel" "?-?-?-?" "{([])}" "Lucy" "ricky" "book" "******" "12345" " " "HEPHALUMP" "bookkeeper" "6789" ";+<?" "^^^^^^^^^^" "hephalump" The strings in lexicographic order: " " "******" "12345" "6789" ";+<?" "?-?-?-?" "Ethel" "HEPHALUMP"


Java Foundations, 5th Edtion "Lucy" "^^^^^^^^^^" "book" "bookkeeper" "fred" "hephalump" "ricky" "{([])}" EX 4.7.

What output is produced by the following code fragment? int num = 1, max = 20; while (num < max) { System.out.println(num); num += 4; } The output produced is: 1 5 9 13 17

EX 4.8.

What output is produced by the following code fragment? int num = 1, max = 20; while (num < max) { if (num%2 == 0) System.out.println(num); num++; } The output produced is: 2 4 6 8 10 12 14 16 18

EX 4.9.

What output is produced by the following code fragment? for (int num = 0; num <= 200; num += 2) System.out.println(num);

Exercise Solutions, Ch. 4


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 4

The output produced is the even numbers from 0 to 200: 0 2 4 and so on until… 198 200 EX 4.10. What output is produced by the following code fragment? for (int val = 200; val >= 0; val -= 1) if (val % 4 != 0) System.out.println(val); The output produced is all values from 200 down to 0, except those that are evenly divisible by 4: 199 198 197 195 and so on until… 5 3 2 1 EX 4.11. Transform the following while loop into an equivalent do loop (make sure it produces the same output). int num = 1; while (num < 20) { num++; System.out.println(num); } This code can be written using a do loop as follows: int num = 1; do { num++; System.out.println(num); } while (num < 20); EX 4.12. Transform the while loop from exercise 4.11 into an equivalent for loop (make sure it produces the same output). for (int num = 2; num <=20; num ++) System.out.println(num);


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 4

EX 4.13. What is wrong with the following code fragment? What are three distinct ways it could be changed to remove the flaw? count = 50; while (count >= 0) { System.out.println(count); count = count + 1; } The loop is infinite because count initially is greater than zero, and continues to increase in value. The flaw can be removed by (1) decrementing rather than incrementing count, (2) initializing count to 0 and using, as the condition of the while loop, count <= 50, and (3) picking an upper limit and using, as the condition of the while loop, count <= upperLimit. EX 4.14. Write a while loop that verifies that the user enters a positive integer value. Scanner scan = new Scanner(System.in); System.out.print("Enter a positive integer: "); number = scan.nextInt(); while (number <= 0) { System.out.print("That number was not positive."); System.out.print("Enter a positive integer: "); number = scan.nextInt(); } EX 4.15. Write a do loop that verifies that the user enters an even integer value. Scanner scan = new Scanner(System.in); do { System.out.print("Enter an even integer: "); number = scan.nextInt(); } while {number % 2 != 0); EX 4.16. Write a code fragment that reads and prints integer values entered by a user until a particular sentinel value (stored in SENTINEL) is entered. Do not print the sentinel value. Scanner scan = new Scanner(System.in); System.out.print("Enter some integers (" + SENTINEL + " to quit): "); number = scan.nextInt(); while (number != SENTINEL) { System.out.println(number); number = scan.nextInt(); }


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 4

EX 4.17. Write a for loop to print the odd numbers from 1 to 99 (inclusive). for (int value = 1; value <= 99; value +=2) System.out.println(value); EX 4.18. Write a for loop to print the multiples of 3 from 300 down to 3. for (int value = 300; value >= 3, value -= 3) System.out.println(value); EX 4.19. Write a code fragment that reads 10 integer values from the user and prints the highest value entered. Scanner scan = new Scanner(System.in); int max, number; System.out.print("Enter an integer: "); max = scan.nextInt(); for (int count = 2; count <= 10; count++) { System.out.print("Enter another integer: "); number = scan.nextInt(); if (number > max) max = number; } System.out.println("The highest value is :" + max); EX 4.20. Write a code fragment that computes the sum of the integers from 20 to 70, inclusive, then prints the results. int sum = 0; for (int count = 20; count <= 70; count++) sum += count; System.out.println("The sum is " + sum); EX 4.21. Write a code fragment that determines and prints the number of times the character 'z' appears in a String object called name. int count = 0; for (int index = 0; index < name.length(); index++) if (name.charAt(index) == 'z') count++; System.out.println("The character \'z\' appears " + count + " time(s)"); EX 4.22. Write a code fragment that prints the characters stored in a String object called str backward. for (int index = str.length()-1; index >= 0; index--) System.out.print(str.charAt(index)); System.out.println();


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 4

EX 4.23. Write a code fragment that prints every other character in a String object called word starting with the first character. for (int index = 0; index < word.length(); index +=2) System.out.println(word.charAt(index));


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 5

Chapter 5 Exercise Solutions EX 5.1.

For each of the following pairs, which represents a class and which represents an object of that class?

a. Superhero, Superman Class: Superhero, Object: Superman b. Justin, Person Class: Person, Object: Justin c. Rover, Pet Class: Pet, Object: Rover d. Magazine, Time Class: Magazine, Object: Time e. Christmas, Holiday Class: Holiday, Object: Christmas EX 5.2.

List some attributes and operations that might be defined for a class called PictureFrame that represents a picture frame. Attributes could include: height, width, empty (boolean) Operations could include: getHeight, setHeight, getWidth, setWidth, isEmpty, fill

EX 5.3.

List some attributes and operations that might be defined for a class called Meeting that represents a business meeting. Attributes could include: date, time, location, purpose, attendees (list of People) Operations could include: setters and getters for all attributes, announce, cancel

EX 5.4.

List some attributes and operations that might be defined for a class called Course that represents a college course (not a particular offering of a course, just the course in general). Attributes could include: courseNumber, courseName, department, numCredits, description Operations could include: setters and getters for all attributes, offer

EX 5.5.

Rewrite the for loop body from the SnakeEyes program so that the variables num1 and num2 are not used. for (int roll=1; roll <= ROLLS; roll++) if (die1.roll() == 1 and die2.roll() == 1) count++;

EX 5.6.

Write a method called lyrics that prints the lyrics of a song when invoked. The method should accept no parameters and return no value. public void lyrics() { System.out.println("The itsy bitsy spider"); System.out.println("Went up the waterspout.");


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 5

System.out.println("Down came the rain and"); System.out.println("Washed the spider out."); System.out.println("Out came the sun and"); System.out.println("Dried up all the rain."); System.out.println("So the itsy bitsy spider"); System.out.println("Went up the spout again."); } EX 5.7.

Write a method called cube that accepts one integer parameter and returns that value raised to the third power. public int cube (int num) { return Math.pow(num, 3); }

EX 5.8.

Write a method called random100 that returns a random integer in the range of 1 to 100 (inclusive). public int random100() { Random generator = new Random(); return generator.nextInt(100) + 1; }

EX 5.9.

Write a method called randomInRange that accepts two integer parameters representing a range. The method should return a random integer in the specified range (inclusive). Assume that the first parameter is greater than the second. public int randomInRange (int first, int second) { Random generator = new Random(); int range = second – first + 1; return generator.nextInt(range) + first; }

EX 5.10. Write a method called powersOfTwo that prints the first 10 powers of 2 (starting with 2). The method takes no parameters and doesn't return anything. public void powersOfTwo() { int base = 2; for (int power = 1; power <= 10; power++) System.out.println(Math.pow(base,power)); } Alternate answer: public void powersOfTwo() { int num = 2;


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 5

for (int power = 1; power <= 10; power++) { num *= 2; System.out.println(num); } } EX 5.11. Write a method called alarm that prints the string "Alarm!" multiple times on separate lines. The method should accept an integer parameter that specifies how many times the string is printed. Print an error message if the parameter is less than 1. public void alarm(int number) { if (number < 1) System.out.println("ERROR: Number is less than 1."); else for (int count = 1; count <= number; count++) System.out.println("Alarm!"); } EX 5.12. Write a method called sum100 that returns the sum of the integers from 1 to 100, inclusive. public int sum100() { int sum = 0; for (int count = 1; count <= 100; count++) sum += count; return sum; } EX 5.13. Write a method called maxOfTwo that accepts two integer parameters and returns the larger of the two. public int maxOfTwo(int num1, int num2) { int result = num1; if (num2 > num1) result = num2; return result; } Note that the method Math.max also performs this function. EX 5.14. Write a method called sumRange that accepts two integer parameters that represent a range. Issue an error message and return zero if the second parameter is less than the first. Otherwise, the method should return the sum of the integers in that range (inclusive).


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 5

public int sumRange(int start, int end) { int sum = 0; if (end < start) System.out.println("ERROR: Invalid Range”); else for (int num = start; num <= end; num++) sum += num; return sum; } EX 5.15. Write a method called larger that accepts two floating-point parameters (of type double) and returns true if the first parameter is greater than the second, and false otherwise. public boolean larger(double num1, double num2) { return (num1 > num2); } EX 5.16. Write a method called countA that accepts a String parameter and returns the number of times the character 'A' is found in the string. public int countA(String text) { int count = 0; for (int index = 0; index < text.length(); index++) if (text.charAt(index) == 'A') count++; return count; } EX 5.17. Write a method called evenlyDivisible that accepts two integer parameters and returns true if the first parameter is evenly divisible by the second, or vice versa, and false otherwise. Return false if either parameter is zero. public boolean evenlyDivisible(int num1, int num2) { boolean result = false; if (num1 != 0 && num2 != 0) if (num1 % num2 == 0 || num2 % num1 == 0) result = true; return result; }


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 5

EX 5.18. Write a method called isAlpha that accepts a character parameter and returns true if that character is either an uppercase or lowercase alphabetic letter. public boolean isAlpha(char ch) { return ( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ); } Note: similar functionality is provided by the Character.isLetter method. EX 5.19. Write a method called floatEquals that accepts three floating-point values as parameters. The method should return true if the first two parameters are equal within the tolerance of the third parameter. public boolean floatEquals(double float1, double float2, double tolerance) { return (Math.abs(float1 - float2) <= tolerance); } EX 5.20. Write a method called reverse that accepts a String parameter and returns a string that contains the characters of the parameter in reverse order. Note that there is a method in the String class that performs this operation, but for the sake of this exercise, you are expected to write your own. public String reverse(String text) { String result = ""; for (int place = text.length()-1; place >= 0; place--) result += text.charAt(place); return result; } EX 5.21. Write a method called isIsoceles that accepts three integer parameters that represent the lengths of the sides of a triangle. The method returns true if the triangle is isosceles but not equilateral (meaning that exactly two of the sides have an equal length), and false otherwise. public boolean isIsoceles(int side1, int side2, int side3) { boolean result = false; if ( (side1 == side2) && side1 != side3) || (side2 == side3) && side2 != side1) || (side1 == side3) && side1 != side2) ) result = true; return result;


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 5

} EX 5.22. Write a method called average that accepts two integer parameters and returns their average as a floating point value. public double average(int num1, int num2) { return (num1 + num2) / 2.0; } EX 5.23. Overload the average method of Exercise 5.22 such that if three integers are provided as parameters, the method returns the average of all three. public double average(int num1, int num2, int num3) { return (num1 + num2 + num3) / 3.0; } EX 5.24. Overload the average method of Exercise 5.22 to accept four integer parameters and return their average. public double average(int num1, int num2, int num3, int num4) { return (num1 + num2 + num3 + num4) / 4.0; } EX 5.25. Write a method called multiConcat that takes a String and an integer as parameters. Return a String that consists of the string parameter concatenated with itself count times, where count is the integer parameter. For example, if the parameter values are "hi" and 4, the return value is "hihihihi". Return the original string if the integer parameter is less than 2. public String multiConcat(String text, int count) { String result = text; if (count > 1) for (int i=2; i <= count; i++) result += text; return result; } EX 5.26. Overload the multiConcat method from Exercise 5.25 such that if the integer parameter is not provided, the method returns the string concatenated with itself. For example, if the parameter is "test", the return value is "testtest" public String multiConcat(String text) { return text + text; }


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 5

EX 5.27. Discuss the manner in which Java passes parameters to a method. Is this technique consistent between primitive types and objects? Explain. Java passes all parameters by value. This means that the current value of the actual parameter is copied into the formal parameter in the method header. This technique is consistent between primitive types and objects because object references rather than objects themselves are passed. When an object (actually, an object reference) is passed, the current value of the reference (the object's address) is copied into the corresponding formal parameter in the method header. EX 5.28. Explain why a static method cannot refer to an instance variable. A static method is invoked through a class rather than through an object of the class. No object of the class needs to be instantiated in order to invoke a static method. If no object is instantiated, no instance variable exists. Hence, a static method cannot refer to an instance variable. EX 5.29. Can a class implement two interfaces that each contains the same method signature? Explain. Yes. The class which implements an interface provides method implementations for each of the abstract methods defined in the interface. In satisfying the requirements for a method of one interface, it simultaneously satisfies the requirements for a method with the same signature in another interface. Note: this exercise should have been deferred until Chapter 9. EX 5.30. Draw a UML class diagram for the CountFlips program.

EX 5.31. Draw a UML class diagram for the FlipRace program.

EX 5.32. Draw a UML class diagram for the Transactions program.


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 5


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 6

Chapter 6 Exercise Solutions EX 6.1.

Explain how two controls can be set up to share the same event handler. How can the event handler tell which control generated the event? The relationship between a control and an event handler method is established by calling a convenience method such as setOnAction on the control, passing a reference to the event handler method. So passing the same event handler to two separate controls allow them to share the event handler. The event object passed to the event handler method has a method called getSource that allows the event handler to determine which control generated the event.

EX 6.2.

Can one node have multiple event handler methods? Give an example. Yes, but only if the node generates different types of events. There is only one event handler per event type per node. So, for instance, a node (such as a Scene) that generates various types of mouse events can have different event handlers for each.

EX 6.3.

Explain what would happen if the ToggleGroup had not been set on the radio buttons used in the QuoteOptions program. If the radio buttons hadn’t been added to the ToggleGroup, then the buttons would have acted independently. There would be no mutual exclusion, and mutliple buttons could be “on” at the same time (which would not work properly for that program).

EX 6.4.

In the PushCounter program, why was the count primitive variable and the Text object declared at the class level? Why wasn’t anything else, such as the Button? Declaring something at the class level allows it to be accessed in all methods of the class. The count variable and the Text object were the only elements needed in both the start method and the processButtonPress method. The Button was only needed in the start method, so it could be declared as local data in that method.

EX 6.5.

Why is the event object that is passed to an event handler method sometimes ignored? Sometimes all an event handler needs to know is that the event occurred, in which case, the object representing the event can be ignored. In other cases, the even object has key information that can be used. For instance, the MouseEvent object contains the coordinates where the event occurred, which may be important for handling the event.

EX 6.6.

What kind of event does a TextField object generate? When does it generate the event? A TextField object generates an action event whenever the user presses the Return key while the cursor is in the text field.

EX 6.7.

Which user action generates three separate mouse events? Which events? Why? The user clicking the mouse button generates three separate mouse events: mouse pressed, mouse released, and mouse clicked. The programmer can set up handlers on whichever event, or multiple events, is most appropriate for the situation.

EX 6.8.

Describe the events that can be generated when the user types a key on the keyboard. Pressing a key on the keyboard generates a key pressed event when the key is pressed down, a key released event when it is released, and a key typed event when both occur.


Java Foundations, 5th Edtion EX 6.9.

Exercise Solutions, Ch. 6

How would you create a rollover effect in a JavaFX program? For example, how would you change the background color of the scene whenever you rolled over an image with the mouse cursor? A rollover effect is created by handling the mouse entered and mouse exited events. When the mouse cursor rolls over (enters) the image, the background color of the scene could be changed, and when it rolls off (exits) the image, the color could be changed back.

EX 6.10. What is a file chooser and how does it relate to a dialog box? A file chooser is a specialized dialog box that is already set up to allow the user to select a file from storage. EX 6.11. What is a property binding? Give an example. Property binding is when one property (such as the width of a shape) is bound to another proerty (such as the width of the scene). Then, as the scene size changes when the window is enlarged, the size of the shape changes automatically. EX 6.12. Compare and contrast event handlers and change listeners. Both event handlers and change listeners respond to something happening. An event handler responds to a event occuring, such as a button press, whereas a change listener responds to the value of a property being changed.


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 7

Chapter 7 Exercise Solutions EX 7.1.

Which of the following are valid declarations? Which instantiate an array object? Explain your answers. int primes = {2, 3, 4, 5, 7, 11}; Invalid; an int cannot be declared and initialized using an intializer list. The brackets are missing. float elapsedTimes[] = {11.47, 12.04, 11.72, 13.88}; Valid; the brackets can be placed either after the element type or after the reference variable. However, this is not the preferred technique. This declaration creates an array object. int[] scores = int[30]; Invalid; the right hand side of the assignment operator must contain either an initializer list or a new operation. int[] primes = new {2,3,5,7,11}; Invalid; “new” on the right hand side of the assignment operator is neither necessary nor acceptable. int[] scores = new int[30]; Valid; the assignment is correct Java syntax. This declaration creates an array object. char grades[] = {'a', 'b', 'c', 'd', 'f'}; Valid; the brackets can be placed either after the element type or after the reference variable. However, this is not the preferred technique. This declaration creates an array object. char[] grades = new char[]; Invalid; the size of the array must be indicated when the array is instantiated.

EX 7.2.

Describe five programs that would be difficult to implement without using arrays. A program to find the average midterm score of 600 students enrolled in an introductory computer science course. A program to record and compute the sum of the snowfalls, recorded on a daily basis for the 40 days preceding the Winter Olympics. A program to determine the relative frequency of each character in the Cyrillic alphabet in the original version of The Brothers Karamasov. A program to compute the mean and standard deviation of the Dow Jones Industrial Average closings since September 11, 2001. A program to store the coordinates of the vertices of polygons approximating the surface of a beating heart.

EX 7.3. Describe what problem occurs in the following code. What modifications should be made to it to eliminate the problem? int[] numbers = {3, 2, 3, 6, 9, 10, 12, 32, 3, 12, 6}; for (int count = 1; count <= numbers.length; count++) System.out.println(numbers[count]);


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 7

The for loop fails to print the 0th element of the array, and attempts to print the nonexistent 11th element of the array. As a consequence, an ArrayIndexOutOfBoundsException is thrown. The problem can be eliminated by providing a for loop which initializes count to 0 (rather than 1) and tests if count is less than (rather than less than or equal to) numbers.length. EX 7.4.

Write an array declaration and any necessary supporting classes to represent the following statements:

a. students’ names for a class of 25 students String[] students = new String[25]; b. students’ test grades for a class of 40 students int[] grades = new int[40]; or, for simple letter grades: char[] grades = new char[40]; or, for letter grades that include pluses and minuses String[] grades = new String[40]; c. credit-card transactions that contain a transaction number, a merchant name, and a charge Transactions[] charges = new Transactions[MAX]; public class Transactions { private int transactionNumber; private String merchantName; private double charge; // etc. } d. students’ names for a class and homework grades for each student Student[] myClass = new Student[MAX]; public class Student { private String name; private int[] grades; // etc. } e. for each employee of the L&L International Corporation: the employee number, hire date, and the amount of the last five raises Employee[]employees = new Employee[MAX]; public class Employee { private int employeeNumber; private String hireDate;


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 7

private double raise[] = new double[5]; // etc. } EX 7.5.

Write code that sets each element of an array called nums to the value of the contstant INITIAL. for (int index = 0; index < nums.length; index++) nums[index] = INITIAL;

EX 7.6.

Write code that prints the values stored in an array called names backwards. for (int index = names.length-1; index >= 0; index--) System.out.println(names[index]);

EX 7.7.

Write code that sets each element of a boolean array called flags to alternating values (true at index 0, false at index 1, etc.). for (int index = 0; index < flags.length; index++) flags[index] = (index % 2 == 0);

EX 7.8.

Write a method called sumArray that accepts an array of floating point values and returns the sum of the values stored in the array. public float sumArray(float[] values) { float sum = 0; for (int index = 0; index < values.length; index++) sum += values[index]; return sum; }

EX 7.9.

Write a method called switchThem that accepts two integer arrays as parameters and switches the contents of the arrays. Take into account that the arrays may be of different sizes. public void switchThem(int[] first, int[] second) { if (first.length == second.length) { // copy contents of first into temp int [] temp = new int[first.length]; for (int i = 0; I < first.length; i++) temp[i] = first[i]; //copy contents of second into first for (int i = 0; I < first.length; i++) first[i] = second[i]; //copy contents of temp into second for (int i = 0; I < first.length; i++)


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 7

second[i] = temp[i]; } else System.out.println("Arrays are of different sizes"); }


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 8

Chapter 8 Exercise Solutions EX 8.1.

Draw a UML class diagram showing an inheritance hierarchy containing classes that represent different types of clocks. Show the variables and method names for two of these classes.

EX 8.2.

Show an alternative diagrm for the hierarchy in exercise 8.1. Explain why it may be a better or worse approach than the original.

The value of the organization is dependent on how the classes are used. The hierarchy in exercise 8.1 might be better suited to a system maintaining the inventory and online shopping for a store, whereas the hierarchy in exercise 8.2, centered around the mounting capabilities, might be better suited to a manufacturing system.


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 8

EX 8.3.

Draw a UML class diagram showing an inheritance hierarchy containing classes that represent different types of cars, organized first by manufacturer. Show some appropriate variables and method names for at least two of these classes.

EX 8.4.

Show an alternative diagram for the hierarchy in exercise 8.3 in which the cars are organized first by type (sports car, sedan, SUV, etc.). Show some appropriate variables and method names for at least two of these classes. Compare and contrast the two approaches.


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 8

The hierarchy in exercise 8.3 has the manufacturer information as an inherent part of the inheritance structure, and might store car type information as data in lower level classes. The hierarchy in exercise 8.4 is organized around car type, with the manufacturer as data. Which one would be best depends on the purpose of the system. EX 8.5.

Draw a UML class diagram showing an inheritance hierarchy containing classes that represent different types of airplanes. Show some appropriate variables and method names for at least two of these classes.

EX 8.6.

Draw a UML class diagram showing an inheritance hierarchy containing classes that represent different types of trees (oak, elm, etc.). Show some appropriate variables and method names for at least two of these classes.


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 8

EX 8.7.

Draw a UML class diagram showing an inheritance hierarchy containing classes that represent different types of transactions at a store (cash, credit card, etc.). Show some appropriate variables and method names for at least two of these classes.

EX 8.8.

Experiment with a simple derivation relationship between two classes. Put println statements in constructors of both the parent and child classes. Do not explicitly call the constructor of the parent in the child. What happens? Why?


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 8

Change the child's constructor to explicitly call the constructor of the parent. Now what happens? When a parent's constructor is explicitly called, its program statements are executed as expected. But even in the absence of an explicit call, the parent's constructor is called when the child class is instantiated. An explicit call allows the child to pass parameters, allowing the parent to set up its contribution to the child's state. Without an explicit call, the default constructor is called, without parameters.


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 9

Chapter 9 Exercise Solutions EX 9.1.

Draw and annotate a class hierarchy that represents various types of faculty at a university. Show what characteristics would be represented in the various classes of the hierarchy. Explain how polymorphism could play a role in the process of assigning courses to each faculty member.

The abstract method assignCourses is established in the FacultyMember class, ensuring that child classes will implement it. That way, each class can have a definition of assignCourses that makes sense for it (depending on the rank and other issues). A program that manages a list of various faculty member objects could then assign courses to everyone by making a polymorphic call to assignCourses for each faculty member. EX 9.2.

Draw and annotate a class hierarchy that represents various types of animals in a zoo. Show what characteristics would be represented in the various classes of the hierarchy. Explain how polymorphism could play a role in guiding the feeding of the animals.


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 9

The abstract method feedingInstructions is established in the ZooAnimal class, ensuring that child classes will implement it. That way, each class can have a definition of feedingInstructions that makes sense for it. A program that manages a list of various animal objects could then print feeding instructions for all animals by making a polymorphic call to feedingInstructions for each animal. EX 9.3.

Draw and annotate a class hierarchy that represents various types of sales transactions in a store (cash, credit, etc.). Show what characteristics would be represented in the various classes of the hierarchy. Explain how polymorphism could play a role in the payment process. The following diagram is a modified version of the one used for exercise 8.7.


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 9

The abstract method purchase is established in the Sale class, ensuring that child classes will implement it. That way, each class can have a definition of purchase that makes sense for it, as opposed to the computeTax method, which is implemented in Sale and used by all child classes as is. A program that manages the sales transactions as they occur could then conduct the transaction by making a polymorphic call to purchase no matter what the transaction type is. EX 9.4.

What would happen if the pay method were not defined as an abstract method in the StaffMember class of the Firm program? By defining the pay method in StaffMember, all child classes must implement it (or be abstract themselves). So if pay were not defined in StaffMember, the child classes would not have to implement it and the ability to pay all staff members through a polymorphic reference would not exist. It is only by formally establishing that all children of StaffMember have a pay method that makes it safe to pay them all.

EX 9.5.

Create an interface called Visible that includes two methods: makeVisible and makeInvisible. Both methods should take no parameters and should return a boolean result. Describe how a class might implement this interface. public interface Visible { public boolean makeVisible(); public boolean makeInvisible(); }


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 9

A class implementing Visible would include an implements clause in the class header, such as: public class ControlPanel implements Visible The class would contain, among other things, two methods with signatures that match those specified in the interface. EX 9.6.

Draw a UML class diagram that shows the relationships among the elements of exercise 9.5.

EX 9.7.

Create an interface called DVR that has methods that represent the standard operations on a digital video recorder (play, stop, etc.). Define the method signatures any way you desire. Describe how a class might implement this interface. public interface DVR { public String play(); public String stop(); public String record(int start, int end); public String pause(); } A class implementing DVR would include an implements clause in the class header, such as: public class MyDVR implements DVR The class would contain, among other things, four methods with signatures that match those specified in the interface.

EX 9.8.

Draw a UML class diagram that shows the relationships among the elements of exercise 9.7.


Java Foundations, 5th Edtion EX 9.9.

Exercise Solutions, Ch. 9

Explain how a call to the addMouseListener method in a GUI-based program represents a polymorphic situation. The addMouseListener method was written years ago by a Sun Microsystems API programmer, long before any particular class you write to serve as a mouse listener. The addMouseListener method is written to take a parameter of type MouseListener (the interface). That way, any object that implements the object interface can be passed to it, even one that was just written. Because of the contract established by the interface, the component can make a polymorphic call to a method such as mouseClicked through whatever mouse listener object is provided.


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 10

Chapter 10 Exercise Solutions EX 10.1. Create a UML class diagram for the ProductCodes program.

EX 10.2. Describe the output for the ProductCodes program if a finally clause were added to the try statement that printed the string "Got here!". A finally clause is executed no matter how the try block is executed. So if no exception occurs, or even if one does, the string will be printed in each iteration of the while loop. If an exception occurs, the appropriate catch clause is executed first, then the finally clause. If no catch clause matches the exception thrown, only the finally clause is executed. EX 10.3. What would happen if the try statement were removed from the level1 method of the ExceptionScope class in the Propagation program? If the try statement were removed from the level1 method, the ArithmeticException, when thrown, would propagate to the main method (which called the level1 method). Since there is no try statement in the main method, the program would terminate, producing the message associated with the exception. EX 10.4. What would happen if the try statement described in the previous exercise were moved to the level2 method? If the try statement were moved from the level1 method to the level2 method, the exception thrown in level3 would propogate only to level2, where it would be caught and handled. The level2 method would then be allowed to finish execution. EX 10.5. What happens when the Exception class is used in a catch clause to catch an exception? When an exception is thrown, control transfers to the first catch clause that matches the exception. The Exception class, as the ancestor of all exceptions, will match any exception. Therefore, a catch clause that uses the Exception class will be processed every time unless a previous catch clause matched the exception. EX 10.6. Look up the following exception classes in the online Java API documentation and describe their purpose: a. ArithmeticException This exception is thrown when an exceptional arithmetic condition occurs, such as dividing by zero. b. NullPointerException


Java Foundations, 5th Edtion

Exercise Solutions, Ch. 10

This exception is (most commonly) thrown when attempting to call an instance method of a null reference. It occurs in other situations as well, such as attempting to throw a null reference. c. NumberFormatException This exception is thrown when an application attempts to convert a string into a numeric value, but the string does not have the proper format. d. PatternSyntaxException This exception is thrown when a syntax error occurs in the pattern of a regular expression. EX 10.7. Describe the PrintWriter class used in the TestData program. A PrintWriter object prints formatted output to a text output stream. In the case of the TestData program, the output stream is an ouput file. A PrintWriter object has print and println methods, just like the System.out object.


Java Foundations, 5th Edition

Exercise Solutions, Ch. 11

Chapter 11 Exercise Solutions EX 11.1. What is the order of the following growth functions? a. 10n2 + 100n + 1000

O(n2)

b. 10n3 – 7

O(n3)

c. 2n + 100n3

O(2n)

d. n2 log n

O(n2 log n)

EX 11.2. Arrange the growth functions of the previous exercise in ascending order of efficiency for n = 10 and again for n = 1,000,000. For n = 10: Least efficient: 2n + 100n3 10n3 – 7 10n2 + 100n + 1000 Most efficient:

n2 log n

For n = 1,000,000: Least efficient: 2n + 100n3 10n3 – 7 n2 log n Most efficient:

10n2 + 100n + 1000

EX 11.3. Write the code necessary to find the largest element in an unsorted array of integers. What is the time complexity of this algorithm? int max; if (intArray.length > 0) { max = intArray[0]; for (int num = 1; num < intArray.length; num++) if (intArray[num] > max) max = intArray[num]; System.out.println (max); } else { System.out.println ("The array is empty."); } The algorithm examines each of the array. If there are n elements in the array, the time complexity of the algorithm is O(n).


Java Foundations, 5th Edition

Exercise Solutions, Ch. 11

EX 11.4. Determine the growth function and order of the following code fragment:

for (int count = 0; count < n; count ++) { for (int count2 = 0; count2 < n; count2 = count2 + 2) { System.out.println(count, count2); } } The outer loop will be executed n times. The inner loop will be executed (n+1)/2 times. Therefore, the growth function for the code fragment is n*((n+1)/2) = (n2 + n)/ 2. That is order n2.

EX 11.5. Determine the growth function and order of the following code fragment:

for (int count = 0; count < n; count ++) { for (int count2 = 0; count2 < n; count2 = count2 * 2) { System.out.println(count, count2); } } The outer loop will be executed n times. The inner loop will be executed log n times. Therefore, the growth function for the code fragment is n*(log n). That is order n log n.

EX 11.6. The table in Figure 11.1 shows how the terms of a growth function for our dishwashing example are related to one another as n grows. Write a program that will create such a table for any given growth function.

Solution not provided at this time.


Java Foundations, 5th Edition

Exercise Solutions, Ch. 12

Chapter 12 Exercise Solutions EX 12.1

Compare and contrast data types, abstract data types, and data structures. A data type is a set of values and operations defined on those values. An abstract data type is a data type whose values and operations are not inherently defined within a programming language. A data structure is the collection of programming constructs used to implement an abstract data type.

EX 12.2

List the collections in the Java Collections API and mark the ones that are covered in this text. There are more than 25 classes that implement the Collection interface in the Java Collections API. This text covers stacks, queues, binary search trees, heaps, priority queues, graphs, and hash tables. Most of these collections are also represented in the Java Collectoins API. Graphs are not included in the Java Collections API, which is a notable exception.

EX 12.3

Define the concept of abstraction and explain why it is important in software development. Abstraction hides certain details at certain times. Most modern software is far too complicated for any one person to understand all of it without abstraction. Abstraction allows a person to focus on one part of a program and ignore the details of other parts of the program. In this way, it allows us to manage complexity.

EX 12.4

Hand trace a stack X through the following operations: X.push(new Integer(4)); X.push(new Integer(3)); Integer Y = X.pop(); X.push(new Integer(7)); X.push(new Integer(2)); X.push(new Integer(5)); X.push(new Integer(9)); Integer Y = X.pop(); X.push(new Integer(3)); X.push(new Integer(9));

The stack, after each operation (top of stack on the left): 4 3 4 4 7 4 2 7 4 5 2 7 4 9 5 2 7 4 5 2 7 4 3 5 2 7 4 9 3 5 2 7 4


Java Foundations, 5th Edition

EX 12.5

Exercise Solutions, Ch. 12

Given the resulting stack X from the previous exercise, what would be the result of each of the following? Y = X.peek();

The value of Y would be 9 and the stack would remain unchanged. Y = X.pop(); Z = X.peek();

The value of Y would be 9, the value of Z would be 3, and the stack would contain: 3 5 2 7 4 Y = X.pop(); Z = X.peek();

The value of Y would be 9, the value of Z would be 3, and the stack would contain: 3 5 2 7 4

EX 12.6

What should be the time complexity of the isEmpty(), size(), and toString() methods? Using the count variable, the size method is O(1) and simply returns the value of count. The isEmpty() method simply checks to see if size is equal to zero, so it is also O(1). The toString() method looks at each element in the stack once, so its time complexity is O(n), where n is the number of elements in the stack.

EX 12.7

Show how the undo operation in a word processor can be supported by the use of a stack. Give specific examples and draw the contents of the stack after various actions are taken. Suppose the following actions were taken, in order, in the word processor: (1) type the title, (2) make the title bold, (3) delete the third paragraph, and (4) center the author's name. Every time an action is performed, some representation of it would be pushed onto the stack. So after these actions the stack would look like this (top of stack on the left): center name | delete paragraph | title bold | type title The undo operation would pop the top of the stack (the last operation) and undo it. So if two undo operations were performed at this point, the name would no longer be centered, the paragraph would be reinserted, and the stack would look like this: title bold | type title

EX 12.8

In the postfix expression evaluation example, the two most re- cent operands are popped when an operator is encountered so that the sub-expression can be evaluated. The first operand popped is treated as the second operand in the sub-expression, and the second operand popped is the first. Give and explain an example that demonstrates the importance of this aspect of the solution. For operations such as addition and multiplication, the order of operands does not matter, but for subtraction and division, for instance they do. So the postfix expression


Java Foundations, 5th Edition

Exercise Solutions, Ch. 12

17 4 means to subtract 4 from 17 (and not the other way around). When these operands are pushed onto the stack, 17 goes on first, then 4 on top. So when they are popped to be evaluated, the first value popped must be treated as the second operand.

EX 12.9

Draw an example using the five integers (12, 23, 1, 45, 9) of how a stack could be used to reverse the order (9, 45, 1, 23, 12) of these elements. The five values would be pushed onto the stack in order, yielding (with the top of the stack on the left): 9 45 1 23 12 Then popping each value produces them in the reverse order to which they were first encountered.

EX 12.10

Explain what would happen to the algorithms and the time complexity of an array implementation of the stack if the top of the stack were at position 0. A array-based stack implementation can take advantage of the fact that all processing on the stack takes place on one end. By implementing it so that the bottom of the stack (the "inactive" end) is at position 0, elements are added and removed at higher index values. If the top of the stack were designed to be at position 0, then all activity would take place there, and the remaining elements of the stack would have to be shifted one position every time an element was pushed or popped, which would be inefficient.


Java Foundations, 5th Edition

Exercise Solutions, Ch. 13

Chapter 13 Exercise Solutions EX 13.1. Explain what will happen if the steps depicted in Figure 13.4 are reversed. If we change the front reference of the list before we set the next reference of the newly added node, we will lose the entire list. The newly added node’s next reference will simply point to itself. EX 13.2. Explain what will happen if the steps depicted in Figure 13.5 are reversed. If we change the next reference of current before we set the next reference of the newly added node, we will lose everything after the newly added node. The newly added node’s next reference will simply point to itself. EX 13.3.

Draw a UML diagram showing the relationships among the classes involved in the linked list implementation of a stack.

LinkedStack <<realize>>

<<interface>> Stack

LinearNode

EX 13.4.

Write an algorithm for the add method that will add at the end of the list instead of the beginning. What is the time complexity of this algorithm? Create a new node containing a reference to the object to be placed on the stack. Create a current pointer that references the first element of the linked list representing the stack. Repeatedly set current to point to current.next, stopping when current.next is null. In this way, current points to the last element of the list. Set current.next to point to the newly created node. Increment the count of elements in the stack. This algorithm is O(n), where n is the number of elements in the stack.

EX 13.5.

Modify the algorithm from the previous exercise so that it makes use of a rear reference. How does this affect the time complexity of this and the other operations? Create a new node containing a reference to the object to be placed on the stack. Set rear.next to point to the newly created node. Set rear to point to the newly created node. Increment the count of elements in the stack.


Java Foundations, 5th Edition

Exercise Solutions, Ch. 13

This algorithm is O(1).

EX 13.6.

Discuss the effect on all operations on a stack if there were not a count variable in the implementation. Push and pop would be minimally affected. The only difference would be that the count variable would not have to be updated. Peek would not be affected at all. The isEmpty operation would have to check the contents of the stack to see if anything is on the stack, instead of looking at the count variable. The biggest impact would be on the size operation, which would have to count the number of elements in the stack one by one; instead of a O(1) operation, size would become a O(n) operation. EX 13.7.

Discuss the impact (and draw an example) of using a sentinel node or dummy node at the head of a list. A sentinel node allows the operations to assume there is a node (at least the sentinel) in the list. Therefore, special checks are not needed to set, for instance, the front reference, once the list is set up initially. EX 13.8.

Draw the UML class diagram for the iterative maze solver example from this chapter. Solution is not provided at this time.


Java Foundations, 5th Edition

Exercise Solutions, Ch. 14

Chapter 14 Exercise Solutions EX 14.1

Hand trace a queue X through the following operations: X.enqueue(new Integer(4)); X.enqueue(new Integer(1)); Object Y = X.dequeue(); X.enqueue(new Integer(8)); X.enqueue(new Integer(2)); X.enqueue(new Integer(5)); X.enqueue(new Integer(3)); Object Y = X.dequeue(); X.enqueue(new Integer(4)); X.enqueue(new Integer(9)); The queue, after each operation (rear of queue at the left): 4 1 4 1 8 1 2 8 1 5 2 8 1 3 5 2 8 1 3 5 2 8 4 3 5 2 8 9 4 3 5 2 8

EX 14.2

Given the resulting queue X from Exercise 14.1, what would be the result of each of the following? a.)

X.front();

X.front() is not a valid method call. We should have called X.first(), which would return 8. Additionally, we need to store the returned value if we wish to use it later. The queue would remain unchanged. b.) c.)

Y = X.dequeue(); X.front();

As in part (a), we should have called X.first() instead of X.front(), and we need to store the returned value in a variable if we wish to use it later. The value of Y would be 8, a call to X.first() would have returned 2, and the queue would contain: 9 4 3 5 2 d.) e.)

Y = X.dequeue(); X.front();

As in part (a), we should have called X.first() instead of X.front(), and we need to store the returned value in a variable if we wish to use it later. The value of Y would be 2, a call to X.first() would have returned 5, and the queue would contain: 9 4 3 5


Java Foundations, 5th Edition

EX 14.3

Exercise Solutions, Ch. 14

What would be the time complexity of the size operation for each of the implementations if there were not a count variable? With the count variable, the size operation is O(1) for all implementations. Without the count variable, the regular array solution and the linked solution would require the current elements to be counted, making the complexity O(n). For the circular array solution, the number of elements could be computed using the front and rear pointers (taking into account whether the end of the array is being spanned), so it would remain O(1).

EX 14.4

Under what circumstances could the head and tail references for the linked implementation or the front and rear references of the array implementation be equal? With a linked implementation, head and tail are equal when the queue is empty and they are both null. They are also equal when there is only one element in the queue. With a circular array implementation, front and rear are equal when the array is empty or the array is full.

EX 14.5

Hand trace the ticket counter problem for 22 customers and 4 cashiers. Graph the total process time for each person. What can you surmise from these results?

Cutomer Number Arrival time Cashier 1 Cashier 2 Cashier 3 Cashier 4 Wait Time Total Time 1 0 0 0 120 2 15 15 0 120 3 30 30 0 120 4 45 45 0 120 5 60 120 60 180 6 75 135 60 180 7 90 150 60 180 8 105 165 60 180 9 120 240 120 240 10 135 255 120 240 11 150 270 120 240 12 165 285 120 240 13 180 360 180 300 14 195 375 180 300 15 210 390 180 300 16 225 405 180 300 17 240 480 240 360 18 255 495 240 360 19 270 510 240 360 20 285 525 240 360 21 300 600 300 420 22 315 615 300 420

Customer wait time is going up. If this system were to continue, customer wait time would continue to increase without bound.


Java Foundations, 5th Edition

EX 14.6

Exercise Solutions, Ch. 14

Compare and contrast the enqueue method of the LinkedQueue class to the push method of the LinkedStack class from Chapter 13. Both add an element to the collection by adding a node to the end of a linked list. For enqueue, the node is added to the rear of the queue, and the only special case is if the queue is empty before the add. For push, the node is added to the top of the stack, and there are no special cases.

EX 14.7

Describe two different ways the isEmpty method of the LinkedQueue class could be implemented. In addition to checking the value of count, a queue will be empty only if the reference the front of the queue is null, or if the reference to the rear of the queue is null. You cannot, however, simply check if front and rear are equal, which will occur when there are zero or one elements in the queue.

EX 14.8

Name five everyday examples of a queue other than those discussed in this chapter. (1) Standing in line at the grocery store check out, (2) cars waiting in line at an intersection, (3) lining kids up in a classroom in the order they arrive, (4) a waiting list to join a club, and (5) a line at a cafeteria.

EX 14.9

Explain why the array implementation of a stack does not require elements to be shifted but the noncircular array implementation of a queue does. All operations on a stack occur on one end of the stack (the top). Therefore, the bottom of the stack can remain at location 0 of the array at all times. Operations on a queue, on the other hand, occur at both ends – additions to one end and removals from the other. If a non-circular array is used, the end can "move away" from index 0, requiring a shift in the elements to keep the elements rooted at that location.

EX 14.10

Suppose the count variable was not used in the CircularArrayQueue class. Explain how you could use the values of front and rear to compute the number of elements in the list. The difference between the front and rear indexes indicates the number of elements in the list, but the circular nature of the array must be taken into account. The following code could be used: public int size() { int result = rear – front; if (front > rear) result = MAX – front - rear; else if (front == rear) && (queue[front] != null) result = MAX return result; }


Java Foundations, 5th Edition

Exercise Solutions, Ch. 15

Chapter 15 Exercise Solutions EX 15.1.

Hand trace an ordered list X through the following operations. An ordered list keeps the items in order no matter when they are added. So the evolution of the list is as follows:

Operation

List

X.add(new Integer(4));

4

X.add(new Integer(7));

4 7

Object Y = X.first();

4 7 (Y takes on 4, list not change)

X.add(new Integer(3));

3 4 7

X.add(new Integer(2));

2 3 4 7

X.add(new Integer(5));

2 3 4 5 7

Object Y = X.removeLast();

2 3 4 5

Object Y = X.remove(new Integer(7));

2 3 4 5 (Y takes on null)

X.add(new Integer(9));

2 3 4 5 9

EX 15.2.

Given the resulting list X from Exercise 15.1, what would be the result of each of the following?

X.last()

returns 9

z = X.contains(new Integer(3));

z takes on true

X.first();

returns 2

Y = X.remove(new Integer(2));

Y takes on 2

X.first();

returns 3

EX 15.3.

What would be the time complexity of the size operation for each of the implementations if there were not a count variable? Without keeping track of the number of elements in the list explicitly, it would have to be determined when the size method is called, which would require traversing the list, counting the elements. Therefore, size would be O(n).


Java Foundations, 5th Edition EX 15.4.

Exercise Solutions, Ch. 15

In the linked implementation, under what circumstances could the head and tail references be equal? The head and rear references are equal when the list is empty or when it contains one element.

EX 15.5.

In the array implementation, under what circumstances could the rear reference equal 0? The rear index could only be 0 if the list is empty.

EX 15.6.

Hand trace an unordered list through the following operations. No solution is provided for this exercise at this time.

EX 15.7.

If there were not a rear variable in the array implementation, how could you detrmine whether or not the list was full? If the integer representing the rear of the list was equal to the array capacity (list.length), then the list array would be full.


Java Foundations, 5th Edition

Exercise Solutions, Ch. 16

Chapter 16 Exercise Solutions EX 16.1

Write a for-each loop that prints all elements in a collection of Student objects called role. What is required for that loop to work? for (Student pupil : role) System.out.println(pupil);

For this code to work, the class that defines the object referenced by role must implement the Iterable interface.

EX 16.2

Write a while loop that uses an explicit iterator to accomplish the same thing as Exercise 16.1. Iterator<Student> itr = role.iterator(); while (itr.hasNext()) System.out.println(itr.next());

EX 16.3

Write a for-each loop that calls the addInterest method on each BankAccount object in a collection called accounts. What is required for that loop to work? for (BankAccount accnt : accounts) accnt.addInterest();

For this code to work, the class that defines the object referenced by accounts must implement the Iterable interface.

EX 16.4

Write a while loop that uses an explicit iterator to accomplish the same thing as Exercise 16.3. Iterator<BankAccount> itr = accounts.iterator(); while (itr.hasNext()) itr.next().addInterest();


Java Foundations, 5th Edition

Exercise Solutions, Ch. 17

Chapter 17 Exercise Solutions EX 17.1

Write a recursive definition of a valid Java identifier. A Java-Identifier is a: Letter or a: Letter followed by a Java-Identifier-Substring A Java-Identifier-Substring is a: Letter or a: Digit or a: Letter followed by a Java-Identifier-Substring or a: Digit followed by a Java-Identifier-Substring

EX 17.2

Write a recursive definition of xy (x raised to the power y), where x and y are integers and y > 0. x1 = x xy = x + xy-1 for y > 1

EX 17.3

Write a recursive definition of i * j (integer multiplication), where i > 0. Define the multiplication process in terms of integer addition. For example, 4 * 7 is equal to 7 added to itself 4 times. 1*j=j i * j = j + (i-1) * j for i > 1

EX 17.4

Write a recursive definition of the Fibonacci numbers, a sequence of integers, each of which is the sum of the previous two numbers. The first two numbers in the sequence are 0 and 1. Explain why you would not normally use recursion to solve this problem. Fib(0) = 0 Fib(1) = 1 Fib(j) = Fib(j-1) + Fib(j-2) for j > 1 You would not normally use recursion to solve this problem because the iterative solution is straightforward and the recursive version is inefficient. Calculating a Fibonacci number less than Fib(j-1) would be calculated at least twice in order to calculate Fib(j). The recalculation of each such number would lead to the further recalculation of other Fibonacci numbers with the accompanying inefficiency.

EX 17.5

Modify the method that calculates the sum of the integers between 1 and N shown in this chapter. Have the new version match the following recursive definition: The sum of 1 to N is the sum of 1 to (N/2) plus the sum of (N/2 + 1) to N. Trace your solution using an N of 7. // Computes the sum of the numbers between n1 and n2 (inc) public int sum (int n1, int n2) { int result; if (n2-n1 == 0)


Java Foundations, 5th Edition

Exercise Solutions, Ch. 17

result = n1; else { int mid = (n1+n2)/2; result = sum(n1, mid) + sum(mid+1, n2); } return result; }

EX 17.6

Write a recursive method that returns the value of N! (N factorial) using the definition given in this chapter. Explain why you would not normally use recursion to solve this problem. public int factorial (int num) { int result; if (num == 1) result = 1; else result = num * factorial (num - 1); return result; } You would not normally use recursion to solve this problem because it can be done more efficiently and because the recursive solution is no more intuitive than the iterative solution.

EX 17.7

Write a recursive method to reverse a string. Explain why you would not normally use recursion to solve this problem. public String reverse (String text) { String result = text; if (text.length() > 1) result = text.charAt(text.length()-1) + reverse (text.substring(0, text.length()-1));


Java Foundations, 5th Edition

Exercise Solutions, Ch. 17

return result; } You would not normally use recursion to solve this problem because it can be done more efficiently using iteration and because the recursive solution is no more intuitive than the iterative solution.

EX 17.8

Design or generate a new maze for the MazeSearch program in this chapter, and rerun the program. Explain the processing in terms of your new maze, giving examples of a path that was tried but failed, a path that was never tried, and the ultimate solution. A new maze could be generated with nested for loops which randomly place either a 1 or a 0 in each cell of a two-dimensional array. Because the likelihood of generating a maze with a solution is generally low, subsequent mazes could be generated using a while loop until a maze with a solution is generated. A maze with a solution could be hard-coded with the following statement: private int [][] grid = {{1,0,1,0,1,1,1,1,1}, {1,0,1,0,1,0,1,0,1}, {1,0,1,0,1,0,1,0,1}, {1,0,1,0,1,0,1,0,1}, {1,0,1,0,1,0,1,0,1}, {1,1,1,0,1,0,1,0,1}, {0,0,1,0,1,0,1,0,1}, {1,0,1,0,1,0,1,0,1}, {1,0,1,0,1,0,1,0,1}, {1,0,1,0,1,0,1,0,1}, {1,0,1,1,1,1,1,0,1}}; After the search arrives at position (5,0), it attempts position (6,0). Encountering a 0 causes this path to fail. It then attempts position (5,1) which succeeds. Subsequently, position (6,1) fails and position (5,2) succeeds.Because the maze is traversed successfully from position (5,2), no attempt is ever made to find a path from position (4,1). The following grid shows the solution path marked with 7s. 7 0 1 0 1 1 7 7 7 7 0 1 0 1 0 7 0 7 7 0 1 0 1 0 7 0 7 7 0 1 0 1 0 7 0 7 7 0 1 0 1 0 7 0 7 7 7 7 0 1 0 7 0 7 0 0 7 0 1 0 7 0 7 1 0 7 0 1 0 7 0 7 1 0 7 0 1 0 7 0 7 1 0 7 0 1 0 7 0 7 1 0 7 7 7 7 7 0 7


Java Foundations, 5th Edition EX 17.9

Exercise Solutions, Ch. 17

Annotate the lines of output of the SolveTowers program in this chapter to show the recursive steps. Move one disk from 1 to 2 // called with numDisks = 1 Move one disk from 1 to 3 // called with numDisks = 2 Move one disk from 2 to 3 // called with numDisks = 1 Move one disk from 1 to 2 // called with numDisks = 3 Move one disk from 3 to 1 // called with numDisks = 1 Move one disk from 3 to 2 // called with numDisks = 2 Move one disk from 1 to 2 // called with numDisks = 1 Move one disk from 1 to 3 // called with numDisks = 4 Move one disk from 2 to 3 // called with numDisks = 1 Move one disk from 2 to 1 // called with numDisks = 2 Move one disk from 3 to 1 // called with numDisks = 1 Move one disk from 2 to 3 // called with numDisks = 3 Move one disk from 1 to 2 // called with numDisks = 1 Move one disk from 1 to 3 // called with numDisks = 2 Move one disk from 2 to 3 // called with numDisks = 1 Note the symmetry around the line where a call is made with numDisks = 4.

EX 17.10

EX 17.11

Produce a chart showing the number of moves required to solve the Towers of Hanoi puzzle using the following number of disks: 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, and 25. Disks

Moves

2

3

3

7

4

15

5

31

6

63

7

127

8

255

9

511

10

1023

15

32767

20

1,048,575

25

33,554,431

Determine and explain the order of your solution to Exercise 17.4. You would not normally use recursion to solve this problem because the iterative solution is straightforward and the recursive version is inefficient. Calculating a Fibonacci number less than Fib(j-1) would be calculated at least twice in order to calculate Fib(j). The


Java Foundations, 5th Edition

Exercise Solutions, Ch. 17

recalculation of each such number would lead to the further recalculation of other Fibonacci numbers with the accompanying inefficiency. Expanding the equation illustrates the inefficiency: Fib(j) = Fib(j-1) + Fib(j-2) Fib(j) = Fib(j-2) + Fib(j-3) + Fib(j-3) + Fib(j-4) Fib(j) = Fib(j-3) + Fib(j-4) + Fib(j-4) + Fib(j-5) + Fib(j-4) + Fib(j-5) + Fib(j-5) + Fib(j-6) We can see from this expansion Fib(j-2) gets called twice, Fib(j-3) gets called three times, Fib(j-4) will get called five times, Fib(j-5) will get called eight times and it will only get worse from there! If we look at the number of calls to the functions for some specific numeric examples, we begin to see the pattern: Fib(0) = 0

1 call

Fib(1) = 1

1 call

Fib(2) = Fib(1) + Fib(0)

3 calls

Fib(3) = Fib(2) + Fib(1) = Fib(1) + Fib(0) + 1

5 calls

Fib(4) = Fib(3) + Fib(2) = Fib(2) + Fib(1) + Fib(1) + Fib(0) = Fib(1) + Fib(0) + 1 + 1 + 0

9 calls

Fib(5) = Fib(4) + Fib(3)

15 calls

Fib(6) = Fib(5) + Fib(4)

25 calls

It was not our purpose to derive the exact growth function for this operation but we can see from this growth that the function has time complexity O(2n). EX 17.12

Determine and explain the order of your solution to Exercise 17.5. Using our trace in the solution to Exercise 17.5 as an example, we can see that each time we divide the list in half, it results in twice as many calls to the sum method. We can also reason that it will take logn such divisions until we have lists of length one. Our trace, summing the numbers from 1 to 7 results in 13 calls to the sum method (roughly 2n calls to the sum method). Since the sum method without the recursive portion is O(1), the resulting time complexity would be O(n).

EX 17.13

Determine and explain the order of your solution to Exercise 17.6. You would not normally use recursion to solve this problem because it can be done more efficiently using iteration and because the recursive solution is no more intuitive than the iterative solution. However, since we are subtracting 1 from n each recursive step, we know that we will call the factorial method n times. Give that the rest of the method without the recursive portion is O(1), the resulting time complexity would be O(n).

EX 17.14

Determine the order of the recursive maze solution presented in this chapter. The time complexity of the maze solution is deterimined by looking at the number of potential moves or potential paths through the maze. Given that from any given position within the maze there are 4 potential moves (ignoring edges for the purpose of this reasoning) and that there are n positions in the maze, that yields a time complexity of O(4n). For example, if the starting location were in the middle of the maze, away from an edge, then from that starting location there are four possible moves. From each of those moves there four more possible moves resulting in sixteen possibilities from out starting position. Even though there are some limitations for edges and for not returning to the previous position, the resulting time complexity is still exponential.


Java Foundations, 5th Edition

Exercise Solutions, Ch. 17


Java Foundations, 5th Edition

Exercise Solutions, Ch. 18

Chapter 18 Exercise Solutions EX 18.1.

Compare and contrast the linear search and binary search algorithms by searching for the numbers 45 and 54 in the following list: 3 8 12 34 54 84 91 110 Searching for 45, which isn't in the list, requires eight comparisons in a linear search to exhaust all possibilities, whereas a binary search will determine that the target is not in the list after three comparisons. A linear search will find the value 54 in the list in five comparisons, and a binary search finds it in three comparisons.

EX 18.2.

Using the list from Exercise 18.1, construct a table showing the number of comparisons required to sort that list for each of the sort algoirthms (selection sort, insertion sort, bubble sort, quick sort, and merge sort). Sort Algorithm

Number of Comparisons

Selection sort

7 + 6 + 5 + 4 + 3 + 2 + 1 = 28

Insertion sort

7

Bubble sort

7 + 6 + 5 + 4 + 3 + 2 + 1 = 28

Quick sort

(2+7) + (2+6) + (2+5) + (2+4) + (2+3) + (2+2) = 39

Merge sort

1 + 1 + 2 + 1 + 1 + 2 + 4 = 12

Note that in this problem we are sorting a list that is already sorted. EX 18.3.

Consider the same list from exercise 18.1. What happens to the number of comparisons for each of the sort algorithms if the list is already sorted. The processing of selection and bubble sort, as written, is independent of the original configuration of the items in the list, and therefore remain O(n 2). But given that the data is originally sorted, the inner loop of the insertion sort will only make one comparison for each iteration, giving this situation the best case efficiency of O(n). Because the quick sort algorithm, as written, chooses the first element in the partition as the partition element, each recursive step will only handle one element for an initially sorted list, and the efficiency degrades to the worst case scenario of O(n 2). The merge sort guarantees equal partitions, and is O(n log n) in all cases, including this situation in which the elements are initially sorted.

EX 18.4.

Given the following list: 90 8 7 56

123

235

9

1

653

trace the execution for: a. selection sort Min 1, swap with 90: Min 7, swap with 8: Min 8, swap with 8: Min 9, swap with 56: Min 56, swap with 123: Min 90, swap with 235: Min 123, swap with 123: Min 235, swap with 235:

1 8 7 56 123 235 9 90 1 7 8 56 123 235 9 90 unchanged 1 7 8 9 123 235 56 90 1 7 8 9 56 235 123 90 1 7 8 9 56 90 123 235 unchanged unchanged

653 653 653 653 653


Java Foundations, 5th Edition b. insertion sort Insert 1: Insert 7: Insert 8: Insert 9: Insert 56: Insert 90: Insert 123: Insert 235:

Exercise Solutions, Ch. 18

1 90 8 7 56 123 235 9 1 7 90 8 56 123 235 9 1 7 8 90 56 123 235 9 1 7 8 9 90 56 123 235 1 7 8 9 56 90 123 235 unchanged unchanged unchanged

c. bubble sort After first iteration: After second iteration: After third iteration: After fourth iteration: After fifth iteration: After sixth iteration: After seventh iteration: d. quick sort

e. merge sort

8 7 7 7 7 7 1

7 8 8 8 8 1 7

653 653 653 653 653

56 90 123 9 1 56 90 9 1 123 56 9 1 90 123 9 1 56 90 123 1 9 56 90 123 8 9 56 90 123 8 9 56 90 123

235 235 235 235 235 235 235

653 653 653 653 653 653 653


Java Foundations, 5th Edition EX 18.5.

Exercise Solutions, Ch. 18

Given the resulting sorted list from exercise 18.4, trace the execution for a binary search, searching for the number 235. Given the sorted list: 1 7 8 9 56

90

123

235

653

A binary search for the number 235 would proceed as follows: Range 0-8, Midpoint 4 (56) Range 5-8, Midpoint 6 (123) Range 7-8, Midpoint 7 (235) Target found after three comparisons. EX 18.6.

Draw a UML class diagram for the SortPhoneList program.

EX 18.7.

Hand trace a radix sort for the following list of five-digit student ID numbers, assuming that each digit must be between 1 and 5.

Digit

1s Position

1

22331 32131

2

54312 21212

3

33333 12123

4

13224

5

54355

Digit

10s Position

1

54312 21212

2

13224 12123

3

33333 22331 32131

4 5 Digit

54355 100s Position


Java Foundations, 5th Edition

Exercise Solutions, Ch. 18

1

32131 12123

2

13224 21212

3

54355 33333 22331 54312

4 5 Digit

1,000s Position

1

21212

2

22331 32131 12123

3

33333 13224

4

54355 54312

5 Digit

10,000s Position

1

13224 12123

2

22331 21212

3

33333 32131

4 5

EX 18.8.

54355 54312

What is the time complexity of a radix sort? The time complexity of a radix sort is c * n, or O(n), but only works for specifically designed keys, and degenerates to n2 rather than n if the number of elements and the number of digits in the key are similar in size.


Java Foundations, 5th Edition

Exercise Solutions, Ch. 19

Chapter 19 Exercise Solutions EX 19.1

Develop a pseudocode algorithm for a level-order traversal of a binary tree. Create a new queue(traversalQueue) and add the root to the queue Create a list(resultsList) to hold the resulting traversal While the traversalQueue is not empty { remove the first element from the traversalQueue and add it to the resultList if it has children, add those children to the traversalQueue } return the resultList

EX 19.2

Draw either a matrilineage (following your mother’s lineage) or a patrilineage (following your father’s lineage) diagram for a couple of generations. Develop a pseudocode algorithm for inserting a person into their proper place in the tree. The answer to this question will unique for each student.

EX 19.3

Develop a pseudocode algorithm to build an expression tree from a prefix expression. Create an expressiontree stack Create an operator stack While there is input { get the next term if the term is an operand { create a node object containing the operand push it on the expression tree stack } else if the term is an operator { push it on the operator stack } } While the operator stack is not empty { pop one operator from the operator stack pop two nodes from the expression tree stack create a new node object containing the operator and pointing to the two nodes push the resulting node onto the expression tree stack } At the conclusion of this algorithm, there should be a single node on the expression tree stack and it will be the root of the expression tree.


Java Foundations, 5th Edition

EX 19.4

Exercise Solutions, Ch. 19

Develop a pseudocode algorithm to build an expression tree from an infix expression. This algorithm handles infix expressions without parenthesis or brackets Create an expression tree stack Create an operator stack Create a postfix string While there is input remaining { get the next term if the term is an operand { create a node containing the operand push the node onto the expression tree stack } else if the term is an operator and the operator stack is empty push the operator onto the operator stack else if the term is an operator and the operator stack is not empty { While the operator stack is not empty and the operator has precedence over the one on top of the stack { pop the operator off of the operator stack pop two nodes off of the expression tree stack create a new node containing the operator and pointing to the two nodes push the new node onto the expression tree stack } push the operator onto the operator stack } While the operator stack is not empty { pop the operator off of the operator stack pop two nodes off of the expression tree stack create a new node containing the operator and pointing to the two nodes push the new node onto the expression tree stack } At the conclusion of this algorithm, there should be a single node on the expression tree stack and it will be the root of the expression tree.

EX 19.5

Calculate the time complexity of the find method. Because there is no inherent relationships among the elements in a binary tree, the search is essentially a linear search through the nodes of the tree, first moving recursively down the left path, then down the right. The complexity of this operation is O(n).

EX 19.6

Calculate the time complexity of the iteratorInOrder method. Like the find operation, the iteratorInOrder operation visits every node in the tree recursively without duplication. The complexity is therefore O(n).

EX 19.7

Develop a pseudocode algorithm for the size method assuming that there is not a count variable.


Java Foundations, 5th Edition

Exercise Solutions, Ch. 19

Such an algorithm could simply use the iteratorInOrder operation to visit and count each node. EX 19.8

Develop a pseudocode algorithm for the isEmpty operation assuming that there is not a count variable. return root == null;

EX 19.9

Draw an expression tree for the expression (9 + 4) * 5 + (4 - (6 - 3)).

+

*

+

9

-

5

4

-

4

6

3


Java Founations, 5th Edition

Exercise Solutions, Ch. 20

Chapter 20 Exercise Solutions EX 20.1.

Draw the binary search tree that results from adding the following integers (34 45 3 87 65 32 1 12 17). Assume our simple implementation with no balancing mechanism.

EX 20.2.

Starting with the result from Exercise 20.1, draw the tree that results from removing (45 12 1), again using our simple implementation with no balancing mechanism.

EX 20.3.

Repeat Exercise 20.1, this time assuming an AVL tree. Include the balance factors in your drawing.

Answer on following page.


Java Founations, 5th Edition

Exercise Solutions, Ch. 20


Java Founations, 5th Edition

Exercise Solutions, Ch. 20

EX 20.4.

Repeat Exercise 20.2, this time assuming an AVL tree and using the result of Exercise 20.3 as a starting point. Include the balance factors in your drawing.

EX 20.5.

Repeat Exercise 20.1, this time assuming a red/black tree. Label each node with its color.

Answer not provided.

EX 20.6.

Repeat Exercise 20.2, this time assuming a red/black tree and using the result of Exercise 20.5 as a starting point. Label each node with its color.

Answer not provided.


Java Founations, 5th Edition EX 20.7.

Starting with an empty red/black tree, draw the tree after insertion and before rebalancing, and after rebalancing (if necessary) fo the following series of inserts and removals.

Answer not provided.

EX 20.8.

Exercise Solutions, Ch. 20

Repeat Exercise 20.7, this time with an AVL tree.

Answer not provided.


Java Foundations, 5th Edition

Exercise Solutions, Ch. 21

Chapter 21 Exercise Solutions EX 21.1

Draw the heap that results from adding the following integers (34 45 3 87 65 32 1 12 17). 1

12

17

87

EX 21.2

3

65

34

32

45

Starting with the resulting tree from Exercise 21.1, draw the tree that results from performing a removeMin operation. 3

12

17

32

65

34

45

87

EX 21.3

Starting with an empty minheap, draw the heap after each of the following operations: addElement(40); addElement(25): removeMin(); addElement(10); removeMin(); addElement(5); addElement(1); removeMin(); addElement(45); addElement(50);

Answer on next page.

After the first two addElement operations:


Java Foundations, 5th Edition

Exercise Solutions, Ch. 21

25

40

After removing the minimum and adding the element 10: 10

40

After removing the minimum and adding the elements 5 and 1: 1

40

5

After removing the minimum and adding the elements 45 and 50: 5

40

45

50

EX 21.4

Repeat Exercise 21.3, this time with maxheap. To use a maxheap, we will assume that the removeMin operations are removeMax. After the first two addElement operations: 40

25

After removing the maximum and adding the element 10: 25

10


Java Foundations, 5th Edition

Exercise Solutions, Ch. 21

After removing the maximum and adding the elements 5 and 1: 10

5

1

After removing the maximum and adding the elements 45 and 50: 50

45

1

5

EX 21.5

EX 21.6

Draw the UML description for the PriorityQueue class described in this chapter. BinaryTree ADT

ArrayBinary Tree

HeapADT

ArrayHeap

PriorityQueue Node

PriorityQueue

Draw the UML description for the array implementation of heap described in this chapter. BinaryTree ADT

ArrayBinary Tree

HeapADT

ArrayHeap


Java Foundations, 5th Edition

Exercise Solutions, Ch. 22

Chapter 22 Exercise Solutions EX 22.1

Define the concept of a set. List additional operations that might be considered for a set. A set is a collection of elements with no duplicates. Generally, the elements in sets have no particular order relative to each other and no inherent relationship. Example additional operations that might be considered for a set might include viewing a random element from the set without removing it, checking to see if a particular subset of elements exist within the set, or an implementation of an intersection operation.

EX 22.2

The TreeSet class is built upon a backing instance of the TreeMap class. Discuss the advantages and disadvantages of this strategy for reuse. By using a TreeMap to implement the TreeSet class, much of the common functionality can be shared. The TreeMap has more complex functionality, but by keeping it constrained to one set of values it eliminates the need for a second full implementation.

EX 22.3

Given the nature of a set, one could implement the Set interface using any one of a variety of other collections or data structures. Describe how you might implement the Set interface using a LinkedList. Discuss the advantages and disadvantages of this approach. A LinkedList would be a fairly straightforward implementation, although not particularly efficient, strategy for a set. The add method would check for duplicates and only add unique items. Otherwise, most operations could come directly from the list implementation. However, the operations are not nearly as efficient as the tree-based solutions in the API.

EX 22.4

A bag is a very similar construct to a set except that duplicates are allowed in a bag. What changes would have to be made to extend a TreeSet to create an implementation of a bag? The primary change would be to remove the duplicate restriction in the add method. Since the addAll method, and then indirectly the union method, use the add method, this one change will allow duplicates. The definitions of other methods would need to be examined as well. For example, should the remove method delete the first occurrence of an element or all occurences of an element?

EX 22.5

Draw a UML diagram showing the relationships among the classes involved in the Product Sales example from this chapter. The answer to this exercise is currently not provided.

EX 22.6

Draw a UML diagram showing the relationships among the classes involved in the User Management example from this chapter. The answer to this exercise is currently not provided.

EX 22.7

Describe two hashing functions that might be appropriate for a data set organized by name (e.g. last name, first name, middle initial).


Java Foundations, 5th Edition

Exercise Solutions, Ch. 22

The answer to this exercise is currently not provided. EX 22.8

Explain when it might be preferable to use a map instead of a set. Maps are particularly helpful for relating keys and values, whereas sets focus on containment in one large group. If the goal is to look up information by some id, a map will serve better. A set would be better for, say, seeing if a product is part of the currently available items.


Java Foundations, 4th Edition

Exercise Solutions, Ch. 23

Chapter 23 Exercise Solutions EX 23.1.

Draw the 2-3 tree that results from adding the following elements into an initially empty tree: 34 45 3 87 65 32 1 12 17

EX 23.2.

Using the resulting tree from Exercise 23.1, draw the resulting tree after removing each of the following elements: 3 87 12 17 45

This exercise solution is not provided at this time.

EX 23.3.

Repeat Exercise 23.1 using a 2-4 tree.

EX 23.4.

Repeat Exercise 23.2 using the resulting 2-4 tree from Exercise 23.3.


Java Foundations, 4th Edition EX 23.5.

Exercise Solutions, Ch. 23

Draw the B-tree of order 8 that results from adding the following elemets into an initially empty tree: 34 45 3 87 65 32 1 12 17 33 55 23 67 15 39 11 19 47

This exercise solution is not provided at this time.

EX 23.6.

Draw the B-tree that results from removing the following from the resulting tree from Exercise 23.5: 1 12 17 33 55 23 19 47

This exercise solution is not provided at this time.

EX 23.7.

Describe the complexity (order) of insertion into a B-tree. The power of a B-tree is in it's flatness. An insertion causes a ripple effect no more than the height of the tree. So the complexity of an insertion is O(log n).

EX 23.8.

Describe the complexity (order) of deletion from a B-tree.

Like insertion, the complexity of deletion from a B-tree is logarithmic. That is, O(log n). Because the ripple effect of a deletion affects no more than one path from the root to a leaf, the complexity is equal to the height of the tree, which is log n for a tree of n nodes.


Java Foundations, 5th Edition

Exercise Solutions, Ch. 24

Chapter 24 Exercise Solutions EX 24.1

Draw the undirected graph that is represented by the following: vertices: 1, 2, 3, 4, 5, 6, 7 edges: (1, 2), (1, 4), (2, 3), (2, 4), (3, 7), (4, 7), (4, 6), (5, 6), (5, 7), (6, 7)

EX 24.2

Is the graph from Exercise 24.1 connected? Is it complete? This graph is connected because there is a path from each node to every other node. It is not complete because each node is not directly connected to all others.

EX 24.3

List all of the cycles in the graph from Exercise 24.1. 1, 4, 2, 1 1, 4, 7, 3, 2, 1 1, 4, 6, 7, 3, 2, 1 1, 4, 6, 5, 7, 3, 2, 1 2, 4, 7, 3, 2 2, 4, 6, 7, 3, 2 2, 4, 6, 5, 7, 3, 2 4, 6, 7, 4 4, 6, 5, 7, 4 5, 6, 7, 5 Any of these cycles may be started from any vertex in the cycle.

EX 24.4

Draw a spanning tree for the graph of Exercise 24.1. One possible spanning tree:


Java Foundations, 5th Edition

Exercise Solutions, Ch. 24

EX 24.5

Using the same data from Exercise 24.1, draw the resulting directed graph.

EX 24.6

Is the directed graph of Exercise 24.5 connected? Is it complete? This directed graph is not connected because there are not paths from each node to every other. For example, there is no path from any node to vertex 5. This graph is not complete because each node is not directly connected to all others.

EX 24.7

List all of the cycles in the graph of Exercise 24.5. There are no cycles in this directed graph.

EX 24.8

Draw a spanning tree for the graph of Exercise 24.5. There is no spanning tree for this directed graph.

EX 24.9

Consider the weighted graph shown in Figure 24.12. List all of the possible paths from vertex 2 to vertex 3 along with the total weight of each path. (Note: The textbook exercise incorrectly references Figure 24.10.) 2, 5, 3

Weight: 4

2, 4, 3

Weight: 19

2, 1, 4, 3

Weight: 29


Java Foundations, 5th Edition

Exercise Solutions, Ch. 25

Chapter 25 Exercise Solutions EX 25.1

Design a table for storing the names and contact information (addresses, phone numbers, email addresses) of your closest friends and family. What fields would you use? Fields: firstName, lastName, streetAddress, city, state, zipCode, phone, email

EX 25.2

Design one or more tables for managing a list of courses run by your university. How many tables do you need? What fields are in each table? Be sure to include such data as the instructor’s names, number of credits, department that offers the course, and the current enrollment in the course. Table: Course; Fields: number, name, description, credits, department, enrollment, instructorId Table: Instructor; Fields: id, firstName, lastName, department

EX 25.3

Research the SQL statements needed to perform the CRUD operations on an Oracle database, Access database, and PostgreSQL database. How do they differ from those presented in this chapter? The solution for this exercise is not currently provided.

EX 25.4

Using the MySQL documentation (http://dev.mysql.com/doc), determine how to create a temporary table, and what the implications are of using a temporary table. Temporary tables are created explicitly using the CREATE TEMPORARY TABLE command. They are not permanent and will not be available after the current connection expires. This allows two connections to make use of the same table (conceptually) without conflict.

EX 25.5

How would you go about modifying a table and adding a new column in front of an existing one? The solution for this exercise is not currently provided.

EX 25.6

What is the SQL statement needed to add a new column named employeeNumber to a table named Employees? Assume that the employeeNumber is a 7 digit integer value. ALTER TABLE Employees ADD employeeNumber INT;

EX 25.7

What is the SQL statement needed to delete a column named ProductCode from a table named Products? ALTER TABLE Products DROP ProductCode;

EX 25.8

Given the Person and Location tables provided at the start of the chapter, what is the SQL statement needed to return a query that lists all of the states that


Java Foundations, 5th Edition

Exercise Solutions, Ch. 25

any person resides in? SELECT state FROM Location WHERE locationId = Person.locationID;

EX 25.9

What is the SQL statement needed to insert a new field in the Student table that would store the total number of credits each student has accumulated? What data type should we use, and why? ALTER TABLE Student ADD credits TINYINT; A TINYINT can be used because the number of credits a student has remains a relatively small number.

EX 25.10

What is the SQL statement required to delete the age column from the Student table discussed earlier in the chapter? ALTER TABLE Student DROP age;


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.