Java Software Solutions, 9th edition John Lewis Solution Manual

Page 1

Java Software Solutions, 9th edition BY John Lewis

Email: Richard@qwconsultancy.com


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 1

Chapter 1 Exercise Solutions EX 1.1.

Describe the hardware components of your personal computer or of a computer in a lab to which you have access. Include the processor type and speed, storage capacities of main and secondary memory, and types of I/O devices. Explain how you determined your answers. One possible description: Processor: Intel Celeron D, 2.53 GHz Main Memory: 2 GB SDRAM Secondary Memory: 500 GB Ultra ATA Hard Drive Peripherals: CD/DVD +/- RW, keyboard, mouse, 17" flat screen monitor, HP LaserJet printer To find the processor and memory information, I accessed the System Information from the control panel. To find the I/O devices, I looked in the device manager.

EX 1.2.

Why do we use the binary number system to store information on a computer? Devices that store and move information are less expensive and more reliable if they have to represent only one of two possible values or states.

EX 1.3.

How many unique items can be represented with each of the following?

a. 1 bit 2 items b. 3 bits 8 items c. 6 bits 64 items d. 8 bits 256 items e. 10 bits 1024 items f.

16 bits 16,348 items

EX 1.4.

If a picture is made up of 128 possible colors, how many bits would be needed to store each pixel of the picture? Why? Seven bits are needed to represent each pixel if each pixel can have up to 128 possible colors. This is because there are 128 distinct permutations of 7 bits.

EX 1.5.

If a language uses 240 unique letters and symbols, how many bits would be needed to store each character of a document? Why? Eight bits are needed to store each character of a document written in a language of 240 unique characters and symbols. Seven bits would be sufficient if there were only 128 different characters to represent. Eight bits is sufficient for 256 different characters.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 1

Because 240 is greater than 128, but not greater than 256, at least 8 bits are needed if all characters are represented by the same number of bits. EX 1.6.

How many bits are there in each of the following? How many bytes are there in each?

a. 12 KB 12 KB = 12 x 1024 bytes = 12,288 bytes = 98,304 bits b. 5 MB 5 MB = 5 x 1,048,576 bytes = 5,242,880 bytes = 41,943,040 bits c. 3 GB 3 GB = 3 x 1,703,741,824 bytes = 5,111,225,472 bytes = 40,889,803,776 bits d. 2 TB 2 TB = 2 x 1,099,511,627,776 bytes = 2,199,023,255,552 bytes = approximately 1.76 x 13 10 bits EX 1.7.

Explain the difference between random-access memory (RAM) and read-only memory (ROM). Both RAM and ROM are random access devices. RAM (Random Access Memory) can be written to and read from, but ROM (Read-Only Memory) can only be read from.

EX 1.8.

A disk is a random-access device but it is not RAM (random-access memory). Explain. The data on both can be accessed diretly (without reading intervening data). But RAM typically refers to a set of chips that make up main memory, whereas a disk is considered secondary memory. RAM is volatile, and a disk is not.

EX 1.9.

Determine how your computer, or a computer in a lab to which you have access, is connected to others across a network. Is it linked to the Internet? Draw a diagram to show the basic connections in your environment. The computers in our lab are connected to a local area network, which is connected to the Internet. (diagram not provided)

EX 1.10. Explain the differences between a local-area network (LAN) and a wide-area network (WAN). What is the relationship between them? A LAN is designed to span a short distance and to connect a relatively small number of computers. A WAN connects two or more LANs, typically across longer distances such as throughout a group of buildings. EX 1.11. What is the total number of communication lines needed for a fully connected point-to-point network of eight computers? Nine computers? Ten computers? What is a general formula for determining this result? Eight computers: 28 communication lines Nine computers: 36 communication lines Ten computers: 45 communication lines General formula for n computers: n(n-1)/2, which represents the sum of the numbers between 1 and n-1.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 1

EX 1.12. Explain the difference between the Internet and the World Wide Web. The Internet is a network of networks. The World Wide Web is based on a set of software applications that facilitates sharing of information across a network. EX 1.13. List and explain the parts of the URLs for: a. your school http://www.byu.edu, where http stands for HyperText Transfer Protocol, which determines the way the browser should communicate; the machine referenced is www, a typical reference to a Web server; the domain is byu.edu where byu stands for Brigham Young University, and edu indicates that it is an educational institution. b. the Computer Science department of your school http://www.cs.byu.edu, in which cs refers to the subdomain within the larger byu.edu domain. So in this case the www machine refers to the standard web server designated by the cs department. c. your instructor's Web page http://www.cs.byu.edu/rpburton/info.html/, which refers to a specific file, rpburton/info.html, located on the computer science web server to be transferred to the user's browser for viewing. EX 1.14. 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. 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. EX 1.15. 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.16. Why are the following valid Java identifiers not considered good identifiers?


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 1

a. q The identifier q is a meaningless name. b. totVal The idetnifier totalValue would be more meaningful than the abbreviation. c. theNextValueInTheList Unnecessarily lengthy; nextValue would serve as well. EX 1.17. 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. EX 1.18. What is a Java Virtual Machine? Explain its role. A Java Virtual Machine (JVM) is a software interpreter that executes Java bytecode. Since bytecode is a low-level representation of a program, but not tied to any particular hardware architecture, any computer with a JVM can execute Java code, no matter what machine it was compiled on. That makes Java architecture-neutral, and therefore highly portable. EX 1.19. 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.20. 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 (


th

Java Software Solutions, 9 Edition A compile-time error

Exercise Solutions, Ch. 1


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 2

Chapter 2 Exercise Solutions EX 2.1.

What is the difference between the literals 4, 4.0, '4', and "4"? The literal 4 is an integer literal, with no fractional part. The literal 4.0 is a floating-point literal. The literal '4' reprsents the digit as a character. Using double quotes in the literal "4" make it a String literal. The first three are primitive literals. The last one represents a String object.

EX 2.2.

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 string, enclosed in parentheses and quotation marks, which it displays on the monitor.

EX 2.3.

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.4.

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 using the string concatenation operator (+) or by using a print statement for part of the string and a println statement for the remainder of the string.

EX 2.5.

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 concatenated with the integer 50; since one of the operands associated with the “+” operator is a string, the result is a string. Then the string “50 plus 25 is 50” is concatenated with the integer 25, with similar results.

EX 2.6.

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\"");


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 2

The output produced is: He thrusts his fists against the post and still insists 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.7.

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.8.

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.9.

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.10. Write four different program statements that increment the value of an integer variable total. total = total + 1; total += 1; total++; ++total; EX 2.11. 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;


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 2

fResult is assigned 5.0 c. iResult = num3 / num4; iResult is assigned 3 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.12. 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


th

Java Software Solutions, 9 Edition c. a + b / c / d 3 1 2 d. a + b / c * d 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


th

Java Software Solutions, 9 Edition

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.

th

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

EX 3.3.

Declare a String variable named str and initialize it to contain the same characters as a String object called name, except in all uppercase characters. String str = name.toUpperCase();

EX 3.4.

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.5.

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.6.

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.7.

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(12) + 2 2 to 13, inclusive d. generator.nextInt(35) + 10


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 3

10 to 44, inclusive e. generator.nextInt(100) – 50 -50 to 49, inclusive

EX 3.8.

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 400 rand.nextInt(401) c. 1 to 10 rand.nextInt(10) + 1 d. 1 to 400 rand.nextInt(400) + 1 e. 25 to 50 rand.nextInt(26) + 25 f.

EX 3.9.

–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.sqr(num1 + num2);

EX 3.10. Write a single statement that computes and prints the absolute value of total. System.out.println(Math.abs(total)); EX 3.11. 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.12. 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)));


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 3

EX 3.13. Write a declaration for an enumerated type that represents the days of the week. enum Days {sunday, monday, tuesday, wednesday, thursday, friday, saturday} EX 3.14. Compare and contrast a traditional coordinate system and the coordinate system used by Java graphical components. A traditional coordinate system has the origin in the lower-left corner, with x increasing to the right and y increasing upward. The coordinate system used by Java has the origin in the upper-left corner with x increasing to the right and y increasing downward. EX 3.15. Write a declaration for each of the following: a. A line that extends from point (60, 100) to point (30, 90) Line line = new Line(60, 100, 30, 90); b. A rectangle that is 20 pixels wide, 100 pixels high, and has its upper-left corner at point (10, 10). Rectangle rect = new Rectangle(10, 10, 20, 100); c. A circle that is centered at point (50, 75) and has a radius of 30. Circle circle = new Circle(50, 75, 30); d. An ellipse that is centered at point (150, 180) and is 100 pixels wide and 80 pixels high. Ellipse ellipse = new Ellipse(150, 180, 50, 40); EX 3.16. Are the following lines hirizontal, vertical, or neither? a. new Line(30, 90, 30, 10) vertical b. new Line(85, 70, 70, 85) neither c. new Line(20, 40, 150, 40) horizontal EX 3.17. Is each of the following ellipses wider than it is tall or taller than it is wide? a. new Ellipse(300, 100, 50, 10) wider than it is tall b. new Ellipse (100, 200, 20, 40) taller than it is wide c. new Ellipse (150, 220, 60, 30) wider than it is tall EX 3.18. How do you make a shape that has no fill color, so tht you can see the elements behind it? Set its fill color to null: circle.setFill(null); EX 3.19. Write a line of code that rotates an ellipse called myEllipse 45 degrees clockwise.


th

Java Software Solutions, 9 Edition myEllipse.setRotate(45);

Exercise Solutions, Ch. 3


h

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 4

Chapter 4 Exercise Solutions EX 4.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 4.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 4.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 4.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 4.5.

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."); 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.");


h

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 4

} EX 4.6.

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 4.7.

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 4.8.

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 4.9.

Write a method called randomColor that creates and returns a Color object that represents a random color. Recall that a Color object can be defined by three integer values between 0 and 255 representing the contributions of red, green, and blue (its RGB value). final int MAX = 256; public Color randomColor() { Random generator = new Random(); int randRed = generator.nextInt(MAX); int randGreen = generator.nextInt(MAX); int randBlue = generator.nextInt(MAX); return new Color.rgb(randRed, randGreen, randBlue); }

EX 4.10. Suppose you have a class called Movie. Write a constructor for the class that initializes the title and director instance variables based on parameters passed to the constructor.


h

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 4

public Movie(String theTitle, String theDirector) { title = theTitle; director = theDirector; } EX 4.11. Suppose you have a class called Child with an instance data value called age. Write a getter method and a setter method for age. public int getAge() { return age; } public void setAge(int newAge) { age = newAge; } EX 4.12. Draw a UML class diagram that shows the relationships among the classes used in the Transactions program.

EX 4.13. Write a declaration that creates an Arc object that is centered at point (50, 50) and sweeps across the top half of the underlying ellipse. Base it on an ellipse with a horizontal radius of 40 and a vertical radius of 100. Arc arc = new Arc(50, 50, 40, 100, 0, 180); EX 4.14. How do you restrict the pixels displayed of an image? By setting a rectangular viewport on the image view that displays it. EX 4.15. What is the purpose of a layout pane? A layout pane is used to organize the visual presentation of the elements in a JavaFX node. For example, a GridPane lays out its elements in a rectangular grid. EX 4.16. How can a method reference be used to define an event handler?


h

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 4

The parameter to a method such as setOnAction is an event handler object. That parameter could also be a method reference that specifies a particular method to be used as the event handler method that is called when the event occurs. For example: button.setOnAction(this::processButtonClick);


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 5

Chapter 5 Exercise Solutions EX 5.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 5.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 5.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 5.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:


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 5

apple orange pear EX 5.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 5.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"


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 5

"Lucy" "^^^^^^^^^^" "book" "bookkeeper" "fred" "hephalump" "ricky" "{([])}" EX 5.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 5.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 5.9

What is wrong with the following code fragment? What are three distinct ways it could be changed to remove the flaw? count = 50;


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 5

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 5.10 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 5.11 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(); } EX 5.12 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; }


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 5

Note that the method Math.max also performs this function. EX 5.13 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.14 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; } EX 5.15 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.16 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.17 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)


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 5

{ boolean result = false; if ( (side1 == side2) && side1 != side3) || (side2 == side3) && side2 != side1) || (side1 == side3) && side1 != side2) ) result = true; return result; } EX 5.18 Would it be better to use check boxes or radio buttons to determine the following? Explain. a. Your favorite book genre. radio buttons – favorite implies only one should be chosen b. Whether to make your profile visible or not. check box – with only one option there is no mutual exclusion involved c. Which image format to use (jpg, png, or gif). radio buttons – only one should be slected d. Which programming languages you know. check boxes – multiple options may be valid


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 6

Chapter 6 Exercise Solutions EX 6.1. How many iterations will the following for loops execute? a. for (int i = 0; i < 20; i++) { } 20 iterations b. for (int i = 1; i <= 20; i++) { } 20 iterations c. for (int i = 5; i < 20; i++) { } 15 iterations d. for (int i = 20; i > 0; i--) { } 20 iterations e. for (int i = 1; i < 20; i = i + 2) { } 10 iterations f. for (int i = 1; i < 20; i *= 2) { } 5 iterations EX 6.2. What output is produced by the following code fragment? for (int num = 0; num <= 200; num += 2) System.out.println(num); The output produced is the even numbers from 0 to 200: 0 2 4 and so on until… 198 200 EX 6.3. 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


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 6

EX 6.4. 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 6.5. Transform the while loop from the previous exercise into an equivalent for loop (make sure it produces the same output). for (int num = 2; num <= 20; num ++) System.out.println(num); EX 6.6. 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 6.7. 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 6.8. 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 6.9. 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();


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 6

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 6.10. Write a code fragment that determines and prints the number of times the character 'a' appears in a String object called name. int count = 0; for (int index = 0; index < name.length(); index++) if (name.charAt(index) == 'a') count++; System.out.println("The character \'a\' appears " + count + " time(s)"); EX 6.11. Write a code fragment that prints the characters stored in a String object called str backwards. for (int index = str.length()-1; index >= 0; index--) System.out.print(str.charAt(index)); System.out.println(); EX 6.12. 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)); EX 6.13. 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; for (int power = 1; power <= 10; power++) { num *= 2; System.out.println(num); }


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 6

} EX 6.14. 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 6.15. 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 6.16. 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). 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 6.17. 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;


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 6

for (int index = 0; index < text.length(); index++) if (text.charAt(index) == 'A') count++; return count; } EX 6.18. 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 6.19. In the Bullseye program, what is the fill color of the innermost circle before it is changed to red? Explain. The innermost circle is initially white before it is changed to red. The colors alternate, and the previous color was black. EX 6.20. Given the way the Boxes program is written, what color will a rectangle be if it is both narrow and short? Explain. A box that is both narrow and short will be colored yellow because that's the characteristic that is checked first. If the box is norrow, the height of the box is not checked. EX 6.21. Rewrite the if statement used in the Boxes program so that if a box is both narrow and short, its fill color will be orange. Otherwise, keep narrow boxes yellow and short boxes green. if (width < 10 && height < 10) fill = Color.ORANGE; else if (width < 10) fill = Color.YELLOW; else if (height < 10) fill = Color.GREEN; EX 6.22. Write code that will shift a Rectangle named rec 50 pixels right and 10 pixels down, rotate it 45 degrees clockwise, and display it at half its original size. rec.setTranslateX(50); rec.setTranslateY(10); rec.setScaleX(0.5);


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 6

rec.setScaleY(0.5); EX 6.23. Write code that will invert (turn upside down) an ImageView named pic and display it at twice its original size. pic.setRotate(180); pic.setScaleX(2.0); pic.setScaleY(2.0); EX 6.24.

What happens when you apply a transformation to a group? The transformation is applied to each node in the group.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 7

Chapter 7 Exercise Solutions EX 7.1. 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 7.2. Overload the average method of Exercise 7.1 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 7.3. Overload the average method of Exercise 7.1 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 7.4. 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 (repeats > 1) for (int i=2; i <= count; i++) result += text; return result; } EX 7.5. Overload the multiConcat method from Exercise 7.4 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;


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 7

} EX 7.6. Write a method called makeCircle that returns a new Circle object based on the method's parameters: two integer values representing the (x, y) coordinates of the center of the circle, an integer that represents the circle's radius, and a Color object that defines the circle's fill color. public void makeCircle(int centerX, int centerY, int radius, Color color) { Circle circle = new Circle(centerX, centerY, radius); circle.setFill(color); return circle; } EX 7.7. Overload the makeCircle method of Exercise 7.6 such that if the Color parameter is not provided, the circle's color will default to red. public void makeCircle(int centerX, int centerY, int radius) { Circle circle = new Circle(centerX, centerY, radius); circle.setFill(Color.RED); return circle; } EX 7.8. Overload the makeCircle method of Exercise 7.6 such that if the radius is not provided, a random radius in the range 10 to 20 will be used. public void makeCircle(int centerX, int centerY, Color color) { Random generator = new Random(); int radius = generator.nextInt(11) + 10; Circle circle = new Circle(centerX, centerY, radius); circle.setFill(color); return circle; } EX 7.9. Overload the makeCircle method of Exercise 7.6 such that if both the color and the radius of the circle are not provided, the color will default to green and the radius will default to 40. public void makeCircle(int centerX, int centerY) { Circle circle = new Circle(centerX, centerY, 40); circle.setFill(Color.GREEN); return circle; }


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 7

EX 7.10. 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 7.11.

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 7.12. 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. EX 7.13. 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(); } 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 7.14. Draw a UML class diagram that shows the relationships among the elements of the previous exercise.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 7

EX 7.15. Imagine a game in which some game elements can be broken by the player and others can't. Create an interface called Breakable that has a method called break that takes no parameters and another called broken that returns a boolean result indicating whether the object is currently broken. public interface Breakable { public void break(); public boolean broken(); } EX 7.16. Create an interface called VCR that has methods that represent the standard operations on a video cassette recorder (play, stop, etc.). Define the method signatures any way you desire. Describe how a class might implement this interface. public interface VCR { public String play(); public String stop(); public String record(int start, int end); public String pause(); } A class implementing VCR would include an implements clause in the class header, such as: public class MyVCR implements VCR The class would contain, among other things, four methods with signatures that match those specified in the interface. EX 7.17. Draw a UML class diagram that shows the relationships among the elements of the Exercise 7.16.

EX 7.18.

Compare and contrast a mouse clicked event and a key typed event.

Both types of events can originate from any JavaFX node. The node must have the keyboard focus for key events to be recognized. Both types of events correspond to user actions, but not explicitly to visual controls on the screen per se. When either event happens, multiple events are generated: clicking the mouse button generates mouse pressed, mouse released, and mouse clicked events. Tying a keyboard key generates key pressed, key released, and key typed events. EX 7.19.

What is rubberbanding? How can it be accomplished?


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 7

Rubberbanding is the visual effect created when the user can seemingly drag a shape into existence. The shape grows while the mouse is dragged. This effect can be accompished by constantly updating the shapes characteristics in response to rapid-fire mouse dragged events.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 8

Chapter 8 Exercise Solutions EX 8.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 8.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 8.3. Describe how an element in an array is accessed in memory. For example, where is myArray[25] stored in memory? The elements of an array are stored contiguously in memory. The name of an array, such as myArray, is a reference to an object that stores the beginning of that data in memory. To compute the address of a particular element, the address of the first data element is multiplied by the index (25) and the size of the array element. That is why array indexes begin at zero.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 8

EX 8.4. 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]); th

The for loop fails to print the 0 element of the array, and attempts to print the nonexistent th 11 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 8.5. 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


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 8

Employee[]employees = new Employee[MAX]; public class Employee { private int employeeNumber; private String hireDate; private double raise[] = new double[5]; // etc. } EX 8.6. 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 8.7. 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 8.8. 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 8.9. 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 8.10. 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];


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 8

//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++) second[i] = temp[i]; } else System.out.println("Arrays are of different sizes"); } EX 8.11. Describe a program for which you would use the ArrayList class instead of arrays to implement choices. Describe a program for which you would use arrays instead of the ArrayList class. Explain your choices. A program associated with a mail order Website for backpacks would use an object of the ArrayList class to implement the choices of colors of the backpacks because the colors and number of colors change with the seasons and as colors gain and lose popularity. An object of the ArrayList class can grow and shrink dynamically to accommodate these changes. A program associated with a personal day planner, with entries possible for each hour of the day, would use an array object to implement the choices for each hour of the day because the number of hours in a day, and hence the number of hours for which choices can be made for any given day, never changes. There is no need for the array object to grow or shrink to accommodate a larger or smaller number of hours. EX 8.12. The Dots program listens for a mouse pressed event to draw a dot. How would the program behave differently if it listened for a mouse released event instead? A mouse clicked event? If the program listened instead for a mouse released event, the position and appearance of the dot would be determined at the time of the release, and wouldn’t appear until the mouse button was released. Similarly, if the program listened for a mouse clicked event, the position and appearance of the dot would be determined at the time of a click (which requires a press followed by a release). EX 8.13. How would you modify the JukeBox program so that it will play the new song as soon as a combo box item is selected (without having to press the Play button)? Currently, the event handler processing the choice box selection only stops the current song and sets the new current song. To play a new song immediately when it's selected, the following line could be added at the end of the processChoice method: current.play(); EX 8.14. What program modifications would be necessary to add three more songs to the juke box? The program is largely data-driven, so the song names would have to be added to the names array and the corresponding audio files would have to be added to the audioFiles array. The program is designed to work for any size array.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 9

Chapter 9 Exercise Solutions EX 9.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 9.2. Show an alternative diagrm for the hierarchy in Exercise 9.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 Ex. 9.1 might be better suited to a system maintaining the inventory and online shopping for a store, whereas the hierarchy in 9.2, centered around the mounting capabilities, might be better suited to a manufacturing system.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 9

EX 9.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 9.4. Show an alternative diagram for the hierarchy in Exercise 9.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.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 9

The hierarchy in Ex. 9.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 Ex. 9.4 is organized around car type, with the manufacturer as data. Which one would be best depends on the purpose of the system. EX 9.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 9.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.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 9

EX 9.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 9.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? Change the


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 9

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. EX 9.9. Which of the following classes can be used as the root node of a scene in a JavaFX application? What is the determining factor? Only a class derived from the Parent class can serve as the root node of a scene. a. GridPane. Yes. b. Rectangle No. c.

Group

Yes. d. Button Yes. e. ImageView No. EX 9.10.

Describe the role of the Alert class. The Alert class provides support for creating and displaying several basic types of dialog boxes, which provide information, let the user confirm an action, or conveys a warning or error message.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 10

Chapter 10 Exercise Solutions EX 10.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 10.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.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 10

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 10.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 9.7.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 10

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 10.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 10.5. Describe a property binding that you could set up other than the examples used in this chapter. You could bind the property representing the end point of a horizontal line to the width of the scene so that the line is always long enough to span the scene. EX 10.6. Write a statement that would bind the property representing the radius of a Circle object to the property representing the value in a slider. myCircle.radiusProperty().bind(mySlider.valueProperty());


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 11

Chapter 11 Exercise Solutions EX 11.1.

Create a UML class diagram for the ProductCodes program.

EX 11.2. 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 11.3. 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 11.4. 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 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. PatterSyntaxException This exception is thrown when a syntax error occurs in the pattern of a regular expression. EX 11.5. Other than the examples discussed in this chapter, describe a situation in which you might disable control(s) to help guide user actions. You might disable a button used to move to the next step of a process until the current step has been completed or until the data being requested is filled in and validated.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 11

EX 11.6. Explain how the functionality of the FoodImages program would change if the property binding was removed. The property binding binds the width of the image view to the width of the pane in which the image is displayed. So if that properyt binding wasn't set up, the image size would dictate the window size, which might vary from one image to the next.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 12

Chapter 12 Exercise Solutions EX 12.1.

Write a recursive definition of a valid Java identifier (see Chapter 1). 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 y

EX 12.2. Write a recursive definition of x (x raised to the power y), where x and y are integers and y > 0. 1

x =x y

x =x+x

y-1

for y > 1

EX 12.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 12.4. Write a recursive definition of the Fibonacci numbers. The Fibonacci numbers are 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 12.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) result = n1; else {


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 12

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

EX 12.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 using iteration and because the recursive solution it no more intuitive than the iterative solution. EX 12.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)); 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 12.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,


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 12

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 EX 12.9. 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


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 12

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 about the line where a call is made with numDisks = 4. EX 12.10. 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

EX 12.11. How many line segments are used to construct a Koch snowflake of order N? Produce a chart showing the number of line segments that make up a Koch snowflake for orders 1 through 9. A Koch snowflake of order N has 3(4N-1) line segments. Order

Line Segments

1

3

2

12

3

48

4

192

5

768

6

3072

7

12,288

8

49,152

9

196,608


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 13

Chapter 13 Exercise Solutions EX 13.1. Suppose current is a reference to a Node object and that it currently refers to a specific node in a linked list. Show, in pseudocode, the steps that would delete the node following current from the list. Carefully consider the cases in which current is referring to the first and last nodes in the list. if current.next is not null then current.next = current.next.next; endIf Must check for current pointing to the last node in the list (so we don't follow a null reference). In this case, current pointing to the first node in the list is not a special case. EX 13.2. Modify your answer to Exercise 13.1 assuming that the list was set up as a doubly linked list, with both next and prev references. if current.next is not null then current.next = current.next.next; if current.next is not null then current.next.prev = current; endIf endIf EX 13.3. Suppose current and newNode are references to Node objects. Assume current currently refers to a specific node in a linked list and newNode refers to an unattached Node object. Show, in pseudocode, the steps that would insert newNode behind current in the list. Carefully consider the cases in which current is referring to the first and last nodes in the list. newNode.next = current.next; current.next = newNode; The situations of current pointing to the first or last nodes in the list are not special cases for this operation. EX 13.4. Modify your answer to Exercise 13.3 assuming that the list was set up as a doubly linked list, with both next and prev references. newNode.prev = current; newNode.next = current.next; if current.next is not null then current.next.prev = newNode; endIf current.next = newNode; EX 13.5. Would the front and rear references in the header node of a linked list ever refer to the same node? Would they ever both be null? Would one ever be null if the other was not? Explain your answers using examples. The front and rear references in the header node of a linked list would refer to the same node if the list consists of only a single node. They would both be null if the list were empty. One would never be null if the other were not. For example, if the linked list consisted of a single node containing the string “William” and a null next reference (since there is no successor node), both the front and rear references would contain reference


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 13

this node. If the node containing “William” were deleted, both the front and rear references would be set to null. It is impossible to have a list which has a front, but no rear or a rear but no front, thus it is impossible for one reference to be null and the other not. EX 13.6. Show the contents of a queue after the following operations are performed. Assume the queue is initially empty. enqueue(45); 45 enqueue(12); 12 45 enqueue(28); 28 12 45 dequeue(); 28 12 dequeue(); 28 enqueue(69); 69 28 enqueue(27); 27 69 28 enqueue(99); 99 27 69 28 dequeue(); 99 27 69 enqueue(24); 24 99 27 69 enqueue(85); 85 24 99 27 69 enqueue(16); 16 85 24 99 27 69 dequeue(); 16 85 24 99 27 EX 13.7. In terms of the final state of a queue, does it matter how dequeue operations are intermixed with enqueue operations? Does it matter how the enqueue operations are intermixed among themselves? Explain using examples. In terms of the final state of a queue, as long as the number of dequeue opertions does not exceed the number of enqueue operations, the intermixing of these operations does not matter. It does matter, however, how the enqueue operations are intermixed among themselves; an item which arrives earlier moves closer to the front of the queue than an item which arrives later.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 13

As an example of intermixing enqueue and dequeue operations, consider enqueuing six integers such as 2, 3, 5, 7, 11, and 13 and then dequeuing half of them. The resulting queue contains 7, 11, and 13. Alternatively, suppose that the same six integers are enqueued, but every time two integers are enqueued, one is dequeued. The resulting queue contains 7, 11, and 13. Of course, this does not prove than the intermixing of dequeue and enqueue operations is inconsequential; it merely shows that it is inconsequential in this case. On the other hand, if the enqueue operations are intermixed among themselves, such as enqueuing the 13 first and the 2 last (instead of 2 first and 13 last), the resulting queue would contain 7, 11, and 2 (instead of 7, 11, and 13). This single case is sufficient to prove that the intermixing of enqueue operations matters. EX 13.8. Show the contents of a stack after the following operations are performed. Assume the stack is initially empty. push(45); 45 push(12); 45 12 push(28); 45 12 28 pop(); 45 12 pop(); 45 push(69); 45 69 push(27); 45 69 27 push(99); 45 69 27 99 pop(); 45 69 27 push(24); 45 69 27 24 push(85); 45 69 27 24 85 push(16); 45 69 27 24 85 16 pop(); 45 69 27 24 85 EX 13.9. In terms of the final state of a stack, does it matter how the pop operations are intermixed with the push operations? Does it matter how the push operations are intermixed among themselves? Explain using examples.


th

Java Software Solutions, 9 Edition

Exercise Solutions, Ch. 13

In terms of the final state of a stack, the number of pop operations must not exceed the number of push operations, and the intermixing of pop and push operations matters. How the push operations are intermixed among themselves also matters. For example, suppose the six integers 2, 3, 5, 7, 11, and 13 are pushed onto a stack, and then three integers are popped off the stack. The resulting stack contains 2, 3, and 5. Alternatively, suppose that the same six integers are pushed onto the stack, put every time 2 integers are pushed onto the stack, one is popped. The resulting stack contains 2, 5, and 11. This single illustration is sufficient to prove that the intermixing of push and pop operations matters. Similarly, if the 13 is pushed onto the stack first and the 2 is pushed onto the stack last (instead of the 2 first and the 13 last), with no popping, the 2 is at the top of the stack and the 13 is at the bottom of the stack (instead of the 2 at the bottom and the 13 at the top). Again, this single example is sufficient to prove that the intermixing of push operations among themselves matters. EX 13.10. Would a tree data structure be a good choice to represent a family tree that shows lineage? Why or why not? Would a binary tree be a better choice? Why or why not? A binary tree would be a good choice to represent a family tree that shows lineage (ancestors). Everyone you know has exactly two biological parents, as does each of their ancestors, making a binary tree a natural choice. A tree, on the other hand, would not be a particularly good choice, because tree nodes often are designed to accommodate a variable number of references. In this example, the number of references needed is known; it is exactly two. Further, a tree typically is represented as the corresponding binary tree, with some accompanying overhead, so it makes sense to “cut to the chase” when there is no intuitive loss in the representation. EX 13.11. What data structure would be a good choice to represent the links between various web sites of the World Wide Web? Give an example. A digraph (directed graph) would be a good choice to represent the links between various web sites of the World Wide Web. For example, a university’s web site might link to all the department’s web sites, and each of those might link to all of the faculty members web sites in that department. A particular faculty web site might link to a spouse’s web site which links to a son’s web site and back to the faculty member's web site. A linear list cannot accommodate such a complex linking structure. A tree does not accommodate paths that circle their way back to a particular node. A graph accommodates paths than make their way back to a particular node, but a graph assumes that bidirectional links (so if one page A links to page B, then page B links to page A, which may not be the case). Therefore a digraph, with its edges that go in one direction, would be the best choice.


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.