26
Control Flow Practice Problems Mr. Fahrenbacher AP Computer Science A This problem set has four sections. After each section is the answer key. This problem set is NOT exhaustive, but it is too long. Find interesting questions that you want to practice and work on those. Questions Section I 1. Translate each of the following English statements into logical tests that could be used in an if/else statement. Write the appropriate if statement with your logical test. Assume that three int variables, x, y, and z, have been declared. a. z is odd. b. z is not greater than y’s square root. c. y is positive. d. Either x or y is even, and the other is odd. e. y is a multiple of z. f. z is not zero. g. y is greater in magnitude than z. h. x and z are of opposite signs. i. y is a nonnegative one-digit number. j. z is nonnegative. k. x is even. l. x is closer in value to y than z is. 2. Given the variable declarations int x = 4; int y = –3; int z = 4; what are the results of the following relational expressions? a. x == 4 b. x == y c. x == z d. y == z e. x + y > 0 f. x – z != 0 g. y * y <= z h. y / y == 1 i. x * (y + 2) > y - (y + z) * 2 3. Consider the following method:

Self-Check Problems Questions Section I if/else · Self-Check Problems 289 Chapter Summary An if statement lets you write code that will execute only if a certain condition is met

  • Upload
    others

  • View
    61

  • Download
    0

Embed Size (px)

Citation preview

Control Flow Practice ProblemsMr. FahrenbacherAP Computer Science A

This problem set has four sections. After each section is the answer key. This problem set is NOT exhaustive, but it is too long. Find interesting questions that you want to practice and work on those.

Questions Section I

Self-Check Problems 289

Chapter Summary

An if statement lets you write code that will execute onlyif a certain condition is met. An if/else statement letsyou execute one piece of code if a condition is met, andanother if the condition is not met. Conditions are Booleanexpressions and can be written using relational operatorssuch as <, >= , and != . You can test multiple conditionsusing the && and || operators.

You can nest if/else statements to test a series of condi-tions and execute the appropriate block of code on thebasis of whichever condition is true.

The == operator that tests primitive data for equalitydoesn’t behave the way we would expect with objects, sowe test objects for equality by calling their equalsmethod instead.

Common code that appears in every branch of anif/else statement should be factored out so that it is notreplicated multiple times in the code.

Cumulative algorithms compute values incrementally. A cumulative sum loop declares a sum variable and

incrementally adds to that variable’s value inside theloop.

Since the double type does not store all values exactly,small roundoff errors can occur when the computer per-forms calculations on real numbers. Avoid these errors byproviding a small amount of tolerance in your code forvalues near the values that you expect.

The char type represents individual characters of text.Each letter of a String is stored internally as a charvalue, and you can use the String’s charAt method toaccess these characters with an index.

The System.out.printf method prints formatted text.You can specify complex format strings to control the width,alignment, and precision by which values are printed.

You can “throw” (generate) exceptions in your own code.This technique can be useful if your code ever reaches anunrecoverable error condition, such as the passing of aninvalid argument value to a method.

Self-Check Problems

Section 4.1:if/else Statements

1. Translate each of the following English statements into logical tests that could be used in an if/else statement. Writethe appropriate if statement with your logical test. Assume that three int variables, x, y, and z, have been declared.

a. z is odd.b. z is not greater than y’s square root.c. y is positive.d. Either x or y is even, and the other is odd.e. y is a multiple of z.f. z is not zero.g. y is greater in magnitude than z.h. x and z are of opposite signs.i. y is a nonnegative one-digit number.290 Chapter 4 Conditional Execution

j. z is nonnegative.k. x is even.l. x is closer in value to y than z is.

2. Given the variable declarations

int x = 4;

int y = –3;

int z = 4;

what are the results of the following relational expressions?

a. x == 4b. x == yc. x == zd. y == ze. x + y > 0f. x – z != 0

g. y * y <= zh. y / y == 1i. x * (y + 2) > y - (y + z) * 2

3. Consider the following method:

public static void ifElseMystery1(int x, int y) {

int z = 4;

if (z <= x) {

z = x + 1;

} else {

z = z + 9;

}

if (z <= y) {

y++;

}

System.out.println(z + " " + y);

}

What output is produced for each of the following calls?

a. ifElseMystery1(3, 20);b. ifElseMystery1(4, 5);c. ifElseMystery1(5, 5);d. ifElseMystery1(6, 10);

4. Consider the following method:

public static void ifElseMystery2(int a, int b) {

if (a * 2 < b) {

a = a * 3;

} else if (a > b) {

290 Chapter 4 Conditional Execution

j. z is nonnegative.k. x is even.l. x is closer in value to y than z is.

2. Given the variable declarations

int x = 4;

int y = –3;

int z = 4;

what are the results of the following relational expressions?

a. x == 4b. x == yc. x == zd. y == ze. x + y > 0f. x – z != 0

g. y * y <= zh. y / y == 1i. x * (y + 2) > y - (y + z) * 2

3. Consider the following method:

public static void ifElseMystery1(int x, int y) {

int z = 4;

if (z <= x) {

z = x + 1;

} else {

z = z + 9;

}

if (z <= y) {

y++;

}

System.out.println(z + " " + y);

}

What output is produced for each of the following calls?

a. ifElseMystery1(3, 20);b. ifElseMystery1(4, 5);c. ifElseMystery1(5, 5);d. ifElseMystery1(6, 10);

4. Consider the following method:

public static void ifElseMystery2(int a, int b) {

if (a * 2 < b) {

a = a * 3;

} else if (a > b) {

b = b + 3;

}

if (b < a) {

b++;

} else {

a– –;

}

System.out.println(a + " " + b);

}

What output is produced for each of the following calls?

a. ifElseMystery2(10, 2);b. ifElseMystery2(3, 8);c. ifElseMystery2(4, 4);d. ifElseMystery2(10, 30);

5. Write Java code to read an integer from the user, then print even if that number is an even number or odd otherwise.You may assume that the user types a valid integer.

6. The following code contains a logic error:

Scanner console = new Scanner(System.in);

System.out.print("Type a number: ");

int number = console.nextInt();

if (number % 2 == 0) {

if (number % 3 == 0) {

System.out.println("Divisible by 6.");

} else {

System.out.println("Odd.");

}

}

Examine the code and describe a case in which the code would print something that is untrue about the number thatwas entered. Explain why. Then correct the logic error in the code.

7. Describe a problem with the following code:

Scanner console = new Scanner(System.in);

System.out.print("What is your favorite color?");

String name = console.next();

if (name == "blue") {

System.out.println("Mine, too!");

}

8. The following code is poorly structured:

int sum = 1000;

Scanner console = new Scanner(System.in);

System.out.print("Is your money multiplied 1 or 2 times? ");

Self-Check Problems 291

b = b + 3;

}

if (b < a) {

b++;

} else {

a– –;

}

System.out.println(a + " " + b);

}

What output is produced for each of the following calls?

a. ifElseMystery2(10, 2);b. ifElseMystery2(3, 8);c. ifElseMystery2(4, 4);d. ifElseMystery2(10, 30);

5. Write Java code to read an integer from the user, then print even if that number is an even number or odd otherwise.You may assume that the user types a valid integer.

6. The following code contains a logic error:

Scanner console = new Scanner(System.in);

System.out.print("Type a number: ");

int number = console.nextInt();

if (number % 2 == 0) {

if (number % 3 == 0) {

System.out.println("Divisible by 6.");

} else {

System.out.println("Odd.");

}

}

Examine the code and describe a case in which the code would print something that is untrue about the number thatwas entered. Explain why. Then correct the logic error in the code.

7. Describe a problem with the following code:

Scanner console = new Scanner(System.in);

System.out.print("What is your favorite color?");

String name = console.next();

if (name == "blue") {

System.out.println("Mine, too!");

}

8. The following code is poorly structured:

int sum = 1000;

Scanner console = new Scanner(System.in);

System.out.print("Is your money multiplied 1 or 2 times? ");

Self-Check Problems 291

b = b + 3;

}

if (b < a) {

b++;

} else {

a– –;

}

System.out.println(a + " " + b);

}

What output is produced for each of the following calls?

a. ifElseMystery2(10, 2);b. ifElseMystery2(3, 8);c. ifElseMystery2(4, 4);d. ifElseMystery2(10, 30);

5. Write Java code to read an integer from the user, then print even if that number is an even number or odd otherwise.You may assume that the user types a valid integer.

6. The following code contains a logic error:

Scanner console = new Scanner(System.in);

System.out.print("Type a number: ");

int number = console.nextInt();

if (number % 2 == 0) {

if (number % 3 == 0) {

System.out.println("Divisible by 6.");

} else {

System.out.println("Odd.");

}

}

Examine the code and describe a case in which the code would print something that is untrue about the number thatwas entered. Explain why. Then correct the logic error in the code.

7. Describe a problem with the following code:

Scanner console = new Scanner(System.in);

System.out.print("What is your favorite color?");

String name = console.next();

if (name == "blue") {

System.out.println("Mine, too!");

}

8. The following code is poorly structured:

int sum = 1000;

Scanner console = new Scanner(System.in);

System.out.print("Is your money multiplied 1 or 2 times? ");

Self-Check Problems 291

292 Chapter 4 Conditional Execution

int times = console.nextInt();

if (times == 1) {

System.out.print("And how much are you contributing? ");

int donation = console.nextInt();

sum = sum + donation;

count1++;

total = total + donation;

}

if (times == 2) {

System.out.print("And how much are you contributing? ");

int donation = console.nextInt();

sum = sum + 2 * donation;

count2++;

total = total + donation;

}

Rewrite it so that it has a better structure and avoids redundancy. To simplify things, you may assume that theuser always types 1 or 2. (How would the code need to be modified to handle any number that the user mighttype?)

9. The following code is poorly structured:

Scanner console = new Scanner(System.in);

System.out.print("How much will John be spending? ");

double amount = console.nextDouble();

System.out.println();

int numBills1 = (int) (amount / 20.0);

if (numBills1 * 20.0 < amount) {

numBills1++;

}

System.out.print("How much will Jane be spending? ");

amount = console.nextDouble();

System.out.println();

int numBills2 = (int) (amount / 20.0);

if (numBills2 * 20.0 < amount) {

numBills2++;

}

System.out.println("John needs " + numBills1 + " bills");

System.out.println("Jane needs " + numBills2 + " bills");

Rewrite it so that it has a better structure and avoids redundancy. You may wish to introduce a method to helpcapture redundant code.

10. Write a piece of code that reads a shorthand text description of a color and prints the longer equivalent. Acceptable colornames are B for Blue, G for Green, and R for Red. If the user types something other than B, G, or R, the program should

292 Chapter 4 Conditional Execution

int times = console.nextInt();

if (times == 1) {

System.out.print("And how much are you contributing? ");

int donation = console.nextInt();

sum = sum + donation;

count1++;

total = total + donation;

}

if (times == 2) {

System.out.print("And how much are you contributing? ");

int donation = console.nextInt();

sum = sum + 2 * donation;

count2++;

total = total + donation;

}

Rewrite it so that it has a better structure and avoids redundancy. To simplify things, you may assume that theuser always types 1 or 2. (How would the code need to be modified to handle any number that the user mighttype?)

9. The following code is poorly structured:

Scanner console = new Scanner(System.in);

System.out.print("How much will John be spending? ");

double amount = console.nextDouble();

System.out.println();

int numBills1 = (int) (amount / 20.0);

if (numBills1 * 20.0 < amount) {

numBills1++;

}

System.out.print("How much will Jane be spending? ");

amount = console.nextDouble();

System.out.println();

int numBills2 = (int) (amount / 20.0);

if (numBills2 * 20.0 < amount) {

numBills2++;

}

System.out.println("John needs " + numBills1 + " bills");

System.out.println("Jane needs " + numBills2 + " bills");

Rewrite it so that it has a better structure and avoids redundancy. You may wish to introduce a method to helpcapture redundant code.

10. Write a piece of code that reads a shorthand text description of a color and prints the longer equivalent. Acceptable colornames are B for Blue, G for Green, and R for Red. If the user types something other than B, G, or R, the program should

print an error message. Make your program case-insensitive so that the user can type an uppercase or lowercase letter.Here are some example executions:

What color do you want? B

You have chosen Blue.

What color do you want? g

You have chosen Green.

What color do you want? Bork

Unknown color: Bork

11. Write a piece of code that reads a shorthand text description of a playing card and prints the longhand equivalent.The shorthand description is the card’s rank (2 through 10, J, Q, K, or A) followed by its suit (C, D, H, or S). Youshould expand the shorthand into the form “<Rank> of <Suit>”. You may assume that the user types valid input.Here are two sample executions:

Enter a card: 9 S

Nine of Spades

Enter a card: K C

King of Clubs

Section 4.2: Cumulative Algorithms

12. What is wrong with the following code, which attempts to add all numbers from 1 to a given maximum? Describehow to fix the code.

public static int sumTo(int n) {

for (int i = 1; i <= n; i++) {

int sum = 0;

sum += i;

}

return sum;

}

13. What is wrong with the following code, which attempts to return the number of factors of a given integer n?Describe how to fix the code.

public static int countFactors(int n) {

for (int i = 1; i <= n; i++) {

if (n % i == 0) { // factor

return i;

}

}

}

Self-Check Problems 293

294 Chapter 4 Conditional Execution

14. Write code to produce a cumulative product by multiplying together many numbers that are read from the console.

15. The following expression should equal 6.8, but in Java it does not. Why not?

0.2 + 1.2 + 2.2 + 3.2

16. The following code was intended to print a message, but it actually produces no output. Describe how to fix the code to print the expected message.

double gpa = 3.2;

if (gpa * 3 == 9.6) {

System.out.println("You earned enough credits.");

}

Section 4.3:Text Processing

17. What output is produced by the following program?

1 public class CharMystery {

2 public static void printRange(char startLetter, char endLetter) {

3 for (char letter = startLetter; letter <= endLetter; letter++) {

4 System.out.print(letter);

5 }

6 System.out.println();

7 }

8

9 public static void main(String[] args) {

10 printRange('e', 'g');

11 printRange('n', 's');

12 printRange('z', 'a');

13 printRange('q', 'r');

14 }

15 }

18. Write an if statement that tests to see whether a String begins with a capital letter.

19. What is wrong with the following code, which attempts to count the number occurrences of the letter 'e' in aString, case-insensitively?

int count = 0;

for (int i = 0; i < s.length(); i++) {

if (s.charAt(i).toLowerCase() == 'e') {

count++;

}

}

20. Consider a String stored in a variable called name that stores a person’s first and last name (e. g., “Marla Singer”).Write the expression that would produce the last name followed by the first initial (e. g., “Singer, M.”).

21. Write code to examine a String and determine how many of its letters come from the second half of the alphabet(that is, have values of 'n' or subsequent letters). Compare case-insensitively, such that values of 'N' through 'Z' alsocount. Assume that every character in the String is a letter.

Section 4.4: Methods with Conditional Execution

22. Consider a method printTriangleType that accepts three integer arguments representing the lengths of the sidesof a triangle and prints the type of triangle that these sides form. The three types are equilateral, isosceles, and sca-lene. An equilateral triangle has three sides of the same length, an isosceles triangle has two sides that are the samelength, and a scalene triangle has three sides of different lengths.

However, certain integer values (or combinations of values) would be illegal and could not represent the sides ofan actual triangle. What are these values? How would you describe the precondition(s) of the printTriangleTypemethod?

23. Consider a method getGrade that accepts an integer representing a student’s grade percentage in a course andreturns that student’s numerical course grade. The grade can be between 0.0 (failing) and 4.0 (perfect). What arethe preconditions of such a method?

24. The following method attempts to return the median (middle) of three integer values, but it contains logic errors. Inwhat cases does the method return an incorrect result? How can the code be fixed?

public static int medianOf3(int n1, int n2, int n3) {

if (n1 < n2) {

if (n2 < n3) {

return n2;

} else {

return n3;

}

} else {

if (n1 < n3) {

return n1;

} else {

return n3;

}

}

}

25. One of the exercises in Chapter 3 asked you to write a method that would find the roots of a quadratic equation ofthe form ax2 + bx + c = 0. The quadratic method was passed a, b, and c and then applied the following quadratic formula:

Under what conditions would this formula fail? Modify the quadratic method so that it will reject invalid values of a, b, or c by throwing an exception. (If you did not complete the exercise in the previous chapter, just write themethod’s header and the exception-throwing code.)

x = -b ; 2b2 - 4ac2a

Self-Check Problems 295

296 Chapter 4 Conditional Execution

26. Consider the following Java method, which is written incorrectly:

// This method should return how many of its three

// arguments are odd numbers.

public static void printNumOdd(int n1, int n2, int n3) {

int count = 0;

if (n1 % 2 != 0) {

count++;

} else if (n2 % 2 != 0) {

count++;

} else if (n3 % 2 != 0) {

count++;

}

System.out.println(count + " of the 3 numbers are odd.");

}

Under what cases will the method print the correct answer, and when will it print an incorrect answer? What shouldbe changed to fix the code? Can you think of a way to write the code correctly without any if/else statements?

Exercises

1. Write a method called fractionSum that accepts an integer parameter n and returns as a double the sum of thefirst n terms of the sequence

In other words, the method should generate the following sequence:

You may assume that the parameter n is nonnegative.

2. Write a method called repl that accepts a String and a number of repetitions as parameters and returns theString concatenated that many times. For example, the call repl("hello", 3) should return"hellohellohello". If the number of repetitions is zero or less, the method should return an empty string.

3. Write a method called season that takes as parameters two integers representing a month and day and returns aString indicating the season for that month and day. Assume that the month is specified as an integer between 1and 12 (1 for January, 2 for February, and so on) and that the day of the month is a number between 1 and 31. If thedate falls between 12/16 and 3/15, the method should return "winter". If the date falls between 3/16 and 6/15, themethod should return "spring". If the date falls between 6/16 and 9/15, the method should return "summer". Andif the date falls between 9/16 and 12/15, the method should return "fall".

4. Write a method called pow that accepts a base and an exponent as parameters and returns the base raised to the givenpower. For example, the call pow(3, 4) should return 3 * 3 * 3 * 3, or 81. Assume that the base and exponentare nonnegative.

1 + 12

+ 13

+ 14

+ 15

+ Á

an

i=1

1i

Answers Section I

Appendix A Answers to Self-Check Problems 1047

Chapter 4

1. (a) z % 2 != 0(b) z <= Math.sqrt(y)(c) y > 0(d) x % 2 != y % 2(e) y % z == 0(f) z != 0(g) Math.abs(y) > Math.abs(z)(h) (x >= 0) == (z < 0)(i) y % 10 == y(j) z >= 0(k) x % 2 == 0(l) Math.abs(x – y) < Math.abs(z – y)

g.fillRect(10, 10, 50, 50); g.setColor(Color.WHITE); g.fillOval(10, 10, 50, 50);

3. The problem is that the parameters for the drawRect and drawLine methods havedifferent meanings. In drawRect, the parameters are (x, y, width, height);in drawLine, they are (x1, y1, x2, y2). To fix the problem, the third andfourth parameters passed to drawRect should be changed to 40 and 20 so that therectangle’s bottom-left corner will be at (50, 40). The following code fixes theproblem:

DrawingPanel panel = new DrawingPanel(200, 100); Graphics g = panel.getGraphics();g.drawRect(10, 20, 40, 20);g.drawLine(10, 20, 50, 40);

4. The Draw7 program draws a series of progressively smaller black circles, eachwith its right and bottom edges touching the right and bottom corners of the win-dow. Its output looks like this:

1048 Appendix A Answers to Self-Check Problems

2. (a) true(b) false(c) true(d) false(e) true(f) false(g) false(h) true(i) true

3. (a) 13 21(b) 5 6(c) 6 5(d) 7 11

4. (a) 10 6(b) 9 9(c) 3 4(d) 29 30

5. Scanner console = new Scanner(System.in);

System.out.print("Type a number: ");int number = console.nextInt();

if (number % 2 == 0) {System.out.println("even");

} else {System.out.println("odd");

}

6. The code incorrectly prints that even numbers not divisible by 3 are odd, because theelse statement matches the most closely nested if statement (number % 3 == 0),not the outer if statement.

The following change corrects the problem. Note the braces around the outer ifstatement:

if (number % 2 == 0) {if (number % 3 == 0) {

System.out.println("Divisible by 6.");}

}else {

System.out.println("Odd.");}

Appendix A Answers to Self-Check Problems 1049

7. The code won’t ever print "Mine, too!" because it mistakenly uses the == operator to compare two string objects. It should use the equals method to com-pare them:

if (name.equals("blue")) {...

8. int sum = 1000;Scanner console = new Scanner(System.in); System.out.print(

"Is your money multiplied 1 or 2 times? ");int times = console.nextInt();

System.out.print("And how much are you contributing? ");int donation = console.nextInt();sum += times * donation;total += donation;if (times == 1) {

count1++;}else if (times == 2) {

count2++;}

If the user could type any number, the code might need additional if statements toincrement the proper count variable. If the user could type anything, even a non-integer, the code might need to use the hasNextInt method of the Scanner (seenin Chapter 5) to ensure that it has received valid input before it proceeds.

9. // Prompts for two people's money and reports// how many $20 bills the person would need.

import java.util.*;public class Bills {

public static void main(String[] args) {Scanner console = new Scanner(System.in);

int numBills1 = getBills(console, "John");int numBills2 = getBills(console, "Jane");

System.out.println("John needs " + numBills1 + " bills");

System.out.println("Jane needs " + numBills2 + " bills");

}public static int getBills(Scanner console,

String name) {System.out.print("How much will " + name +

" be spending? ");1050 Appendix A Answers to Self-Check Problems

double amount = console.nextDouble(); System.out.println();

int numBills = (int) (amount/20.0);if (numBills * 20.0 < amount) {

numBills++;}return numBills;

}}

10. Scanner console = new Scanner(System.in); System.out.print("What color do you want? "); String choice = console.nextLine();if (choice.equalsIgnoreCase("r")) {

System.out.println("You have chosen Red.");} else if (choice.equalsIgnoreCase("g")) {

System.out.println("You have chosen Green.");} else if (choice.equalsIgnoreCase("b")) {

System.out.println("You have chosen Blue.");} else {

System.out.println("Unknown color: " + choice);}

11. Scanner console = new Scanner(System.in); System.out.print("Enter a card: ");String rank = console.next(); String suit = console.next();

if (rank.equals("2")) {rank = "Two";

} else if (rank.equals("3")) {rank = "Three";

} else if (rank.equals("4")) {rank = "Four";

} else if (rank.equals("5")) {rank = "Five";

} else if (rank.equals("6")) {rank = "Six";

} else if (rank.equals("7")) {rank = "Seven";

} else if (rank.equals("8")) {rank = "Eight";

} else if (rank.equals("9")) {rank = "Nine";

} else if (rank.equals("10")) {rank = "Ten";

Appendix A Answers to Self-Check Problems 1051

} else if (rank.equals("J")) {rank = "Jack";

} else if (rank.equals("Q")) {rank = "Queen";

} else if (rank.equals("K")) {rank = "King";

} else { // rank.equals("A")rank = "Ace";

}

if (suit.equals("C")) {suit = "Clubs";

} else if (suit.equals("D")) {suit = "Diamonds";

} else if (suit.equals("H")) {suit = "Hearts";

} else { // suit.equals("S")suit = "Spades";

}

System.out.println(rank + " of " + suit);

12. The sum variable needs to be declared outside the for loop. The following codefixes the problem:

public static int sumTo(int n) {int sum = 0;for (int i = 1; i <= n; i++) {sum += i;

}return sum;

}

13. The method will not compile. It should count the factors using a cumulative sum;it should not return inside the loop when it finds each factor. Instead, it shoulddeclare a counter outside the loop that is incremented as each factor is seen. Thefollowing code fixes the problem:

public static int countFactors(int n) {int count = 0;for (int i = 1; i <= n; i++) {

if (n % i == 0) {count++;

}}return count;

}1052 Appendix A Answers to Self-Check Problems

14. Scanner console = new Scanner(System.in); System.out.print("How many numbers? "); int count = console.nextInt();int product = 1;for (int i = 1; i <= count; i++) {

System.out.print("Next number --> "); int num = console.nextInt();product *= num;

}System.out.println("Product = " + product);

15. The expression equals 6.800000000000001 because the limited precision of thedouble type led to a roundoff error.

16. The expression gpa * 3 equals 9.600000000000001 because of a roundofferror. To fix this, test that the value is close to 9.6 rather than exactly equal to it:

double gpa = 3.2;if (Math.abs(gpa * 3 – 9.6) < 0.1) {

System.out.println("You earned enough credits.");}

17. efg nopqrs

qr

18. if (Character.isUpperCase(theString.charAt(0))) {...

}

19. The toLowerCase method cannot be called on a char value, which is what the charAt method returns. A better solution would be to call theCharacter.toLowerCase method on the characters of the string:

int count = 0;for (int i = 0; i < s.length(); i++) {

if (Character.toLowerCase(s.charAt(i)) == 'e') {count++;

}}

Another solution would be to lowercase the entire string once before the loop:

s = s.toLowerCase();int count = 0;for (int i = 0; i < s.length(); i++) {

Appendix A Answers to Self-Check Problems 1053

if (s.charAt(i) == 'e') {count++;

}}

20. The following expression would produce the desired result:

String name = "Marla Singer";int space = name.indexOf(" ");String lastName = name.substring(space + 1); String firstInitial = name.substring(0, 1); String lastNameFirstInitial = lastName + ", " +

firstInitial + "."; System.out.println(lastNameFirstInitial);

Alternatively, you could use this shorter version:

String name = "Marla Singer"; System.out.println(name.substring(name.indexOf(" ") + 1) +

", " + name.charAt(0) + ".");

21. // assuming that the String is stored in the variable str int count = 0;for (int i = 0; i < str.length(); i++) {

if (Character.toLowerCase(str.charAt(i)) >= 'n') {count++;

}}System.out.println(count + " letters come after n.");

22. public static void printTriangleType(int s1, int s2, int s3) {if (s1 == s2 && s2 == s3) {

System.out.println("equilateral");} else if (s1 == s2 || s1 == s3 || s2 == s3) {

System.out.println("isosceles");} else {

System.out.println("scalene");}

}

Invalid values include negative numbers for a side’s length and a number for anyone side length that is greater than the sum of the other two side lengths, becausethis cannot be a valid triangle. The precondition of the printTriangleTypemethod is that the side lengths must constitute a valid triangle.

23. The preconditions of this method are that the grade parameter’s value is between0 and 100.1054 Appendix A Answers to Self-Check Problems

24. The code fails when n3 is the smallest of the three numbers; for example, when theparameters’ values are (4, 7, 2), the code should return 4 but instead returns 2.The method could be correctly written as follows:

public static int medianOf3(int n1, int n2, int n3) {if (n1 < n2 && n1 < n3) {

if (n2 < n3) {return n2;

} else {return n3;

}} else if (n2 < n1 && n2 < n3) {

if (n1 < n3) {return n1;

} else {return n3;

}} else { // (n3 < n1 && n3 < n2)

if (n1 < n2) {return n1;

} else {return n2;

}}

}

Alternatively, here is a shorter version:

public static int medianOf3(int n1, int n2, int n3) {return Math.max(Math.max(Math.min(n1, n2),

Math.min(n2, n3)),Math.min(n1, n3));

}

25. // Throws an exception if a, b, c are invalidpublic static void quadratic(int a, int b, int c) {

double determinant = b * b – 4 * a * c;if (a == 0) {

throw new IllegalArgumentException("Invalid a value of 0");

}if (determinant < 0) {

throw new IllegalArgumentException("Invalid determinant");

}...

}

Appendix A Answers to Self-Check Problems 1055

Invalid values are when a = 0 (because it makes the denominator of the equationequal 0), or when b2 - 4ac < 0, because then it has no real square root.

26. The code fails when more than one number is odd, because it uses else if ratherthan if. The tests should not be nested because they are not mutually exclusive;more than one number could be odd. The following code fixes the problem:

public static void printNumOdd(int n1, int n2, int n3) {int count = 0;if (n1 % 2 != 0) {

count++;}if (n2 % 2 != 0) {

count++;}if (n3 % 2 != 0) {

count++;}System.out.println(count +

" of the 3 numbers are odd.");}

The following version without if statements also works:

public static void printNumOdd(int n1, int n2, int n3) {int count = n1 % 2 + n2 % 2 + n3 % 2;System.out.println(count +

" of the 3 numbers are odd.");}

Chapter 5

1. (a) Executes body 10 times.Output is1 11 21 31 41 51 61 71 81 91

(b) Executes body 0 times.No output.

(c) Loops infinitely.Output is250250250...

(d) Executes body 3 times.Output is2 4 16

Questions Section II

8. Suppose you have an int variable called number. What Java expression produces the second-to-last digit of thenumber (the 10s place)? What expression produces the third-to-last digit of the number (the 100s place)?

9. Consider the following code:

int first = 8;

int second = 19;

first = first + second;

second = first – second;

first = first – second;

What are the values of first and second at the end of this code? How would you describe the net effect of thecode statements in this exercise?

10. Rewrite the code from the previous exercise to be shorter, by declaring the variables together and by using the specialassignment operators (e.g., += , –=, *=, and /=) as appropriate.

11. What are the values of a, b, and c after the following code statements? (It may help you to write down their valuesafter each line.)

int a = 5;

int b = 10;

int c = b;

a++;

b––;

c += a;

12. What is the output from the following code?

int max;

int min = 10;

max = 17 – 4 / 10;

max = max + 6;

min = max – min;

System.out.println(max * 2);

System.out.println(max + min);

System.out.println(max);

System.out.println(min);

13. Suppose you have a real number variable x. Write a Java expression that computes the following value y while usingthe * operator only four times:

Section 2.3: The for Loop

14. Assume that you have a variable called count that will take on the values 1, 2, 3, 4, and so on. You are going toformulate expressions in terms of count that will yield different sequences. For example, to get the sequence 2, 4,6, 8, 10, 12, ..., you would use the expression (2 * count). Fill in the following table, indicating an expres-sion that will generate each sequence.

y = 12.3x4 - 9.1x3 + 19.3x2 - 4.6x + 34.2

Self-Check Problems 119

120 Chapter 2 Primitive Data and Definite Loops

Sequence Expression

a. 2, 4, 6, 8, 10, 12, . . .

b. 4, 19, 34, 49, 64, 79, . . .

c. 30, 20, 10, 0, !10, !20, . . .

d. !7, !3, 1, 5, 9, 13, . . .

e. 97, 94, 91, 88, 85, 82, . . .

15. Complete the code for the following for loop:

for (int i = 1; i <= 6; i++) {

// your code here

}

so that it prints the following numbers, one per line:

–4

14

32

50

68

86

16. What is the output of the following oddStuff method?

public static void oddStuff() {

int number = 4;

for (int count = 1; count <= number; count++) {

System.out.println(number);

number = number / 2;

}

}

17. What is the output of the following loop?

int total = 25;

for (int number = 1; number <= (total / 2); number++) {

total = total – number;

System.out.println(total + " " + number);

}

18. What is the output of the following loop?

System.out.println("+---+");

for (int i = 1; i <= 3; i++) {

System.out.println("\\ /");

System.out.println("/ \\");

}

System.out.println("+---+");

120 Chapter 2 Primitive Data and Definite Loops

Sequence Expression

a. 2, 4, 6, 8, 10, 12, . . .

b. 4, 19, 34, 49, 64, 79, . . .

c. 30, 20, 10, 0, !10, !20, . . .

d. !7, !3, 1, 5, 9, 13, . . .

e. 97, 94, 91, 88, 85, 82, . . .

15. Complete the code for the following for loop:

for (int i = 1; i <= 6; i++) {

// your code here

}

so that it prints the following numbers, one per line:

–4

14

32

50

68

86

16. What is the output of the following oddStuff method?

public static void oddStuff() {

int number = 4;

for (int count = 1; count <= number; count++) {

System.out.println(number);

number = number / 2;

}

}

17. What is the output of the following loop?

int total = 25;

for (int number = 1; number <= (total / 2); number++) {

total = total – number;

System.out.println(total + " " + number);

}

18. What is the output of the following loop?

System.out.println("+---+");

for (int i = 1; i <= 3; i++) {

System.out.println("\\ /");

System.out.println("/ \\");

}

System.out.println("+---+");

19. What is the output of the following loop?

for (int i = 1; i <= 3; i++)

System.out.println("How many lines");

System.out.println("are printed?");

20. What is the output of the following loop?

System.out.print("T-minus ");

for (int i = 5; i >= 1; i——) {

System.out.print(i + ", ");

}

System.out.println("Blastoff!");

21. What is the output of the following sequence of loops?

for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= 10; j++) {

System.out.print((i * j) + " ");

}

System.out.println();

}

22. What is the output of the following sequence of loops?for (int i = 1; i <= 10; i++) {

for (int j = 1; j <= 10 — i; j++) {

System.out.print(" ");

}

for (int j = 1; j <= 2 * i — 1; j++) {

System.out.print("*");

}

System.out.println();

}

23. What is the output of the following sequence of loops?

for (int i = 1; i <= 2; i++) {

for (int j = 1; j <= 3; j++) {

for (int k = 1; k <= 4; k++) {

System.out.print("*");

}

System.out.print("!");

}

System.out.println();

}

24. What is the output of the following sequence of loops? Notice that the code is the same as that in the previous exer-cise, except that the placement of the braces has changed.for (int i = 1; i <= 2; i++) {

for (int j = 1; j <= 3; j++) {

for (int k = 1; k <= 4; k++) {

Self-Check Problems 121

Answers Section II

Appendix A Answers to Self-Check Problems 1041

7. Last digit: number % 10

8. Second-to-last digit: (number % 100) / 10 or (number / 10) % 10Third-to-last digit: (number % 1000) / 100 or (number / 100) % 10

9. first: 19 second: 8

The code swaps the values of the variables first and second.

10. int first = 8, second = 19;first += second;second = first – second;first -= second;

11. a: 6b: 9c: 16

12. 46362313

13. double y = 34.2 + x * (–4.6 + x * (19.3 + x * (–9.1 + x * 12.3)));

14. (a) 2 * count(b) 15 * count – 11(c) –10 * count + 40(d) 4 * count – 11(e) –3 * count + 100

15. for (int i = 1; i <= 6; i++) {// your code hereSystem.out.println(18 * i – 22);

}

16. 42

17. 24 122 219 315 410 51042 Appendix A Answers to Self-Check Problems

18. +----+\ // \\ // \\ // \+----+

19. How many lines How many lines How many lines are printed?

20. T-minus 5, 4, 3, 2, 1, Blastoff!

21. 1 2 3 4 5 6 7 8 9 102 4 6 8 10 12 14 16 18 203 6 9 12 15 18 21 24 27 304 8 12 16 20 24 28 32 36 405 10 15 20 25 30 35 40 45 50

22. ****************************************************************************************************

23. ****!****!****!****!****!****!

24. ************!************!

25. *!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!

26. • The loop prints every third number, not every odd number. The statement count= count + 2 on line 8 should be moved into the loop header instead of count++.

1042 Appendix A Answers to Self-Check Problems

18. +----+\ // \\ // \\ // \+----+

19. How many lines How many lines How many lines are printed?

20. T-minus 5, 4, 3, 2, 1, Blastoff!

21. 1 2 3 4 5 6 7 8 9 102 4 6 8 10 12 14 16 18 203 6 9 12 15 18 21 24 27 304 8 12 16 20 24 28 32 36 405 10 15 20 25 30 35 40 45 50

22. ****************************************************************************************************

23. ****!****!****!****!****!****!

24. ************!************!

25. *!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!

26. • The loop prints every third number, not every odd number. The statement count= count + 2 on line 8 should be moved into the loop header instead of count++.

Questions Section III

Self-Check Problems 177

Objects contain methods that implement their behavior. Tocall a method on an object, write its name, followed by adot, followed by the method name.

A String object holds a sequence of characters. The char-acters have indexes, starting with 0 for the first character.

An exception is an error that occurs when a program hasperformed an illegal action and is unable to continue exe-cuting normally.

Some programs are interactive and respond to input fromthe user. These programs should print a message to theuser, also called a prompt, asking for the input.

Java has a class called Scanner that reads input from thekeyboard. A Scanner can read various pieces of input(also called tokens) from an input source. It can readeither one token at a time or an entire line at a time.

Self-Check Problems

Section 3.1: Parameters

1. What output is produced by the following program?

1 public class Odds {

2 public static void main(String[] args) {

3 printOdds(3);

4 printOdds(17 / 2);

5

6 int x = 25;

7 printOdds(37 – x + 1);

8 }

9

10 public static void printOdds(int n) {

11 for (int i = 1; i <= n; i++) {

12 int odd = 2 * i – 1;

13 System.out.print(odd + " ");

14 }

15 System.out.println();

16 }

17 }

2. What is the output of the following program?

1 public class Weird {

2 public static void main(String[] args) {

3 int number = 8;

4 halfTheFun(11);

5 halfTheFun(2 – 3 + 2 * 8);

6 halfTheFun(number);

Self-Check Problems 177

Objects contain methods that implement their behavior. Tocall a method on an object, write its name, followed by adot, followed by the method name.

A String object holds a sequence of characters. The char-acters have indexes, starting with 0 for the first character.

An exception is an error that occurs when a program hasperformed an illegal action and is unable to continue exe-cuting normally.

Some programs are interactive and respond to input fromthe user. These programs should print a message to theuser, also called a prompt, asking for the input.

Java has a class called Scanner that reads input from thekeyboard. A Scanner can read various pieces of input(also called tokens) from an input source. It can readeither one token at a time or an entire line at a time.

Self-Check Problems

Section 3.1: Parameters

1. What output is produced by the following program?

1 public class Odds {

2 public static void main(String[] args) {

3 printOdds(3);

4 printOdds(17 / 2);

5

6 int x = 25;

7 printOdds(37 – x + 1);

8 }

9

10 public static void printOdds(int n) {

11 for (int i = 1; i <= n; i++) {

12 int odd = 2 * i – 1;

13 System.out.print(odd + " ");

14 }

15 System.out.println();

16 }

17 }

2. What is the output of the following program?

1 public class Weird {

2 public static void main(String[] args) {

3 int number = 8;

4 halfTheFun(11);

5 halfTheFun(2 – 3 + 2 * 8);

6 halfTheFun(number);178 Chapter 3 Introduction to Parameters and Objects

7 System.out.println("number = " + number);

8 }

9

10 public static void halfTheFun(int number) {

11 number = number / 2;

12 for (int count = 1; count <= number; count++) {

13 System.out.print(count + " ");

14 }

15 System.out.println();

16 }

17 }

3. What is the output of the following program?

1 public class MysteryNumbers {

2 public static void main(String[] args) {

3 String one = "two";

4 String two = "three";

5 String three = "1";

6 int number = 20;

7

8 sentence(one, two, 3);

9 sentence(two, three, 14);

10 sentence(three, three, number + 1);

11 sentence(three, two, 1);

12 sentence("eight", three, number / 2);

13 }

14

15 public static void sentence(String three, String one, int number) {

16 System.out.println(one + " times " + three + " = " + (number * 2));

17 }

18 }

4. What output is produced by the following program?

1 public class MysteryWho {

2 public static void main(String[] args) {

3 String whom = "her";

4 String who = "him";

5 String it = "who";

6 String he = "it";

7 String she = "whom";

8

9 sentence(he, she, it);

10 sentence(she, he, who);

11 sentence(who, she, who);

178 Chapter 3 Introduction to Parameters and Objects

7 System.out.println("number = " + number);

8 }

9

10 public static void halfTheFun(int number) {

11 number = number / 2;

12 for (int count = 1; count <= number; count++) {

13 System.out.print(count + " ");

14 }

15 System.out.println();

16 }

17 }

3. What is the output of the following program?

1 public class MysteryNumbers {

2 public static void main(String[] args) {

3 String one = "two";

4 String two = "three";

5 String three = "1";

6 int number = 20;

7

8 sentence(one, two, 3);

9 sentence(two, three, 14);

10 sentence(three, three, number + 1);

11 sentence(three, two, 1);

12 sentence("eight", three, number / 2);

13 }

14

15 public static void sentence(String three, String one, int number) {

16 System.out.println(one + " times " + three + " = " + (number * 2));

17 }

18 }

4. What output is produced by the following program?

1 public class MysteryWho {

2 public static void main(String[] args) {

3 String whom = "her";

4 String who = "him";

5 String it = "who";

6 String he = "it";

7 String she = "whom";

8

9 sentence(he, she, it);

10 sentence(she, he, who);

11 sentence(who, she, who);

178 Chapter 3 Introduction to Parameters and Objects

7 System.out.println("number = " + number);

8 }

9

10 public static void halfTheFun(int number) {

11 number = number / 2;

12 for (int count = 1; count <= number; count++) {

13 System.out.print(count + " ");

14 }

15 System.out.println();

16 }

17 }

3. What is the output of the following program?

1 public class MysteryNumbers {

2 public static void main(String[] args) {

3 String one = "two";

4 String two = "three";

5 String three = "1";

6 int number = 20;

7

8 sentence(one, two, 3);

9 sentence(two, three, 14);

10 sentence(three, three, number + 1);

11 sentence(three, two, 1);

12 sentence("eight", three, number / 2);

13 }

14

15 public static void sentence(String three, String one, int number) {

16 System.out.println(one + " times " + three + " = " + (number * 2));

17 }

18 }

4. What output is produced by the following program?

1 public class MysteryWho {

2 public static void main(String[] args) {

3 String whom = "her";

4 String who = "him";

5 String it = "who";

6 String he = "it";

7 String she = "whom";

8

9 sentence(he, she, it);

10 sentence(she, he, who);

11 sentence(who, she, who);Self-Check Problems 179

12 sentence(it, "stu", "boo");

13 sentence(it, whom, who);

14 }

15

16 public static void sentence(String she, String who, String whom) {

17 System.out.println(who + " and " + whom + " like " + she);

18 }

19 }

5. What output is produced by the following program?

1 public class MysteryTouch {

2 public static void main(String[] args) {

3 String head = "shoulders";

4 String knees = "toes";

5 String elbow = "head";

6 String eye = "eyes and ears";

7 String ear = "eye";

8

9 touch(ear, elbow);

10 touch(elbow, ear);

11 touch(head, "elbow");

12 touch(eye, eye);

13 touch(knees, "Toes");

14 touch(head, "knees " + knees);

15 }

16

17 public static void touch(String elbow, String ear) {

18 System.out.println("touch your " + elbow + " to your " + ear);

19 }

20 }

6. What output is produced by the following program?

1 public class MysterySoda {

2 public static void main(String[] args) {

3 String soda = "coke";

4 String pop = "pepsi";

5 String coke = "pop";

6 String pepsi = "soda";

7 String say = pop;

8

9 carbonated(coke, soda, pop);

10 carbonated(pop, pepsi, pepsi);

11 carbonated("pop", pop, "koolaid");

12 carbonated(say, "say", pop);

13 }

Self-Check Problems 179

12 sentence(it, "stu", "boo");

13 sentence(it, whom, who);

14 }

15

16 public static void sentence(String she, String who, String whom) {

17 System.out.println(who + " and " + whom + " like " + she);

18 }

19 }

5. What output is produced by the following program?

1 public class MysteryTouch {

2 public static void main(String[] args) {

3 String head = "shoulders";

4 String knees = "toes";

5 String elbow = "head";

6 String eye = "eyes and ears";

7 String ear = "eye";

8

9 touch(ear, elbow);

10 touch(elbow, ear);

11 touch(head, "elbow");

12 touch(eye, eye);

13 touch(knees, "Toes");

14 touch(head, "knees " + knees);

15 }

16

17 public static void touch(String elbow, String ear) {

18 System.out.println("touch your " + elbow + " to your " + ear);

19 }

20 }

6. What output is produced by the following program?

1 public class MysterySoda {

2 public static void main(String[] args) {

3 String soda = "coke";

4 String pop = "pepsi";

5 String coke = "pop";

6 String pepsi = "soda";

7 String say = pop;

8

9 carbonated(coke, soda, pop);

10 carbonated(pop, pepsi, pepsi);

11 carbonated("pop", pop, "koolaid");

12 carbonated(say, "say", pop);

13 }

Self-Check Problems 179

12 sentence(it, "stu", "boo");

13 sentence(it, whom, who);

14 }

15

16 public static void sentence(String she, String who, String whom) {

17 System.out.println(who + " and " + whom + " like " + she);

18 }

19 }

5. What output is produced by the following program?

1 public class MysteryTouch {

2 public static void main(String[] args) {

3 String head = "shoulders";

4 String knees = "toes";

5 String elbow = "head";

6 String eye = "eyes and ears";

7 String ear = "eye";

8

9 touch(ear, elbow);

10 touch(elbow, ear);

11 touch(head, "elbow");

12 touch(eye, eye);

13 touch(knees, "Toes");

14 touch(head, "knees " + knees);

15 }

16

17 public static void touch(String elbow, String ear) {

18 System.out.println("touch your " + elbow + " to your " + ear);

19 }

20 }

6. What output is produced by the following program?

1 public class MysterySoda {

2 public static void main(String[] args) {

3 String soda = "coke";

4 String pop = "pepsi";

5 String coke = "pop";

6 String pepsi = "soda";

7 String say = pop;

8

9 carbonated(coke, soda, pop);

10 carbonated(pop, pepsi, pepsi);

11 carbonated("pop", pop, "koolaid");

12 carbonated(say, "say", pop);

13 }180 Chapter 3 Introduction to Parameters and Objects

14 public static void carbonated(String coke, String soda, String pop) {

15 System.out.println("say " + soda + " not " + pop + " or " + coke);

16 }

17 }

7. Write a method called printStrings that accepts a String and a number of repetitions as parameters and printsthat String the given number of times with a space after each time. For example, the call

printStrings("abc", 5);

will print the following output:

abc abc abc abc abc

8. The System.out.println command works on many different types of values, such as integers or doubles. What isthe term for such a method?

Section 3.2: Methods That Return Values

9. What is wrong with the following program?1 public class Temperature {

2 public static void main(String[] args) {

3 double tempf = 98.6;

4 double tempc = 0.0;

5 ftoc(tempf, tempc);

6 System.out.println("Body temp in C is: " + tempc);

7 }

8

9 // converts Fahrenheit temperatures to Celsius

10 public static void ftoc(double tempf, double tempc) {

11 tempc = (tempf – 32) * 5 / 9;

12 }

13 }

10. Evaluate the following expressions:

a. Math.abs(–1.6)b. Math.abs(2 + –4)c. Math.pow(6, 2)d. Math.pow(5 / 2, 6)e. Math.ceil(9.1)f. Math.ceil(115.8)

g. Math.max(7, 4)h. Math.min(8, 3 + 2)i. Math.min(–2, –5)

j. Math.sqrt(64)

k. Math.sqrt(76 + 45)l. 100 + Math.log10(100)

180 Chapter 3 Introduction to Parameters and Objects

14 public static void carbonated(String coke, String soda, String pop) {

15 System.out.println("say " + soda + " not " + pop + " or " + coke);

16 }

17 }

7. Write a method called printStrings that accepts a String and a number of repetitions as parameters and printsthat String the given number of times with a space after each time. For example, the call

printStrings("abc", 5);

will print the following output:

abc abc abc abc abc

8. The System.out.println command works on many different types of values, such as integers or doubles. What isthe term for such a method?

Section 3.2: Methods That Return Values

9. What is wrong with the following program?1 public class Temperature {

2 public static void main(String[] args) {

3 double tempf = 98.6;

4 double tempc = 0.0;

5 ftoc(tempf, tempc);

6 System.out.println("Body temp in C is: " + tempc);

7 }

8

9 // converts Fahrenheit temperatures to Celsius

10 public static void ftoc(double tempf, double tempc) {

11 tempc = (tempf – 32) * 5 / 9;

12 }

13 }

10. Evaluate the following expressions:

a. Math.abs(–1.6)b. Math.abs(2 + –4)c. Math.pow(6, 2)d. Math.pow(5 / 2, 6)e. Math.ceil(9.1)f. Math.ceil(115.8)

g. Math.max(7, 4)h. Math.min(8, 3 + 2)i. Math.min(–2, –5)

j. Math.sqrt(64)

k. Math.sqrt(76 + 45)l. 100 + Math.log10(100)

180 Chapter 3 Introduction to Parameters and Objects

14 public static void carbonated(String coke, String soda, String pop) {

15 System.out.println("say " + soda + " not " + pop + " or " + coke);

16 }

17 }

7. Write a method called printStrings that accepts a String and a number of repetitions as parameters and printsthat String the given number of times with a space after each time. For example, the call

printStrings("abc", 5);

will print the following output:

abc abc abc abc abc

8. The System.out.println command works on many different types of values, such as integers or doubles. What isthe term for such a method?

Section 3.2: Methods That Return Values

9. What is wrong with the following program?1 public class Temperature {

2 public static void main(String[] args) {

3 double tempf = 98.6;

4 double tempc = 0.0;

5 ftoc(tempf, tempc);

6 System.out.println("Body temp in C is: " + tempc);

7 }

8

9 // converts Fahrenheit temperatures to Celsius

10 public static void ftoc(double tempf, double tempc) {

11 tempc = (tempf – 32) * 5 / 9;

12 }

13 }

10. Evaluate the following expressions:

a. Math.abs(–1.6)b. Math.abs(2 + –4)c. Math.pow(6, 2)d. Math.pow(5 / 2, 6)e. Math.ceil(9.1)f. Math.ceil(115.8)

g. Math.max(7, 4)h. Math.min(8, 3 + 2)i. Math.min(–2, –5)

j. Math.sqrt(64)

k. Math.sqrt(76 + 45)l. 100 + Math.log10(100)

Self-Check Problems 181

m.13 + Math.abs(–7) – Math.pow(2, 3) + 5n. Math.sqrt(16) * Math.max(Math.abs(–5), Math.abs(–3))o. 7 – 2 + Math.log10(1000) + Math.log(Math.pow(Math.E, 5))p. Math.max(18 – 5, Math.ceil(4.6 * 3))

11. What output is produced by the following program?

1 public class MysteryReturn {

2 public static void main(String[] args) {

3 int x = 1, y = 2, z = 3;

4 z = mystery(x, z, y);

5 System.out.println(x + " " + y + " " + z);

6 x = mystery(z, z, x);

7 System.out.println(x + " " + y + " " + z);

8 y = mystery(y, y, z);

9 System.out.println(x + " " + y + " " + z);

10 }

11

12 public static int mystery(int z, int x, int y) {

13 z––;

14 x = 2 * y + z;

15 y = x – 1;

16 System.out.println(y + " " + z);

17 return x;

18 }

19 }

12. Write a method called min that takes three integers as parameters and returns the smallest of the three values; forexample, a call of min(3, –2, 7) would return !2, and a call of min(19, 27, 6) would return 6. UseMath.min to write your solution.

13. Write a method called countQuarters that takes an int representing a number of cents as a parameter and returnsthe number of quarter coins represented by that many cents. Don’t count any whole dollars, because those would bedispensed as dollar bills. For example, countQuarters(64) would return 2, because 64 cents is equivalent to 2 quar-ters with 14 cents left over. A call of countQuarters(1278) would return 3, because after the 12 dollars are takenout, 3 quarters remain in the 78 cents that are left.

Section 3.3: Using Objects

14. Assuming that the following variables have been declared:

String str1 = "Q.E.D.";

String str2 = "Arcturan Megadonkey";

String str3 = "Sirius Cybernetics Corporation";

evaluate the following expressions:

a. str1.length()b. str2.length()c. str1.toLowerCase()

Self-Check Problems 181

m.13 + Math.abs(–7) – Math.pow(2, 3) + 5n. Math.sqrt(16) * Math.max(Math.abs(–5), Math.abs(–3))o. 7 – 2 + Math.log10(1000) + Math.log(Math.pow(Math.E, 5))p. Math.max(18 – 5, Math.ceil(4.6 * 3))

11. What output is produced by the following program?

1 public class MysteryReturn {

2 public static void main(String[] args) {

3 int x = 1, y = 2, z = 3;

4 z = mystery(x, z, y);

5 System.out.println(x + " " + y + " " + z);

6 x = mystery(z, z, x);

7 System.out.println(x + " " + y + " " + z);

8 y = mystery(y, y, z);

9 System.out.println(x + " " + y + " " + z);

10 }

11

12 public static int mystery(int z, int x, int y) {

13 z––;

14 x = 2 * y + z;

15 y = x – 1;

16 System.out.println(y + " " + z);

17 return x;

18 }

19 }

12. Write a method called min that takes three integers as parameters and returns the smallest of the three values; forexample, a call of min(3, –2, 7) would return !2, and a call of min(19, 27, 6) would return 6. UseMath.min to write your solution.

13. Write a method called countQuarters that takes an int representing a number of cents as a parameter and returnsthe number of quarter coins represented by that many cents. Don’t count any whole dollars, because those would bedispensed as dollar bills. For example, countQuarters(64) would return 2, because 64 cents is equivalent to 2 quar-ters with 14 cents left over. A call of countQuarters(1278) would return 3, because after the 12 dollars are takenout, 3 quarters remain in the 78 cents that are left.

Section 3.3: Using Objects

14. Assuming that the following variables have been declared:

String str1 = "Q.E.D.";

String str2 = "Arcturan Megadonkey";

String str3 = "Sirius Cybernetics Corporation";

evaluate the following expressions:

a. str1.length()b. str2.length()c. str1.toLowerCase()

Answer Section III

Appendix A Answers to Self-Check Problems 1043

• On line 12, the variable count is no longer defined (its scope is limited to thefor loop). It should be declared before the loop begins rather than inside theloop’s header.

• On line 12, too large a value is printed for the final odd number; count shouldbe printed, not count + 2.

• On line 20, it is illegal to try to assign a new value to a constant such asMAX_ODD. One way to fix this would be to write two methods: one to print theodds up to 21 and a second to print the odds up to 11. (Admittedly, this solutionis redundant. A better solution to this kind of problem involves parameter pass-ing, which will be demonstrated in later chapters.)

• The last print statement in main should be a println statement.

27. The result is: 55

28. (a) 2 * line + (2 * SIZE)(b) 4 * line + (3 * SIZE)(c) -line + (2 * SIZE + 3)

29. line \ ! /1 0 22 02 2 18 23 4 14 44 6 10 65 8 6 86 10 2 10• expression for \ and /: 2 * line – 2• expression for !: –4 * line + 26

30. Line \ ! /1 0 14 02 2 10 23 4 6 44 6 2 6• expression for \ and /: 2 * line - 2• expression for !: –4 * line + 18• generalized for constant: –4 * line + (4 * SIZE + 2)

Chapter 3

1. 1 3 51 3 5 7 9 11 13 151 3 5 7 9 11 13 15 17 19 21 23 25

2. 1 2 3 4 51 2 3 4 5 6 71 2 3 4number = 8

1044 Appendix A Answers to Self-Check Problems

3. three times two = 61 times three = 281 times 1 = 42 three times 1 = 21 times eight = 20

4. whom and who like it it and him like whom whom and him like him stu and boo like who her and him like who

5. touch your eye to your headtouch your head to your eyetouch your shoulders to your elbowtouch your eyes and ears to your eyes and earstouch your toes to your Toestouch your shoulders to your knees toes

6. say coke not pepsi or popsay soda not soda or pepsisay pepsi not koolaid or popsay say not pepsi or pepsi

7. public static void printStrings(String s, int n) {for (int i = 1; i <= n; i++) {

System.out.print(s + " ");} System.out.println();

}

8. System.out.println is an overloaded method.

9. The program changes the value of its tempc parameter, but this doesn’t affect thevariable tempc in main. The (incorrect) output is:

Body temp in C is: 0.0

10. (a) 1.6(b) 2(c) 36.0(d) 64.0(e) 10.0(f) 116.0(g) 7(h) 5(i) !5(j) 8.0

1044 Appendix A Answers to Self-Check Problems

3. three times two = 61 times three = 281 times 1 = 42 three times 1 = 21 times eight = 20

4. whom and who like it it and him like whom whom and him like him stu and boo like who her and him like who

5. touch your eye to your headtouch your head to your eyetouch your shoulders to your elbowtouch your eyes and ears to your eyes and earstouch your toes to your Toestouch your shoulders to your knees toes

6. say coke not pepsi or popsay soda not soda or pepsisay pepsi not koolaid or popsay say not pepsi or pepsi

7. public static void printStrings(String s, int n) {for (int i = 1; i <= n; i++) {

System.out.print(s + " ");} System.out.println();

}

8. System.out.println is an overloaded method.

9. The program changes the value of its tempc parameter, but this doesn’t affect thevariable tempc in main. The (incorrect) output is:

Body temp in C is: 0.0

10. (a) 1.6(b) 2(c) 36.0(d) 64.0(e) 10.0(f) 116.0(g) 7(h) 5(i) !5(j) 8.0

Appendix A Answers to Self-Check Problems 1045

(k) 11.0(l) 102.0(m)17.0(n) 20.0(o) 13.0(p) 14.0

11. 3 01 2 44 35 2 48 15 9 4

12. public static int min(int n1, int n2, int n3) {return Math.min(n1, Math.min(n2, n3));

}

13. public static int countQuarters(int cents) {return cents % 100 / 25;

}

14. (a) 6(b) 19(c) "q.e.d."(d) "ARCTURAN MEGADONKEY"(e) "E."(f) "egad"(g) 4(h) 1(i) 13(j) –1(k) "Arcturan Megadonkeys"(l) "b"(m)"Cyber"(n) "mega Corp"

15. quote.substring(5, 10).toUpperCase()quote.toLowerCase().substring(0, 4) + quote.substring(20, 26)

16. There are 10 tokens:• Hello• there.• 1+2• is• 3• and

Questions Section IV

Self-Check Problems 357

A fencepost loop executes a “loop-and-a-half” by execut-ing part of a loop’s body once before the loop begins.

A sentinel loop is a kind of fencepost loop that repeatedlyprocesses input until it is passed a particular value, butdoes not process the special value.

The boolean primitive type represents logical values ofeither true or false. Boolean expressions are used astests in if statements and loops. Boolean expressions canuse relational operators such as < or != as well as logical operators such as && or !.

Complex Boolean tests with logical operators such as &&or || are evaluated lazily: If the overall result is clearfrom evaluating the first part of the expression, later partsare not evaluated. This is called short-circuited evaluation.

Boolean variables (sometimes called “flags”) can storeBoolean values and can be used as loop tests.

A complex Boolean expression can be negated using a set of rules known as De Morgan’s Laws, in which each sub-expression is negated and all AND and OR operations are swapped.

A robust program checks for errors in user input. Betterrobustness can be achieved by looping and repromptingthe user to enter input when he or she types bad input. The Scanner class has methods like hasNextInt thatyou can use to “look ahead” for valid input.

Assertions are logical statements about a particular point in aprogram. Assertions are useful for proving properties abouthow a program will execute. Two useful types of assertionsare preconditions and postconditions, which are claims aboutwhat will be true before and after a method executes.

Self-Check Problems

Section 5.1: The while Loop

1. For each of the following while loops, state how many times the loop will execute its body. Remember that “zero,”“infinity,” and “unknown” are legal answers. Also, what is the output of the code in each case?

a. int x = 1;while (x < 100) {

System.out.print(x + " ");

x += 10;

}

b. int max = 10;while (max < 10) {

System.out.println("count down: " + max);

max––;

}

c. int x = 250;while (x % 3 != 0) {

System.out.println(x);

}358 Chapter 5 Program Logic and Indefinite Loops

d. int x = 2;while (x < 200) {

System.out.print(x + " ");

x *= x;

}

e. String word = "a";while (word.length() < 10) {

word = "b" + word + "b";

}

System.out.println(word);

f. int x = 100;

while (x > 0) {

System.out.println(x / 10);

x = x / 2;

}

2. Convert each of the following for loops into an equivalent while loop:a. for (int n = 1; n <= max; n++) {

System.out.println(n);

}

b. int total = 25;for (int number = 1; number <= (total / 2); number++) {

total = total – number;

System.out.println(total + " " + number);

}

c. for (int i = 1; i <= 2; i++) {for (int j = 1; j <= 3; j++) {

for (int k = 1; k <= 4; k++) {

System.out.print("*");

}

System.out.print("!");

}

System.out.println();

}

d. int number = 4;for (int count = 1; count <= number; count++) {

System.out.println(number);

number = number / 2;

}

3. Consider the following method:

public static void mystery(int x) {

int y = 1;

int z = 0;

while (2 * y <= x) {

y = y * 2;

358 Chapter 5 Program Logic and Indefinite Loops

d. int x = 2;while (x < 200) {

System.out.print(x + " ");

x *= x;

}

e. String word = "a";while (word.length() < 10) {

word = "b" + word + "b";

}

System.out.println(word);

f. int x = 100;

while (x > 0) {

System.out.println(x / 10);

x = x / 2;

}

2. Convert each of the following for loops into an equivalent while loop:a. for (int n = 1; n <= max; n++) {

System.out.println(n);

}

b. int total = 25;for (int number = 1; number <= (total / 2); number++) {

total = total – number;

System.out.println(total + " " + number);

}

c. for (int i = 1; i <= 2; i++) {for (int j = 1; j <= 3; j++) {

for (int k = 1; k <= 4; k++) {

System.out.print("*");

}

System.out.print("!");

}

System.out.println();

}

d. int number = 4;for (int count = 1; count <= number; count++) {

System.out.println(number);

number = number / 2;

}

3. Consider the following method:

public static void mystery(int x) {

int y = 1;

int z = 0;

while (2 * y <= x) {

y = y * 2;

358 Chapter 5 Program Logic and Indefinite Loops

d. int x = 2;while (x < 200) {

System.out.print(x + " ");

x *= x;

}

e. String word = "a";while (word.length() < 10) {

word = "b" + word + "b";

}

System.out.println(word);

f. int x = 100;

while (x > 0) {

System.out.println(x / 10);

x = x / 2;

}

2. Convert each of the following for loops into an equivalent while loop:a. for (int n = 1; n <= max; n++) {

System.out.println(n);

}

b. int total = 25;for (int number = 1; number <= (total / 2); number++) {

total = total – number;

System.out.println(total + " " + number);

}

c. for (int i = 1; i <= 2; i++) {for (int j = 1; j <= 3; j++) {

for (int k = 1; k <= 4; k++) {

System.out.print("*");

}

System.out.print("!");

}

System.out.println();

}

d. int number = 4;for (int count = 1; count <= number; count++) {

System.out.println(number);

number = number / 2;

}

3. Consider the following method:

public static void mystery(int x) {

int y = 1;

int z = 0;

while (2 * y <= x) {

y = y * 2;

358 Chapter 5 Program Logic and Indefinite Loops

d. int x = 2;while (x < 200) {

System.out.print(x + " ");

x *= x;

}

e. String word = "a";while (word.length() < 10) {

word = "b" + word + "b";

}

System.out.println(word);

f. int x = 100;

while (x > 0) {

System.out.println(x / 10);

x = x / 2;

}

2. Convert each of the following for loops into an equivalent while loop:a. for (int n = 1; n <= max; n++) {

System.out.println(n);

}

b. int total = 25;for (int number = 1; number <= (total / 2); number++) {

total = total – number;

System.out.println(total + " " + number);

}

c. for (int i = 1; i <= 2; i++) {for (int j = 1; j <= 3; j++) {

for (int k = 1; k <= 4; k++) {

System.out.print("*");

}

System.out.print("!");

}

System.out.println();

}

d. int number = 4;for (int count = 1; count <= number; count++) {

System.out.println(number);

number = number / 2;

}

3. Consider the following method:

public static void mystery(int x) {

int y = 1;

int z = 0;

while (2 * y <= x) {

y = y * 2;Self-Check Problems 359

z++;

}

System.out.println(y + " " + z);

}

For each of the following calls, indicate the output that the preceding method produces:

mystery(1);

mystery(6);

mystery(19);

mystery(39);

mystery(74);

4. Consider the following method:

public static void mystery(int x) {

int y = 0;

while (x % 2 == 0) {

y++;

x = x / 2;

}

System.out.println(x + " " + y);

}

For each of the following calls, indicate the output that the preceding method produces:

mystery(19);

mystery(42);

mystery(48);

mystery(40);

mystery(64);

5. Consider the following code:

Random rand = new Random();

int a = rand.nextInt(100);

int b = rand.nextInt(20) + 50;

int c = rand.nextInt(20 + 50);

int d = rand.nextInt(100) – 20;

int e = rand.nextInt(10) * 4;

What range of values can each variable (a, b, c, d, and e) have?

6. Write code that generates a random integer between 0 and 10 inclusive.

7. Write code that generates a random odd integer (not divisible by 2) between 50 and 99 inclusive.

8. For each of the do/while loops that follow, state the number of times that the loop will execute its body. Rememberthat “zero,” “infinity,” and “unknown” are legal answers. Also, what is the output of the code in each case?

a. int x = 1;do {

Self-Check Problems 359

z++;

}

System.out.println(y + " " + z);

}

For each of the following calls, indicate the output that the preceding method produces:

mystery(1);

mystery(6);

mystery(19);

mystery(39);

mystery(74);

4. Consider the following method:

public static void mystery(int x) {

int y = 0;

while (x % 2 == 0) {

y++;

x = x / 2;

}

System.out.println(x + " " + y);

}

For each of the following calls, indicate the output that the preceding method produces:

mystery(19);

mystery(42);

mystery(48);

mystery(40);

mystery(64);

5. Consider the following code:

Random rand = new Random();

int a = rand.nextInt(100);

int b = rand.nextInt(20) + 50;

int c = rand.nextInt(20 + 50);

int d = rand.nextInt(100) – 20;

int e = rand.nextInt(10) * 4;

What range of values can each variable (a, b, c, d, and e) have?

6. Write code that generates a random integer between 0 and 10 inclusive.

7. Write code that generates a random odd integer (not divisible by 2) between 50 and 99 inclusive.

8. For each of the do/while loops that follow, state the number of times that the loop will execute its body. Rememberthat “zero,” “infinity,” and “unknown” are legal answers. Also, what is the output of the code in each case?

a. int x = 1;do {

Self-Check Problems 361

Do you want to hear it again? y

She sells seashells by the seashore.

Do you want to hear it again? n

10. Write a method called zeroDigits that accepts an integer parameter and returns the number of digits in the numberthat have the value 0. For example, the call zeroDigits(5024036) should return 2, and zeroDigits(743)should return 0. The call zeroDigits(0) should return 1. (We suggest you use a do/while loop in your solution.)

11. Write a do/while loop that repeatedly prints random numbers between 0 and 1000 until a number above 900 isprinted. At least one line of output should always be printed, even if the first random number is above 900. Here is asample execution:

Random number: 235

Random number: 15

Random number: 810

Random number: 147

Random number: 915

Section 5.2: Fencepost Algorithms

12. Consider the flawed method printLetters that follows, which accepts a String as its parameter and attempts toprint the letters of the String, separated by dashes. For example, the call of printLetters("Rabbit") shouldprint R-a-b-b-i-t. The following code is incorrect:

public static void printLetters(String text) {

for (int i = 0; i < text.length(); i++) {

System.out.print(text.charAt(i) + "–");

}

System.out.println(); // to end the line of output

}

What is wrong with the code? How can it be corrected to produce the desired behavior?

13. Write a sentinel loop that repeatedly prompts the user to enter a number and, once the number –1 is typed, displaysthe maximum and minimum numbers that the user entered. Here is a sample dialogue:

Type a number (or –1 to stop): 5

Type a number (or –1 to stop): 2

Type a number (or –1 to stop): 17

Type a number (or –1 to stop): 8

Type a number (or –1 to stop): –1

Maximum was 17

Minimum was 2

If –1 is the first number typed, no maximum or minimum should be printed. In this case, the dialogue would looklike this:

Type a number (or –1 to stop): –1

Self-Check Problems 361

Do you want to hear it again? y

She sells seashells by the seashore.

Do you want to hear it again? n

10. Write a method called zeroDigits that accepts an integer parameter and returns the number of digits in the numberthat have the value 0. For example, the call zeroDigits(5024036) should return 2, and zeroDigits(743)should return 0. The call zeroDigits(0) should return 1. (We suggest you use a do/while loop in your solution.)

11. Write a do/while loop that repeatedly prints random numbers between 0 and 1000 until a number above 900 isprinted. At least one line of output should always be printed, even if the first random number is above 900. Here is asample execution:

Random number: 235

Random number: 15

Random number: 810

Random number: 147

Random number: 915

Section 5.2: Fencepost Algorithms

12. Consider the flawed method printLetters that follows, which accepts a String as its parameter and attempts toprint the letters of the String, separated by dashes. For example, the call of printLetters("Rabbit") shouldprint R-a-b-b-i-t. The following code is incorrect:

public static void printLetters(String text) {

for (int i = 0; i < text.length(); i++) {

System.out.print(text.charAt(i) + "–");

}

System.out.println(); // to end the line of output

}

What is wrong with the code? How can it be corrected to produce the desired behavior?

13. Write a sentinel loop that repeatedly prompts the user to enter a number and, once the number –1 is typed, displaysthe maximum and minimum numbers that the user entered. Here is a sample dialogue:

Type a number (or –1 to stop): 5

Type a number (or –1 to stop): 2

Type a number (or –1 to stop): 17

Type a number (or –1 to stop): 8

Type a number (or –1 to stop): –1

Maximum was 17

Minimum was 2

If –1 is the first number typed, no maximum or minimum should be printed. In this case, the dialogue would looklike this:

Type a number (or –1 to stop): –1

362 Chapter 5 Program Logic and Indefinite Loops

Section 5.3: The booleanType

14. Consider the following variable declarations:

int x = 27;

int y = –1;

int z = 32;

boolean b = false;

What is the value of each of the following Boolean expressions?

a. !bb. b || truec. (x > y) && (y > z)d. (x == y) || (x <= z)e. !(x % 2 == 0)f. (x % 2 != 0) && b

g. b && !bh. b || !bi. (x < y) == b

j. !(x / 2 == 13) || b || (z * 3 == 96)

k. (z < x) == falsel. !((x > 0) && (y < 0))

15. Write a method called isVowel that accepts a character as input and returns true if that character is a vowel (a, e, i,o, or u). For an extra challenge, make your method case-insensitive.

16. The following code attempts to examine a number and return whether that number is prime (i.e., has no factors otherthan 1 and itself). A flag named prime is used. However, the Boolean logic is not implemented correctly, so themethod does not always return the correct answer. In what cases does the method report an incorrect answer? Howcan the code be changed so that it will always return a correct result?

public static boolean isPrime(int n) {

boolean prime = true;

for (int i = 2; i < n; i++) {

if (n % i = = 0) {

prime = false;

} else {

prime = true;

}

}

return prime;

}

17. The following code attempts to examine a String and return whether it contains a given letter. A flag named foundis used. However, the Boolean logic is not implemented correctly, so the method does not always return the correct

362 Chapter 5 Program Logic and Indefinite Loops

Section 5.3: The booleanType

14. Consider the following variable declarations:

int x = 27;

int y = –1;

int z = 32;

boolean b = false;

What is the value of each of the following Boolean expressions?

a. !bb. b || truec. (x > y) && (y > z)d. (x == y) || (x <= z)e. !(x % 2 == 0)f. (x % 2 != 0) && b

g. b && !bh. b || !bi. (x < y) == b

j. !(x / 2 == 13) || b || (z * 3 == 96)

k. (z < x) == falsel. !((x > 0) && (y < 0))

15. Write a method called isVowel that accepts a character as input and returns true if that character is a vowel (a, e, i,o, or u). For an extra challenge, make your method case-insensitive.

16. The following code attempts to examine a number and return whether that number is prime (i.e., has no factors otherthan 1 and itself). A flag named prime is used. However, the Boolean logic is not implemented correctly, so themethod does not always return the correct answer. In what cases does the method report an incorrect answer? Howcan the code be changed so that it will always return a correct result?

public static boolean isPrime(int n) {

boolean prime = true;

for (int i = 2; i < n; i++) {

if (n % i = = 0) {

prime = false;

} else {

prime = true;

}

}

return prime;

}

17. The following code attempts to examine a String and return whether it contains a given letter. A flag named foundis used. However, the Boolean logic is not implemented correctly, so the method does not always return the correct

Self-Check Problems 363

answer. In what cases does the method report an incorrect answer? How can the code be changed so that it willalways return a correct result?

public static boolean contains(String str, char ch) {

boolean found = false;

for (int i = 0; i < str.length(); i++) {

if (str.charAt(i) == ch) {

found = true;

} else {

found = false;

}

}

return found;

}

18. Using “Boolean Zen,” write an improved version of the following method, which returns whether the given Stringstarts and ends with the same character:

public static boolean startEndSame(String str) {

if (str.charAt(0) == str.charAt(str.length() – 1)) {

return true;

} else {

return false

}

}

19. Using “Boolean Zen,” write an improved version of the following method, which returns whether the given numberof cents would require any pennies (as opposed to being an amount that could be made exactly using coins otherthan pennies):

public static boolean hasPennies(int cents) {

boolean nickelsOnly = (cents % 5 == 0);

if (nickelsOnly == true) {

return false;

} else {

return true;

}

}

20. Consider the following method:

public static int mystery(int x, int y) {

while (x != 0 && y != 0) {

if (x < y) {

y –= x;

} else {

x –= y;

}

Self-Check Problems 363

answer. In what cases does the method report an incorrect answer? How can the code be changed so that it willalways return a correct result?

public static boolean contains(String str, char ch) {

boolean found = false;

for (int i = 0; i < str.length(); i++) {

if (str.charAt(i) == ch) {

found = true;

} else {

found = false;

}

}

return found;

}

18. Using “Boolean Zen,” write an improved version of the following method, which returns whether the given Stringstarts and ends with the same character:

public static boolean startEndSame(String str) {

if (str.charAt(0) == str.charAt(str.length() – 1)) {

return true;

} else {

return false

}

}

19. Using “Boolean Zen,” write an improved version of the following method, which returns whether the given numberof cents would require any pennies (as opposed to being an amount that could be made exactly using coins otherthan pennies):

public static boolean hasPennies(int cents) {

boolean nickelsOnly = (cents % 5 == 0);

if (nickelsOnly == true) {

return false;

} else {

return true;

}

}

20. Consider the following method:

public static int mystery(int x, int y) {

while (x != 0 && y != 0) {

if (x < y) {

y –= x;

} else {

x –= y;

}364 Chapter 5 Program Logic and Indefinite Loops

}

return x + y;

}

For each of the following calls, indicate the value that is returned:

mystery(3, 3)

mystery(5, 3)

mystery(2, 6)

mystery(12, 18)

mystery(30, 75)

21. The following code is a slightly modified version of actual code that was in the Microsoft Zune music player in 2008.The code attempts to calculate today’s date by determining how many years and days have passed since 1980.Assume the existence of methods for getting the total number of days since 1980 and for determining whether agiven year is a leap year:

int days = getTotalDaysSince1980();

year = 1980;

while (days > 365) { // subtract out years

if (isLeapYear(year)) {

if (days > 366) {

days –= 366;

year += 1;

}

} else {

days –= 365;

year += 1;

}

}

Thousands of Zune players locked up on January 1, 2009, the first day after the end of a leap year since the Zunewas released. (Microsoft quickly released a patch to fix the problem.) What is the problem with the preceding code,and in what cases will it exhibit incorrect behavior? How can it be fixed?

22. Consider the following variable declarations:

int x = 27;

int y = –1;

int z = 32;

boolean b = false;

Write a new Boolean expression that is the negation of each of the following Boolean expressions. Use De Morgan’slaws rather than simply writing a ! at the beginning of each entire expression.

a. b

b. (x > y) && (y > z)c. (x == y) || (x <= z)

364 Chapter 5 Program Logic and Indefinite Loops

}

return x + y;

}

For each of the following calls, indicate the value that is returned:

mystery(3, 3)

mystery(5, 3)

mystery(2, 6)

mystery(12, 18)

mystery(30, 75)

21. The following code is a slightly modified version of actual code that was in the Microsoft Zune music player in 2008.The code attempts to calculate today’s date by determining how many years and days have passed since 1980.Assume the existence of methods for getting the total number of days since 1980 and for determining whether agiven year is a leap year:

int days = getTotalDaysSince1980();

year = 1980;

while (days > 365) { // subtract out years

if (isLeapYear(year)) {

if (days > 366) {

days –= 366;

year += 1;

}

} else {

days –= 365;

year += 1;

}

}

Thousands of Zune players locked up on January 1, 2009, the first day after the end of a leap year since the Zunewas released. (Microsoft quickly released a patch to fix the problem.) What is the problem with the preceding code,and in what cases will it exhibit incorrect behavior? How can it be fixed?

22. Consider the following variable declarations:

int x = 27;

int y = –1;

int z = 32;

boolean b = false;

Write a new Boolean expression that is the negation of each of the following Boolean expressions. Use De Morgan’slaws rather than simply writing a ! at the beginning of each entire expression.

a. b

b. (x > y) && (y > z)c. (x == y) || (x <= z)

364 Chapter 5 Program Logic and Indefinite Loops

}

return x + y;

}

For each of the following calls, indicate the value that is returned:

mystery(3, 3)

mystery(5, 3)

mystery(2, 6)

mystery(12, 18)

mystery(30, 75)

21. The following code is a slightly modified version of actual code that was in the Microsoft Zune music player in 2008.The code attempts to calculate today’s date by determining how many years and days have passed since 1980.Assume the existence of methods for getting the total number of days since 1980 and for determining whether agiven year is a leap year:

int days = getTotalDaysSince1980();

year = 1980;

while (days > 365) { // subtract out years

if (isLeapYear(year)) {

if (days > 366) {

days –= 366;

year += 1;

}

} else {

days –= 365;

year += 1;

}

}

Thousands of Zune players locked up on January 1, 2009, the first day after the end of a leap year since the Zunewas released. (Microsoft quickly released a patch to fix the problem.) What is the problem with the preceding code,and in what cases will it exhibit incorrect behavior? How can it be fixed?

22. Consider the following variable declarations:

int x = 27;

int y = –1;

int z = 32;

boolean b = false;

Write a new Boolean expression that is the negation of each of the following Boolean expressions. Use De Morgan’slaws rather than simply writing a ! at the beginning of each entire expression.

a. b

b. (x > y) && (y > z)c. (x == y) || (x <= z)

Self-Check Problems 365

d. (x % 2 != 0) && be. (x / 2 == 13) || b || (z * 3 == 96)f. (z < x) && (z > y || x >= y)

Section 5.4: User Errors

23. The following code is not robust against invalid user input. Describe how to change the code so that it will not pro-ceed until the user has entered a valid age and grade point average (GPA). Assume that any int is a legal age andthat any double is a legal GPA.

Scanner console = new Scanner(System.in);

System.out.print("Type your age: ");

int age = console.nextInt();

System.out.print("Type your GPA: ");

double gpa = console.nextDouble();

For an added challenge, modify the code so that it rejects invalid ages (for example, numbers less than 0) and GPAs(say, numbers less than 0.0 or greater than 4.0).

24. Consider the following code:

Scanner console = new Scanner(System.in);

System.out.print("Type something for me! ");

if (console.hasNextInt()) {

int number = console.nextInt();

System.out.println("Your IQ is " + number);

} else if (console.hasNext()) {

String token = console.next();

System.out.println("Your name is " + token);

}

What is the output when the user types the following values?

a. Janeb. 56c. 56.2

25. Write a piece of code that prompts the user for a number and then prints a different message depending on whetherthe number was an integer or a real number. Here are two sample dialogues:

Type a number: 42.5

You typed the real number 42.5

Type a number: 3

You typed the integer 3

26. Write code that prompts for three integers, averages them, and prints the average. Make your code robust againstinvalid input. (You may want to use the getInt method discussed in this chapter.)

Answers Section IV

Appendix A Answers to Self-Check Problems 1055

Invalid values are when a = 0 (because it makes the denominator of the equationequal 0), or when b2 - 4ac < 0, because then it has no real square root.

26. The code fails when more than one number is odd, because it uses else if ratherthan if. The tests should not be nested because they are not mutually exclusive;more than one number could be odd. The following code fixes the problem:

public static void printNumOdd(int n1, int n2, int n3) {int count = 0;if (n1 % 2 != 0) {

count++;}if (n2 % 2 != 0) {

count++;}if (n3 % 2 != 0) {

count++;}System.out.println(count +

" of the 3 numbers are odd.");}

The following version without if statements also works:

public static void printNumOdd(int n1, int n2, int n3) {int count = n1 % 2 + n2 % 2 + n3 % 2;System.out.println(count +

" of the 3 numbers are odd.");}

Chapter 5

1. (a) Executes body 10 times.Output is1 11 21 31 41 51 61 71 81 91

(b) Executes body 0 times.No output.

(c) Loops infinitely.Output is250250250...

(d) Executes body 3 times.Output is2 4 161056 Appendix A Answers to Self-Check Problems

(e) Executes body 5 times.Output isbbbbbabbbbb

(f) Executes body 7 times.Output is10521000

2. (a) int n = 1;while (n <= max) {

System.out.println(n);n++;

}(b) int total = 25;

int number = 1;while (number <= (total / 2)) {

total = total – number; System.out.println(total + " " + number);number++;

}(c) int i = 1;

while (i <= 2) {int j = 1;while (j <= 3) {

int k = 1;while (k <= 4) {

System.out.print("*");k++;

} System.out.print("!"); j++;

}System.out.println();i++;

}(d) int number = 4;

int count = 1;while (count <= number) {

System.out.println(number); number = number / 2;

1056 Appendix A Answers to Self-Check Problems

(e) Executes body 5 times.Output isbbbbbabbbbb

(f) Executes body 7 times.Output is10521000

2. (a) int n = 1;while (n <= max) {

System.out.println(n);n++;

}(b) int total = 25;

int number = 1;while (number <= (total / 2)) {

total = total – number; System.out.println(total + " " + number);number++;

}(c) int i = 1;

while (i <= 2) {int j = 1;while (j <= 3) {

int k = 1;while (k <= 4) {

System.out.print("*");k++;

} System.out.print("!"); j++;

}System.out.println();i++;

}(d) int number = 4;

int count = 1;while (count <= number) {

System.out.println(number); number = number / 2;

Appendix A Answers to Self-Check Problems 1057

count++;}

3. Method call Outputmystery(1); 1 0mystery(6); 4 2mystery(19); 16 4mystery(39); 32 5mystery(74); 64 6

4. Method call Outputmystery(19); 19 0mystery(42); 21 1mystery(48); 3 4mystery(40); 5 3mystery(64); 1 6

5. a: 0 through 99 inclusiveb: 50 through 69 inclusivec: 0 through 69 inclusived: -20 through 79 inclusivee: 0, 4, 8, 12, 16, 20, 24, 28, 32, or 36

6. Random rand = new Random();int num = rand.nextInt(11);

7. Random rand = new Random();int num = rand.nextInt(25) * 2 + 50;

8. (a) Executes body 10 times.Output is1 11 21 31 41 51 61 71 81 91

(b) Loops infinitely.Output iscount down: 10 count down: 9...

(c) Loops infinitely.Output is250250250...

(d) Executes body 2 times.Output is10050

Appendix A Answers to Self-Check Problems 1057

count++;}

3. Method call Outputmystery(1); 1 0mystery(6); 4 2mystery(19); 16 4mystery(39); 32 5mystery(74); 64 6

4. Method call Outputmystery(19); 19 0mystery(42); 21 1mystery(48); 3 4mystery(40); 5 3mystery(64); 1 6

5. a: 0 through 99 inclusiveb: 50 through 69 inclusivec: 0 through 69 inclusived: -20 through 79 inclusivee: 0, 4, 8, 12, 16, 20, 24, 28, 32, or 36

6. Random rand = new Random();int num = rand.nextInt(11);

7. Random rand = new Random();int num = rand.nextInt(25) * 2 + 50;

8. (a) Executes body 10 times.Output is1 11 21 31 41 51 61 71 81 91

(b) Loops infinitely.Output iscount down: 10 count down: 9...

(c) Loops infinitely.Output is250250250...

(d) Executes body 2 times.Output is10050

10. ! public static int zeroDigits(int number) {

if(number == 0) {return 1;

}

int count = 0;while(number > 0) {

if(number % 10 == 0) {count++;

}number /= 10;

}return count;

}

Appendix A Answers to Self-Check Problems 1059

12. The code has a fencepost problem; it will print a dash after the last letter. The fol-lowing code corrects the problem:

public static void printLetters(String text) {if (text.length() > 0) {

System.out.print(text.charAt(0));for (int i = 1; i < text.length(); i++) {

System.out.print("-" + text.charAt(i));}

}System.out.println(); // to end the line of output

}

13. int SENTINEL = -1;System.out.print("Type a number (or " + SENTINEL + " to stop): ");Scanner console = new Scanner(System.in);int input = console.nextInt();int min = input;int max = input;

while (input != SENTINEL) {if (input < min) {

min = input;} else if (input > max) {

max = input;}System.out.print("Type a number (or " + SENTINEL

+ " to stop): ");input = console.nextInt();

}if (min != SENTINEL) {

System.out.println("Maximum was " + max);System.out.println("Minimum was " + min);

}

14. (a) true(b) true(c) false(d) true(e) true(f) false(g) false(h) true(i) true(j) true(k) true(l) false

1060 Appendix A Answers to Self-Check Problems

15. public static boolean isVowel(char c) {c = Character.toLowerCase(c); // case-insensitive return c == 'a' || c == 'e' || c == 'i' ||

c == 'o' || c == 'u';}

An alternative version follows:

public static boolean isVowel(char c) {String vowels = "aeiouAEIOU";return vowels.indexOf(c) >= 0;

}

16. In this code the boolean flag isn’t being used properly, because if the code finds afactor of the number, prime will be set to false, but on the next pass through theloop, if the next number isn’t a factor, prime will be reset to true again. The fol-lowing code fixes the problem:

public static boolean isPrime(int n) {boolean prime = true;for (int i = 2; i < n; i++) {

if (n % i == 0) {prime = false;

}}return prime;

}

17. In this code the boolean flag isn’t being used properly, because if the code findsthe character, found will be set to true, but on the next pass through the loop, ifthe next character isn’t ch, found will be reset to false again. The following codefixes the problem:

public static boolean contains(String str, char ch) {boolean found = false;for (int i = 0; i < str.length(); i++) {

if (str.charAt(i) == ch) {found = true;

}}return found;

}

18. public static boolean startEndSame(String str) {return str.charAt(0) == str.charAt(str.length() – 1);

}

Appendix A Answers to Self-Check Problems 1061

19. public static boolean hasPennies(int cents) {return cents % 5 != 0;

}

20. Method call Value returnedmystery(3, 3) 3mystery(5, 3) 1mystery(2, 6) 2mystery(12, 18) 6mystery(30, 75) 15

21. The code will get stuck in an infinite loop when the current date is the end of a leapyear. On December 31 the days value will be 366, so code enters the if(isLeapYear) statement but does not enter the if (days > 366) statement. Sothe loop does not subtract any days and never terminates. The code can be fixed byadding a break statement to the loop (see Appendix D):

int days = getTotalDaysSince1980();year = 1980;while (days > 365) { // subtract out years

if (isLeapYear(year)) {if (days > 366) {

days -= 366;year += 1;

} else { //break; // new code here

} //} else {

days -= 365;year += 1;

}}

22. (a) !b(b) (x <= y) || (y <= z) (c) (x != y) && (x > z) (d) (x % 2 == 0) || !b(e) (x / 2 != 13) && !b && (z * 3 != 96) (f) (z >= x) || (z <= y && x < y)

23. The code should reprompt for a valid integer for the user’s age and a valid realnumber for the user’s GPA. If the user types a token of the wrong type, the line ofinput should be consumed and the user should be reprompted.

The following code implements the corrected behavior:

Scanner console = new Scanner(System.in); System.out.print("Type your age: ");