5Control Statements: Part 2 OB J ECT IVES In this chapter you will learn: ■ The essentials of counter-controlled repetition. ■ To use the for and do…while repetition statements to execute statements in a program repeatedly. ■ To understand multiple selection using the switch selection statement. ■ To use the break and continue program control statements to alter the flow of control. ■ To use the logical operators to form complex conditional expressions in control statements. Not everything that can be counted counts, and not every thing that counts can be counted. —Albert Einstein Who can control his fate? —William Shakespeare The used key is always bright. —Benjamin Franklin Intelligence … is the faculty of making artificial objects, especially tools to make tools. —Henri Bergson Every advantage in the past is judged in the light of the final issue. —Demosthenes Chapter 5 Control Statements: Part 2 153 Name: Date: Section: Assignment Checklist Exercises Assigned: Circle assignments Date Due Prelab Activities Matching YES NO Fill in the Blank 13, 14, 15, 16, 17, 18, 19, 20, 21 Short Answer 22, 23, 24, 25, 26 Programming Output 27, 28, 29, 30, 31, 32, 33, 34, 35, 36 Correct the Code 37, 38, 39, 40 Lab Exercises Exercise 1 — Triangles YES NO Follow-Up Question and Activity 1 Exercise 2 — Sales YES NO Follow-Up Questions and Activities 1, 2 Exercise 3 — Pythagorean Triples YES NO Follow-Up Questions and Activities 1, 2, 3 Debugging YES NO Postlab Activities Coding Exercises 1, 2, 3, 4, 5, 6, 7, 8 Programming Challenges 1, 2 Chapter 5 Control Statements: Part 2 155 Prelab Activities Name: Date: Section: Matching After reading Chapter 5 of Java How to Program: Seventh Edition, answer the given questions. These questions are intended to test and reinforce your understanding of key Java concepts. You may answer these questions ei- ther before or during the lab. For each term in the left column, write the letter for the description that best matches the term from the right column. Term Description E H J A B F D L I G C K 1. && 2. || 3. ! 4. switch 5. continue 6. break 7. for repetition statement 8. do…while repetition statement 9. | 10. off-by-one error 11. & 12. constant a) Handles a series of decisions, in which a particular variable or expression is tested for values it can as- sume and different actions are taken. b) Skips any remaining statements in the body of a rep- etition statement and proceeds with the next itera- tion of the loop. c) Boolean logical AND d) Handles all of the details of counter-controlled rep- etition. e) Conditional AND. f) Causes immediate exit from a repetition statement. g) Can be caused by the use of an incorrect relational operator or using an incorrect final value of a loop counter in the condition of a repetition statement. h) Conditional OR. i) Boolean logical inclusive OR. j) Logical negation. k) A variable which contains a value which does not change for the entire program. l) Repetition statement that tests the loop-continua- tion condition at the end of the loop, so that the body of the loop will execute at least once. Prelab Activities Name: Fill in the Blank Chapter 5 Control Statements: Part 2 157 Name: Date: Section: Fill in the Blank Fill in the blanks for each of the following statements: 13. The %b format specifier causes the value of a boolean expression to be output as the word true or the word false based on the expression’s value. 14. Typically, for statements are used for counter-controlled repetition and while statements are used for sentinel-controlled repetition. 15. In most programs, it is necessary to include a(n) break statement after the statements for each case in a switch statement. 16. The scope of a variable defines where it can be referenced in a program by using just the variable’s name. 17. Logical operators may be used to form complex conditions by combining conditions. 18. Placing a semicolon after the header of a for statement is normally a(n) logic error. 19. Programs should control counting loops with integer values. 20. Infinite loops occur when the loop-continuation condition in a repetition statement never becomes false . 21. The expression in parentheses following keyword switch is called the controlling expression of the switch . Prelab Activities Name: Short Answer Chapter 5 Control Statements: Part 2 159 Name: Date: Section: Short Answer Answer the following questions in the space provided. Your answers should be concise; aim for two or three sen- tences. 22. What is required to perform counter-controlled repetition? Counter-controlled repetition requires the name of a control variable, the initial value of the control variable, the increment or decrement by which the control variable is modified each time through the loop, and the condition that tests for the final value of the control variable. 23. Why should programs control counting loops with integers and not with floating-point numbers? Programs should control counting loops with integers because floating-point values may be approximate. Count- ing with floating-point values may result in imprecise counter values and inaccurate tests for termination. 24. Explain why placing a semicolon after the header of a for statement is a logic error and not a compilation error. Placing a semicolon after the for statement header is not a compilation error because Java treats the semicolon as an empty statement, which satisfies the requirement that the for statement have at least one statement in its body. This normally is a logic error because the code will compile, but will not execute correctly. 25. Differentiate between the while and the do…while repetition statements. In a while statement the program tests the loop-continuation condition at the beginning of the loop, before per- forming the body of the loop. If the initial condition is false, the body does not execute. The do…while state- ment tests the condition after performing the body of the loop, so the body of the loop always executes at least once. 26. Explain why an infinite loop can occur and how one can be prevented. An infinite loop occurs in a repetition statement when the loop-continuation condition never becomes false. In a counter-controlled loop, ensure that the control variable value is modified in a way that will eventually cause the loop-continuation condition to become false. In a sentinel-controlled loop ensure that the sentinel value is eventually input. Prelab Activities Name: Programming Output Chapter 5 Control Statements: Part 2 161 Name: Date: Section: Programming Output For each of the given program segments, read the code and write the output in the space provided below each program. [Note: Do not execute these programs on a computer.] For the following questions, assume that the code segments are contained within the main method of a Java ap- plication. For questions 27–30, use the following code segment: 27. What will be the output if the following code is placed at line 4 of the preceding code? Your answer: 28. What will be the output if the following code is placed at line 4 of the preceding code? Your answer: 1 int startingValue; 2 int terminatingValue; 3 int stepValue; 4 5 for ( int i = startingValue; i < terminatingValue; i += stepValue ) 6 System.out.printf( "%d ", i ); 1 startingValue = 0; 2 terminatingValue = 5; 3 stepValue = 1; 0 1 2 3 4 1 startingValue = -3; 2 terminatingValue = 2; 3 stepValue = 1; -3 -2 -1 0 1 Prelab Activities Name: Programming Output 162 Control Statements: Part 2 Chapter5 29. What will be the output if the following code is placed at line 4 of the preceding code? Your answer: No Output 30. What will be the output if the following code is placed at line 4 of the preceding code? Your answer: For questions 31–35, use the following class definition: 1 startingValue = 6; 2 terminatingValue = 5; 3 stepValue = 1; 1 startingValue = 0; 2 terminatingValue = 5; 3 stepValue = 3; 0 3 1 int startingValue; 2 int terminatingValue; 3 int stepValue; 4 5 for ( int i = startingValue; i <= terminatingValue; i += stepValue ) 6 { 7 switch( i ) 8 { 9 case 0: 10 System.out.print( "Hello there, " ); 11 break; 12 case 1: 13 System.out.println( "What’s up? " ); 14 break; 15 case 2: 16 System.out.println( "How are you doing? " ); 17 break; 18 case 3: 19 System.out.println( "Terrific. " ); 20 break; 21 case 4: 22 System.out.println( "Beautiful day isn't it? " ); 23 break; 24 case 5: 25 System.out.println( "Yes it is. " ); 26 break; 27 default: 28 System.out.println( "See you later. " ); 29 } // end switch 30 } // end for Prelab Activities Name: Programming Output Chapter 5 Control Statements: Part 2 163 31. What will be the output if the following code is placed at line 4 of the preceding class definition? Your answer: 32. What will be the output if the following code is placed at line 4 of the preceding code? Your answer: 33. What will be the output if the following code is placed at line 4 of the preceding code? Your answer: 1 startingValue = 0; 2 terminatingValue = 6; 3 stepValue = 2; Hello there, How are you doing? Beautiful day isn’t it? See you later. 1 startingValue = 0; 2 terminatingValue = 6; 3 stepValue = 3; Hello there, Terrific. See you later. 1 startingValue = -3; 2 terminatingValue = 2; 3 stepValue = 1; See you later. See you later. See you later. Hello there, What’s up? How are you doing? Prelab Activities Name: Programming Output 164 Control Statements: Part 2 Chapter5 34. What will be the output if the following code is placed at line 4 of the preceding code? Your answer: 35. What will be the output if the following code is placed at line 4 of the preceding code? Your answer: No Output 36. What is output by the following code segment? Your answer: 1 startingValue = -5; 2 terminatingValue = 1; 3 stepValue = 2; See you later. See you later. See you later. What’s up? 1 startingValue = 10; 2 terminatingValue = 5; 3 stepValue = 1; 1 for ( int i = 0; i <= 11; i++ ) 2 { 3 if ( i % 2 == 0 ) 4 continue; 5 6 if ( i == 11 ) 7 break; 8 9 System.out.printf( "%d ", i ); 10 } // end for 1 3 5 7 9 Prelab Activities Name: Correct the Code Chapter 5 Control Statements: Part 2 165 Name: Date: Section: Correct the Code Determine if there is an error in each of the following program segments. If there is an error, specify whether it is a logic error or a compilation error, circle the error in the program and write the corrected code in the space provided after each problem. If the code does not contain an error, write “no error.” [Note: There may be more than one error in each program segment.] 37. The following for loop should calculate the product of the integers in the range 1–5. Your answer: • Variable product must be initialized outside of the for loop (line 1). Logic error. 38. The following for loop should print the sum of consecutive odd and even integers in the range 1–10. The expected output is shown below the code. 1 for ( int i = 1; i <= 5; i++ ) 2 { 3 int product = 1; 4 product *= i; 5 } 1 2 3 for ( int i = 1; i <= 5; i++ ) 4 product *= i; 1 for ( int i = 1, j = 1; i <= 10 && j <= 10; i++, j++) 2 System.out.printf( "%d + %d = %d\n", i, j, ( i + j ) ); 1 + 2 = 3 3 + 4 = 7 5 + 6 = 11 7 + 8 = 15 9 + 10 = 19 int product = 1; Prelab Activities Name: Correct the Code 166 Control Statements: Part 2 Chapter5 Your answer: • On line 1, variable j should be initialized to 2 and both i and j should be incremented by 2 after each iteration. Logic error. 39. The following for loop should loop 10 times and compute the product of i times 2 plus 1 in each iteration. For example, if the loop counter is 4, the program should print 4 * 2 + 1 = 9. Your answer: • The preincrement operator on line 2 cannot be used because the expression in parentheses cannot be modified. The line should use a simple addition statement. Compilation error. 40. The following switch statement should print either "x is 5", "x is 10" or "x is neither 5 nor 10". Your answer: No Error 1 for ( int i = 1, j = ; i <= 10 && j <= 10; ) 2 System.out.printf( "%d + %d = %d\n", i, j, ( i + j ) ); 1 for ( int i = 1; i <= 10; i++ ) 2 System.out.printf( "%d * 2 + 1 = %d", i, ( ++( i * 2 ) ) ); 3 1 for ( int i = 1; i <= 10; i++ ) 2 System.out.printf( "%d * 2 + 1 = %d", i, ( i * 2 ) + 1 ); 3 1 switch ( x ) 2 { 3 case 5: 4 System.out.println( "x is 5" ); 5 break; 6 case 10: 7 System.out.println( "x is 10" ); 8 break; 9 default: 10 System.out.println( "x is neither 5 nor 10" ); 11 break; 12 } // end switch 2 i+=2, j+=2 Chapter 5 Control Statements: Part 2 167 Lab Exercises Name: Date: Section: Lab Exercise 1 — Triangles The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Problem Description 3. Sample Output 4. Program Template (Fig. L 5.1 and Fig. L 5.2) 5. Problem-Solving Tips 6. Follow-Up Question and Activity The program template represents a complete working Java program with one or more key lines of code replaced with comments. Read the problem description and examine the output, then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up question. The source code for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel. Lab Objectives This lab was designed to reinforce programming concepts from Chapter 5 of Java How To Program: Seventh Edi- tion. In this lab, you will practice: • Nested for loops. • Using counter-controlled repetition. The follow-up question and activity also will give you practice in: • Using techniques from one program to perform a similar task in another program. Problem Description Write an application that displays the following patterns separately, one below the other. Use for loops to gen- erate the patterns. All asterisks (*) should be printed by a single statement of the form System.out.print( "*" ); which causes the asterisks to print side by side. A statement of the form Sys- tem.out.println(); can be used to move to the next line. A statement of the form System.out.print( " " ); can be used to display a space for the last two patterns. There should be no other output statements in the pro- gram. Lab Exercises Name: Lab Exercise 1 — Triangles 168 Control Statements: Part 2 Chapter5 Sample Output Template * ** *** **** ***** ****** ******* ******** ********* ********** ********** ********* ******** ******* ****** ***** **** *** ** * ********** ********* ******** ******* ****** ***** **** *** ** * * ** *** **** ***** ****** ******* ******** ********* ********** 1 // Lab 1: Triangles.java 2 // Program prints four triangles, one below the other 3 public class Triangles 4 { Fig. L 5.1 | Triangles.java. (Part 1 of 2.) Lab Exercises Name: Lab Exercise 1 — Triangles Chapter 5 Control Statements: Part 2 169 Problem-Solving Tips 1. For the first triangle use a nested for statement in which the outer loop counts rows and the inner loop counts columns. The inner loop for the first triangle should count from 1 to the current row number. 2. For the second triangle use a nested for statement in which the outer loop counts backward from 10 to 1. The inner loop should be identical to the one used for the first triangle. 3. The last two patterns require that each row begin with an appropriate number of blank spaces. 4. For the third and fourth triangles use two separate inner loops—one for displaying spaces and one for displaying asterisks. 5. If you have any questions as you proceed, ask your lab instructor for assistance. 5 // draw four triangles 6 public void drawTriangles() 7 { 8 int row; // the row position 9 int column; // the column position 10 int space; // number of spaces to print 11 12 // first triangle 13 /* Write code to display the first triangle. Use nested for loops. The 14 outer loop should control which row of asterisks is being displayed. 15 The inner loop should display one asterisk at a time. */ 16 17 // second triangle 18 /* Write code to display the second triangle using techniques similar to 19 the first triangle */ 20 21 // third triangle 22 /* Write code to display the third triangle. The outer for loop should 23 contain two separate inner for loops--one to display spaces and one to 24 display asterisks. */ 25 26 // fourth triangle 27 /* Write code to display the fourth triangle using techniques similar to 28 the third triangle. */ 29 } // end method drawTriangles 30 } // end class Triangles 1 // Lab 1: TrianglesTest.java 2 // Test application for class Triangles 3 public class TrianglesTest 4 { 5 public static void main( String args[] ) 6 { 7 Triangles application = new Triangles(); 8 application.drawTriangles(); 9 } // end main 10 } // end class TrianglesTest Fig. L 5.2 | TrianglesTest.java Fig. L 5.1 | Triangles.java. (Part 2 of 2.) Lab Exercises Name: Lab Exercise 1 — Triangles 170 Control Statements: Part 2 Chapter5 Solution 1 // Lab 1: Triangles.java 2 // Program prints four triangles, one below the other 3 public class Triangles 4 { 5 // draw four triangles 6 public void drawTriangles() 7 { 8 int row; // the row position 9 int column; // the column position 10 int space; // number of spaces to print 11 12 // first triangle 13 for ( row = 1; row <= 10; row++ ) 14 { 15 for ( column = 1; column <= row; column++ ) 16 System.out.print( "*" ); 17 18 System.out.println(); 19 } // end for loop 20 21 System.out.println(); 22 23 // second triangle 24 for ( row = 10; row >= 1; row-- ) 25 { 26 for ( column = 1; column <= row; column++ ) 27 System.out.print( "*" ); 28 29 System.out.println(); 30 } // end for loop 31 32 System.out.println(); 33 34 // third triangle 35 for ( row = 10; row >= 1; row-- ) 36 { 37 for ( space = 10; space > row; space-- ) 38 System.out.print( " " ); 39 40 for ( column = 1; column <= row; column++ ) 41 System.out.print( "*" ); 42 43 System.out.println(); 44 } // end for loop 45 46 System.out.println(); 47 48 // fourth triangle 49 for ( row = 10; row >= 1; row-- ) { 50 51 for ( space = 1; space < row; space++ ) 52 System.out.print( " " ); 53 54 for ( column = 10; column >= row; column-- ) 55 System.out.print( "*" ); 56 Lab Exercises Name: Lab Exercise 1 — Triangles Chapter 5 Control Statements: Part 2 171 Follow-Up Question and Activity 1. Using the techniques of the third and fourth triangles in Lab Exercise 1, display two triangles in the format shown below. 57 System.out.println(); 58 } // end for loop 59 } // end method drawTriangles 60 } // end class Triangles 1 // Lab 1: TrianglesTest.java 2 // Test application for class Triangles 3 public class TrianglesTest 4 { 5 public static void main( String args[] ) 6 { 7 Triangles application = new Triangles(); 8 application.drawTriangles(); 9 } // end main 10 } // end class TrianglesTest ********* ******* ***** *** * * *** ***** ******* ********* 1 // Lab 1: Triangles.java 2 // Program prints four triangles, one below the other 3 public class Triangles 4 { 5 // draw four triangles 6 public void drawTriangles() 7 { 8 int row; // the row position 9 int column; // the column position 10 int space; // number of spaces to print 11 12 // first triangle 13 for ( row = 0; row <= 4; row++ ) 14 { 15 for ( column = row; column >= 0; column-- ) 16 System.out.print( " " ); 17 18 for ( column = 2 * row; column <= 8; column++ ) 19 System.out.print( "*" ); 20 Lab Exercises Name: Lab Exercise 1 — Triangles 172 Control Statements: Part 2 Chapter5 21 System.out.println(); 22 } // end for loop 23 24 // second triangle 25 for ( row = 0; row <= 4; row++ ) 26 { 27 for ( column = row; column <= 4; column++ ) 28 System.out.print( " " ); 29 30 for ( column = 2 * row; column >= 0; column-- ) 31 System.out.print( "*" ); 32 33 System.out.println(); 34 } // end for loop 35 } // end method drawTriangles 36 } // end class Triangles 1 // Lab 1: TrianglesTest.java 2 // Test application for class Triangles 3 public class TrianglesTest 4 { 5 public static void main( String args[] ) 6 { 7 Triangles application = new Triangles(); 8 application.drawTriangles(); 9 } // end main 10 } // end class TrianglesTest Lab Exercises Name: Lab Exercise 2 — Sales Chapter 5 Control Statements: Part 2 173 Name: Date: Section: Lab Exercise 2 — Sales The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Problem Description 3. Sample Output 4. Program Template (Fig. L 5.3 and Fig. L 5.4) 5. Problem-Solving Tips 6. Follow-Up Questions and Activities The program template represents a complete working Java program with one or more key lines of code replaced with comments. Read the problem description and examine the output, then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up questions. The source code for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel. Lab Objectives This lab was designed to reinforce programming concepts from Chapter 5 of Java How To Program: Seventh Edi- tion. In this lab, you will practice: • Using switch statements. The follow-up questions and activities also will give you practice: • Validating the input from the user. • Extending an existing program. Problem Description Amail-order house sells five products whose retail prices are as follows: Product 1, $2.98; product 2, $4.50; prod- uct 3, $9.98; product 4, $4.49 and product 5, $6.87. Write an application that reads a series of pairs of numbers as follows: a) product number b) quantity sold Your program should use a switch statement to determine the retail price for each product. It should calculate and display the total retail value of all products sold. Use a sentinel-controlled loop to determine when the pro- gram should stop looping and display the final results. Lab Exercises Name: Lab Exercise 2 — Sales 174 Control Statements: Part 2 Chapter5 Sample Output Template Enter product number (1-5) (0 to stop): 1 Enter quantity sold: 5 Enter product number (1-5) (0 to stop): 5 Enter quantity sold: 10 Enter product number (1-5) (0 to stop): 0 Product 1: $14.90 Product 2: $0.00 Product 3: $0.00 Product 4: $0.00 Product 5: $68.70 1 // Lab 2: Sales.java 2 // Program calculates sales, based on an input of product 3 // number and quantity sold 4 import java.util.Scanner; 5 6 public class Sales 7 { 8 // calculates sales for 5 products 9 public void calculateSales() 10 { 11 Scanner input = new Scanner( System.in ); 12 13 double product1 = 0; // amount sold of first product 14 double product2 = 0; // amount sold of second product 15 double product3 = 0; // amount sold of third product 16 double product4 = 0; // amount sold of fourth product 17 double product5 = 0; // amount sold of fifth product 18 19 /* Ask the user to enter product number */ 20 21 /* Create while statement that loops until sentinel is entered */ 22 23 /* Determine whether user’s product number is in 1-5 */ 24 25 /* If so, ask user to input the quantity sold */ 26 27 /* Write a switch statement here that will compute the total 28 for that product */ 29 30 /* If product number is not in 1-5, test if product number is not 0 */ 31 /* Display error message for invalid product number */ 32 33 /* Ask the user to enter another product number */ 34 35 /* end while loop */ 36 37 // print summary 38 System.out.println(); 39 System.out.printf( "Product 1: $%.2f\n", product1 ); Fig. L 5.3 | Sales.java. (Part 1 of 2.) Lab Exercises Name: Lab Exercise 2 — Sales Chapter 5 Control Statements: Part 2 175 Problem-Solving Tips 1. Before your while loop, request the first product number from the user. 2. Use a sentinel value to control the loop. This loop should terminate when the product number entered is zero. 3. If the user provides a valid product number, inside the loop, request a quantity for that product. Then, perform the appropriate calculation in the switch statement. 4. Your switch statement should consist of five cases, each setting the correct dollar value, depending on the quantity that the user entered. 5. Inside the closing right brace (}) of the loop’s body, request the next product number from the user. 6. Be sure to follow the spacing and indentation conventions mentioned in the text. Before and after each control statement, place a line of vertical space to make the code more readable. 7. If you have any questions as you proceed, ask your lab instructor for assistance. Solution 40 /* write code here for the rest of the summary message it should contain 41 the totals for the rest of the products, each on it’s own line */ 42 } // end method calculateSales 43 } // end class Sales 1 // Lab 2: SalesTest.java 2 // Test application for class Sales 3 public class SalesTest 4 { 5 public static void main( String args[] ) 6 { 7 Sales application = new Sales(); 8 application.calculateSales(); 9 } // end main 10 } // end class SalesTest Fig. L 5.4 | SalesTest.java 1 // Lab 2: Sales.java 2 // Program calculates sales, based on an input of product 3 // number and quantity sold 4 import java.util.Scanner; 5 6 public class Sales 7 { 8 // calculates sales for 5 products 9 public void calculateSales() 10 { 11 Scanner input = new Scanner( System.in ); 12 13 double product1 = 0; // amount sold of first product 14 double product2 = 0; // amount sold of second product 15 double product3 = 0; // amount sold of third product Fig. L 5.3 | Sales.java. (Part 2 of 2.) Lab Exercises Name: Lab Exercise 2 — Sales 176 Control Statements: Part 2 Chapter5 16 double product4 = 0; // amount sold of fourth product 17 double product5 = 0; // amount sold of fifth product 18 19 System.out.print( "Enter product number (1-5) (0 to stop): " ); 20 int productId = input.nextInt(); 21 22 // ask user for product number until flag value entered 23 while ( productId != 0 ) 24 { 25 if ( productId >= 1 && productId <= 5 ) 26 { 27 // determine the number sold of the item 28 System.out.print( "Enter quantity sold: " ); 29 int quantity = input.nextInt(); 30 31 // increment the total for the item by the 32 // price times the quantity sold 33 switch ( productId ) 34 { 35 case 1: 36 product1 += quantity * 2.98; 37 break; 38 39 case 2: 40 product2 += quantity * 4.50; 41 break; 42 43 case 3: 44 product3 += quantity * 9.98; 45 break; 46 47 case 4: 48 product4 += quantity * 4.49; 49 break; 50 51 case 5: 52 product5 += quantity * 6.87; 53 break; 54 } // end switch 55 } // end if 56 else if ( productId != 0 ) 57 System.out.println( 58 "Product number must be between 1 and 5 or 0 to stop" ); 59 60 System.out.print( "Enter product number (1-5) (0 to stop): " ); 61 productId = input.nextInt(); 62 } // end while loop 63 64 // print summary 65 System.out.println(); 66 System.out.printf( "Product 1: $%.2f\n", product1 ); 67 System.out.printf( "Product 2: $%.2f\n", product2 ); 68 System.out.printf( "Product 3: $%.2f\n", product3 ); 69 System.out.printf( "Product 4: $%.2f\n", product4 ); 70 System.out.printf( "Product 5: $%.2f\n", product5 ); 71 } // end method calculateSales 72 } // end class Sales Lab Exercises Name: Lab Exercise 2 — Sales Chapter 5 Control Statements: Part 2 177 Follow-Up Questions and Activities 1. What happens when the user inputs a number that is other than 1 through 5 or 0? Why? What is the output when the user enters a number like 7? In the original program, if the user enters a number other than 1-5 or 0, a message appears that informs the user to enter a valid number. This is because of the while loop that runs until a valid number has been entered. 2. Modify the program so that there is a sixth product, priced at $20.00, that represents a package of all the products. For each of the packages purchased, add $4.00 to the totals for all the other products. Do not keep track of the packages separately. 1 // Lab 2: SalesTest.java 2 // Test application for class Sales 3 public class SalesTest 4 { 5 public static void main( String args[] ) 6 { 7 Sales application = new Sales(); 8 application.calculateSales(); 9 } // end main 10 } // end class SalesTest 1 // Lab 2: Sales.java 2 // Program calculates sales, based on an input of product 3 // number and quantity sold 4 import java.util.Scanner; 5 6 public class Sales 7 { 8 // calculates sales for 5 products 9 public void calculateSales() 10 { 11 Scanner input = new Scanner( System.in ); 12 13 double product1 = 0; // amount sold of first product 14 double product2 = 0; // amount sold of second product 15 double product3 = 0; // amount sold of third product 16 double product4 = 0; // amount sold of fourth product 17 double product5 = 0; // amount sold of fifth product 18 19 System.out.print( "Enter product number (1-6) (0 to stop): " ); 20 int productId = input.nextInt(); 21 22 // ask user for product number until flag value entered 23 while ( productId != 0 ) 24 { 25 if ( productId >= 1 && productId <= 6 ) 26 { 27 // determine the number sold of the item 28 System.out.print( "Enter quantity sold: " ); 29 int quantity = input.nextInt(); 30 Lab Exercises Name: Lab Exercise 2 — Sales 178 Control Statements: Part 2 Chapter5 31 // increment the total for the item by the 32 // price times the quantity sold 33 switch ( productId ) 34 { 35 case 1: 36 product1 += quantity * 2.98; 37 break; 38 39 case 2: 40 product2 += quantity * 4.50; 41 break; 42 43 case 3: 44 product3 += quantity * 9.98; 45 break; 46 47 case 4: 48 product4 += quantity * 4.49; 49 break; 50 51 case 5: 52 product5 += quantity * 6.87; 53 break; 54 55 case 6: 56 product1 += quantity * 4; 57 product2 += quantity * 4; 58 product3 += quantity * 4; 59 product4 += quantity * 4; 60 product5 += quantity * 4; 61 break; 62 } // end switch 63 } // end if 64 else if ( productId != 0 ) 65 System.out.println( 66 "Product number must be between 1 and 6 or 0 to stop" ); 67 68 System.out.print( "Enter product number (1-6) (0 to stop): " ); 69 productId = input.nextInt(); 70 } // end while loop 71 72 // print summary 73 System.out.println(); 74 System.out.printf( "Product 1: $%.2f\n", product1 ); 75 System.out.printf( "Product 2: $%.2f\n", product2 ); 76 System.out.printf( "Product 3: $%.2f\n", product3 ); 77 System.out.printf( "Product 4: $%.2f\n", product4 ); 78 System.out.printf( "Product 5: $%.2f\n", product5 ); 79 } // end method calculateSales 80 } // end class Sales Lab Exercises Name: Lab Exercise 2 — Sales Chapter 5 Control Statements: Part 2 179 1 // Lab 2: SalesTest.java 2 // Test application for class Sales 3 public class SalesTest 4 { 5 public static void main( String args[] ) 6 { 7 Sales application = new Sales(); 8 application.calculateSales(); 9 } // end main 10 } // end class SalesTest Enter product number (1-6) (0 to stop): 1 Enter quantity sold: 5 Enter product number (1-6) (0 to stop): 5 Enter quantity sold: 10 Enter product number (1-6) (0 to stop): 6 Enter quantity sold: 2 Enter product number (1-6) (0 to stop): 0 Product 1: $22.90 Product 2: $8.00 Product 3: $8.00 Product 4: $8.00 Product 5: $76.70 Lab Exercises Name: Lab Exercise 3 — Pythagorean Triples Chapter 5 Control Statements: Part 2 181 Name: Date: Section: Lab Exercise 3 — Pythagorean Triples The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Problem Description 3. Sample Output 4. Program Template (Fig. L 5.5) 5. Problem-Solving Tips 6. Follow-Up Questions and Activities The program template represents a complete working Java program with one or more key lines of code replaced with comments. Read the problem description and examine the output, then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up questions. The source code for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel. Lab Objectives This lab was designed to reinforce programming concepts from Chapter 5 of Java How To Program: Seventh Edi- tion. In this lab, you will practice: • Nested for loops. • Using counter-controlled repetition. • Using “brute force” techniques to solve a problem. The follow-up questions and activities will also give you practice: • Using break statements. • Using continue statements. • Using counters to determine the number of iterations a loop performs. Problem Description A right triangle can have sides whose lengths are all integers. The set of three integer values for the lengths of the sides of a right triangle is called a Pythagorean triple. The lengths of the three sides must satisfy the relationship that the sum of the squares of two of the sides is equal to the square of the hypotenuse. Write an application to find all Pythagorean triples for side1, side2 and the hypotenuse, all no larger than 500. Use a triple-nested for loop that tries all possibilities. This method is an example of “brute-force” computing. You will learn in more advanced computer science courses that there are large numbers of interesting problems for which there is no known algorithmic approach other than using sheer brute force. Lab Exercises Name: Lab Exercise 3 — Pythagorean Triples 182 Control Statements: Part 2 Chapter5 Sample Output Template Solution s1: 3, s2: 4, h: 5 s1: 4, s2: 3, h: 5 s1: 5, s2: 12, h: 13 s1: 6, s2: 8, h: 10 s1: 7, s2: 24, h: 25 . . . s1: 480, s2: 31, h: 481 s1: 480, s2: 88, h: 488 s1: 480, s2: 108, h: 492 s1: 480, s2: 140, h: 500 s1: 483, s2: 44, h: 485 1 // Lab 3: Triples.java 2 // Program calculates Pythagorean triples 3 public class Triples 4 { 5 public static void main( String args[] ) 6 { 7 // declare the three sides of a triangle 8 int side1; 9 int side2; 10 int hypotenuse; 11 12 /* Write loop for side1 to try the values 1-500. */ 13 14 /* Write loop for side2 to try the values 1-500. */ 15 16 /* Write loop for hypotenuse to try the values 1-500 */ 17 18 /* Write an if statement that determines whether the sum of the 19 two sides squared equals the hypotenuse squared. If this 20 condition is true display side1, side2 and hypotenuse. */ 21 } // end main 22 } // end class Triples Fig. L 5.5 | Triples.java. 1 // Lab 3: Triples.java 2 // Program calculates Pythagorean triples 3 public class Triples 4 { 5 public static void main( String args[] ) 6 { 7 // declare the three sides of a triangle 8 int side1; Lab Exercises Name: Lab Exercise 3 — Pythagorean Triples Chapter 5 Control Statements: Part 2 183 Problem-Solving Tips 1. This program does not require any input from the user. 2. The formula for the Pythagorean Theorem is hypotenuse 2 = side1 2 + side2 2 . 3. Do not be concerned about trying values that do not make sense, such as a 1-500-1 triangle. Brute-force computing techniques try all possible values. 4. Use an if statement to determine whether the sum of the two squared sides is equal to the hypotenuse squared. If so, output side1, side2 and hypotenuse. 5. If you have any questions as you proceed, ask your lab instructor for assistance. Follow-Up Questions and Activities 1. How many times did this program execute the innermost for loop? Add another counter to the program that counts the number of times the inner loop iterates. Before exiting the program, display the counter val- ue. 9 int side2; 10 int hypotenuse; 11 12 for ( side1 = 1; side1 <= 500; side1++ ) 13 14 for ( side2 = 1; side2 <= 500; side2++ ) 15 16 for ( hypotenuse = 1; hypotenuse <= 500; hypotenuse++ ) 17 18 // use Pythagorean Theorem to print right triangles 19 if ( ( side1 * side1 ) + ( side2 * side2 ) == 20 ( hypotenuse * hypotenuse ) ) 21 System.out.printf( "s1: %d, s2: %d, h: %d\n", 22 side1, side2, hypotenuse ); 23 } // end main 24 } // end class Triples 1 // Lab 3: Triples.java 2 // Program calculates Pythagorean triples 3 public class Triples 4 { 5 public static void main( String args[] ) 6 { 7 // declare the three sides of a triangle 8 int side1; 9 int side2; 10 int hypotenuse; 11 int counter = 0; 12 13 for ( side1 = 1; side1 <= 500; side1++ ) 14 15 for ( side2 = 1; side2 <= 500; side2++ ) 16 17 for ( hypotenuse = 1; hypotenuse <= 500; hypotenuse++ ) 18 { 19 counter++; 20 Lab Exercises Name: Lab Exercise 3 — Pythagorean Triples 184 Control Statements: Part 2 Chapter5 2. Add a break statement to the program inside the innermost for loop. This break statement should execute after the twentieth Pythagorean triple is found. Explain what happens to the program after the 20th triple is found. Do all three for loops exit, or just the innermost one? What happens differently when the break statement is placed inside the second loop? What happens differently when the break statement is placed inside the outermost loop? [Hint: Use the loop counter you defined in the previous follow-up question to count how many times the loops execute.] Break in innermost for loop: 21 // use Pythagorean Theorem to print right triangles 22 if ( ( side1 * side1 ) + ( side2 * side2 ) == 23 ( hypotenuse * hypotenuse ) ) 24 System.out.printf( "s1: %d, s2: %d, h: %d\n", 25 side1, side2, hypotenuse ); 26 } // end for 27 28 System.out.printf( "The inner loop iterated %d times.\n", counter ); 29 } // end main 30 } // end class Triples s1: 3, s2: 4, h: 5 s1: 4, s2: 3, h: 5 s1: 5, s2: 12, h: 13 s1: 6, s2: 8, h: 10 s1: 7, s2: 24, h: 25 . . . s1: 480, s2: 31, h: 481 s1: 480, s2: 88, h: 488 s1: 480, s2: 108, h: 492 s1: 480, s2: 140, h: 500 s1: 483, s2: 44, h: 485 The inner loop iterated 125000000 times. 1 // Lab 3: Triples1.java 2 // Program calculates Pythagorean triples 3 public class Triples1 4 { 5 public static void main( String args[] ) 6 { 7 // declare the three sides of a triangle 8 int side1; 9 int side2; 10 int hypotenuse; 11 int counter = 0; 12 int numberOfTriples = 0; 13 14 for ( side1 = 1; side1 <= 500; side1++ ) 15 16 for ( side2 = 1; side2 <= 500; side2++ ) 17 18 for ( hypotenuse = 1; hypotenuse <= 500; hypotenuse++ ) 19 { Lab Exercises Name: Lab Exercise 3 — Pythagorean Triples Chapter 5 Control Statements: Part 2 185 Break in second for loop: 20 if ( numberOfTriples >= 20 ) 21 break; 22 23 counter++; 24 25 // use Pythagorean Theorem to print right triangles 26 if ( ( side1 * side1 ) + ( side2 * side2 ) == 27 ( hypotenuse * hypotenuse ) ) 28 { 29 System.out.printf( "s1: %d, s2: %d, h: %d\n", 30 side1, side2, hypotenuse ); 31 numberOfTriples++; 32 } // end if 33 } // end for 34 35 System.out.printf( "The inner loop iterated %d times.\n", counter ); 36 } // end main 37 } // end class Triples1 s1: 3, s2: 4, h: 5 s1: 4, s2: 3, h: 5 s1: 5, s2: 12, h: 13 s1: 6, s2: 8, h: 10 s1: 7, s2: 24, h: 25 s1: 8, s2: 6, h: 10 s1: 8, s2: 15, h: 17 s1: 9, s2: 12, h: 15 s1: 9, s2: 40, h: 41 s1: 10, s2: 24, h: 26 s1: 11, s2: 60, h: 61 s1: 12, s2: 5, h: 13 s1: 12, s2: 9, h: 15 s1: 12, s2: 16, h: 20 s1: 12, s2: 35, h: 37 s1: 13, s2: 84, h: 85 s1: 14, s2: 48, h: 50 s1: 15, s2: 8, h: 17 s1: 15, s2: 20, h: 25 s1: 15, s2: 36, h: 39 The inner loop iterated 3517539 times. 1 // Lab 3: Triples2.java 2 // Program calculates Pythagorean triples 3 public class Triples2 4 { 5 public static void main( String args[] ) 6 { 7 // declare the three sides of a triangle 8 int side1; 9 int side2; 10 int hypotenuse; 11 int counter = 0; 12 int numberOfTriples = 0; Lab Exercises Name: Lab Exercise 3 — Pythagorean Triples 186 Control Statements: Part 2 Chapter5 13 14 for ( side1 = 1; side1 <= 500; side1++ ) 15 16 for ( side2 = 1; side2 <= 500; side2++ ) 17 { 18 if ( numberOfTriples >= 20 ) 19 break; 20 21 for ( hypotenuse = 1; hypotenuse <= 500; hypotenuse++ ) 22 { 23 counter++; 24 25 // use Pythagorean Theorem to print right triangles 26 if ( ( side1 * side1 ) + ( side2 * side2 ) == 27 ( hypotenuse * hypotenuse ) ) 28 { 29 System.out.printf( "s1: %d, s2: %d, h: %d\n", 30 side1, side2, hypotenuse ); 31 numberOfTriples++; 32 } // end if 33 } // end inner for 34 } // end middle for 35 36 System.out.printf( "The inner loop iterated %d times.\n", counter ); 37 } // end main 38 } // end class Triples2 s1: 3, s2: 4, h: 5 s1: 4, s2: 3, h: 5 s1: 5, s2: 12, h: 13 s1: 6, s2: 8, h: 10 s1: 7, s2: 24, h: 25 s1: 8, s2: 6, h: 10 s1: 8, s2: 15, h: 17 s1: 9, s2: 12, h: 15 s1: 9, s2: 40, h: 41 s1: 10, s2: 24, h: 26 s1: 11, s2: 60, h: 61 s1: 12, s2: 5, h: 13 s1: 12, s2: 9, h: 15 s1: 12, s2: 16, h: 20 s1: 12, s2: 35, h: 37 s1: 13, s2: 84, h: 85 s1: 14, s2: 48, h: 50 s1: 15, s2: 8, h: 17 s1: 15, s2: 20, h: 25 s1: 15, s2: 36, h: 39 The inner loop iterated 3518000 times. Lab Exercises Name: Lab Exercise 3 — Pythagorean Triples Chapter 5 Control Statements: Part 2 187 Break in outermost for loop: 1 // Lab 3: Triples3.java 2 // Program calculates Pythagorean triples 3 public class Triples3 4 { 5 public static void main( String args[] ) 6 { 7 // declare the three sides of a triangle 8 int side1; 9 int side2; 10 int hypotenuse; 11 int counter = 0; 12 int numberOfTriples = 0; 13 14 for ( side1 = 1; side1 <= 500; side1++ ) 15 { 16 if ( numberOfTriples >= 20 ) 17 break; 18 19 for ( side2 = 1; side2 <= 500; side2++ ) 20 21 for ( hypotenuse = 1; hypotenuse <= 500; hypotenuse++ ) 22 { 23 counter++; 24 25 // use Pythagorean Theorem to print right triangles 26 if ( ( side1 * side1 ) + ( side2 * side2 ) == 27 ( hypotenuse * hypotenuse ) ) 28 { 29 System.out.printf( "s1: %d, s2: %d, h: %d\n", 30 side1, side2, hypotenuse ); 31 numberOfTriples++; 32 } // end if 33 } // end inner for 34 } // end outer for 35 36 System.out.printf( "The inner loop iterated %d times.\n", counter ); 37 } // end main 38 } // end class Triples3 Lab Exercises Name: Lab Exercise 3 — Pythagorean Triples 188 Control Statements: Part 2 Chapter5 The break statement placed inside the innermost loop will exit the innermost loop, but not the outer two loops. Those two loops will continue to run, but no processing of triples will occur. The innermost loop will execute exactly enough times to find 20 triples. When the break statement is placed in the second loop, the innermost loop will finish its 500 iterations even after finding the twentieth triple. After the first time the second loop is reached after the twentieth triple is found, no more processing of triples will occur. When the break statement is placed in the outermost loop, both inner loop will have to complete after the twentieth triple is found. Only after these two loops complete will the break statement be reached. 3. Add a continue statement to the program that prevents a Pythagorean triple from being found when side1 is equal to 8. Using the loop counter again from Follow-Up Question 1, calculate how many times this new program executed the innermost for loop. Explain how the continue statement affected the output. s1: 3, s2: 4, h: 5 s1: 4, s2: 3, h: 5 s1: 5, s2: 12, h: 13 s1: 6, s2: 8, h: 10 s1: 7, s2: 24, h: 25 s1: 8, s2: 6, h: 10 s1: 8, s2: 15, h: 17 s1: 9, s2: 12, h: 15 s1: 9, s2: 40, h: 41 s1: 10, s2: 24, h: 26 s1: 11, s2: 60, h: 61 s1: 12, s2: 5, h: 13 s1: 12, s2: 9, h: 15 s1: 12, s2: 16, h: 20 s1: 12, s2: 35, h: 37 s1: 13, s2: 84, h: 85 s1: 14, s2: 48, h: 50 s1: 15, s2: 8, h: 17 s1: 15, s2: 20, h: 25 s1: 15, s2: 36, h: 39 s1: 15, s2: 112, h: 113 The inner loop iterated 3750000 times. 1 // Lab 3: Triples.java 2 // Program calculates Pythagorean triples 3 public class Triples 4 { 5 public static void main( String args[] ) 6 { 7 // declare the three sides of a triangle 8 int side1; 9 int side2; 10 int hypotenuse; 11 int counter = 0; 12 13 for ( side1 = 1; side1 <= 500; side1++ ) 14 { 15 if ( side1 == 8 ) 16 continue; 17 18 for ( side2 = 1; side2 <= 500; side2++ ) 19 Lab Exercises Name: Lab Exercise 3 — Pythagorean Triples Chapter 5 Control Statements: Part 2 189 The continue statement affects the output by skipping an iteration of the outer for loop. This results in 250,000 (500 * 500) less iterations of the inner loop. 20 for ( hypotenuse = 1; hypotenuse <= 500; hypotenuse++ ) 21 { 22 counter++; 23 24 // use Pythagorean Theorem to print right triangles 25 if ( ( side1 * side1 ) + ( side2 * side2 ) == 26 ( hypotenuse * hypotenuse ) ) 27 System.out.printf( "s1: %d, s2: %d, h: %d\n", 28 side1, side2, hypotenuse ); 29 } // end inner for 30 } // end outer for 31 32 System.out.printf( "The inner loop iterated %d times.\n", counter ); 33 } // end main 34 } // end class Triples s1: 3, s2: 4, h: 5 s1: 4, s2: 3, h: 5 s1: 5, s2: 12, h: 13 s1: 6, s2: 8, h: 10 s1: 7, s2: 24, h: 25 . . . s1: 480, s2: 31, h: 481 s1: 480, s2: 88, h: 488 s1: 480, s2: 108, h: 492 s1: 480, s2: 140, h: 500 s1: 483, s2: 44, h: 485 The inner loop iterated 124750000 times. Chapter 5 Control Statements: Part 2 197 Postlab Activities Name: Date: Section: Coding Exercises These coding exercises reinforce the lessons learned in the lab and provide additional programming experience outside the classroom and laboratory environment. They serve as a review after you have successfully completed the Prelab Activities and Lab Exercises. For each of the following problems, write a program or a program segment that performs the specified action. 1. Write a for loop that prints all the odd integers from 1 to 100, inclusive. 2. Write a do…while loop that prints the integers from 10 to 0, inclusive. 3. Write a for loop that counts from 1 to 5. Use a switch statement to display a letter in the alphabet that corresponds to the number (i.e., 1 is A, 2 is B, etc.). 1 for ( int i = 1; i <= 100; i++ ) 2 3 if ( i % 2 == 1 ) 4 printf( "%d ", i ); 1 int i = 10; 2 3 do 4 { 5 printf( "%d ", i ); 6 i--; 7 } while ( i >= 0 ); 1 for ( int i = 1; i <= 5; i++ ) 2 { 3 switch ( i ) 4 { 5 case 1: 6 printf( "A" ); 7 break; 8 9 case 2: 10 printf( "B" ); 11 break; 12 13 case 3: 14 printf( "C" ); 15 break; 16 Postlab Activities Name: Coding Exercises 198 Control Statements: Part 2 Chapter5 4. Write a while loop that sums the integers from 1 to 10, excluding 3 and 6. Print the sum. 5. Write a for loop that attempts to display the numbers from 1 to 10, but terminates when the control vari- able reaches the value 6. 6. Write a for loop to display the numbers from 1 to 10, but skip the value 6 by using a continue statement. 17 case 4: 18 printf( "D" ); 19 break; 20 21 case 5: 22 printf( "E" ); 23 break; 24 } // end switch 25 } // end for 1 int i = 1; 2 int sum = 0; 3 4 while ( i <= 10 ) 5 { 6 if ( i == 3 || i == 6 ) 7 continue; 8 9 sum += i 10 i++; 11 } // end while 12 13 printf( "sum: %d\n", sum ); 1 for ( int i = 1; i <= 10; i++ ) 2 { 3 if ( i == 6 ) 4 break; 5 6 printf( "%d ", i ); 7 } // end for 1 for ( int i = 1; i <= 10; i++ ) 2 { 3 if ( i == 6 ) 4 continue; 5 6 printf( "%d ", i ); 7 } // end for Postlab Activities Name: Coding Exercises Chapter 5 Control Statements: Part 2 199 7. Modify your solution in Coding Exercise 6 to use a while statement instead of a for statement. 8. Modify your solution in Coding Exercise 7 to use a do…while statement instead of a while statement. 1 int i = 1; 2 3 while ( i <= 10 ) 4 { 5 if ( i == 6 ) 6 continue; 7 8 printf( "%d ", i ); 9 i++; 10 } // end while 1 int i = 1; 2 3 do 4 { 5 if ( i == 6 ) 6 continue; 7 8 printf( "%d ", i ); 9 i++; 10 } while ( i <= 10 ) Postlab Activities Name: Programming Challenges 202 Control Statements: Part 2 Chapter5 2. (“The Twelve Days of Christmas” Song) Write an application that uses repetition and switch statements to print the song “The Twelve Days of Christmas.” One switch statement should be used to print the day (i.e., “First,” “Second,” etc.). A separate switch statement should be used to print the remainder of each verse. Visit the Web site www.12days.com/library/carols/12daysofxmas.htm for the complete lyrics of the song. Hints: • For this example you will need two switch statements. • Both switch statements should appear inside a for loop that will iterate through the twelve days. • You will have one string to which more text is added during every iteration of the loop. The string will be displayed after the loop terminates. • Your output should appear as follows: On the first day of Christmas, my true love gave to me: a Partridge in a pear tree. On the second day of Christmas, my true love gave to me: Two turtle doves, and a Partridge in a pear tree. On the third day of Christmas, my true love gave to me: Three French hens, Two turtle doves, and a Partridge in a pear tree. On the fourth day of Christmas, my true love gave to me: Four calling birds, Three French hens, Two turtle doves, and a Partridge in a pear tree. On the fifth day of Christmas, my true love gave to me: Five golden rings. Four calling birds, Three French hens, Two turtle doves, and a Partridge in a pear tree. On the sixth day of Christmas, my true love gave to me: Six geese-a-laying, Five golden rings. Four calling birds, Three French hens, Two turtle doves, and a Partridge in a pear tree. On the seventh day of Christmas, my true love gave to me: Seven swans-a-swimming, Six geese-a-laying, Five golden rings. Four calling birds, Three French hens, Two turtle doves, and a Partridge in a pear tree. Postlab Activities Name: Programming Challenges Chapter 5 Control Statements: Part 2 203 On the eighth day of Christmas, my true love gave to me: Eight maids-a-milking, Seven swans-a-swimming, Six geese-a-laying, Five golden rings. Four calling birds, Three French hens, Two turtle doves, and a Partridge in a pear tree. On the ninth day of Christmas, my true love gave to me: Nine ladies dancing, Eight maids-a-milking, Seven swans-a-swimming, Six geese-a-laying, Five golden rings. Four calling birds, Three French hens, Two turtle doves, and a Partridge in a pear tree. On the tenth day of Christmas, my true love gave to me: Ten drummers drumming, Nine ladies dancing, Eight maids-a-milking, Seven swans-a-swimming, Six geese-a-laying, Five golden rings. Four calling birds, Three French hens, Two turtle doves, and a Partridge in a pear tree. On the eleventh day of Christmas, my true love gave to me: Eleven pipers piping, Ten drummers drumming, Nine ladies dancing, Eight maids-a-milking, Seven swans-a-swimming, Six geese-a-laying, Five golden rings. Four calling birds, Three French hens, Two turtle doves, and a Partridge in a pear tree. On the twelfth day of Christmas, my true love gave to me: Twelve lords-a-leaping, Eleven pipers piping, Ten drummers drumming, Nine ladies dancing, Eight maids-a-milking, Seven swans-a-swimming, Six geese-a-laying, Five golden rings. Four calling birds, Three French hens, Two turtle doves, and a Partridge in a pear tree. Postlab Activities Name: Programming Challenges 204 Control Statements: Part 2 Chapter5 Solution 1 // Programming Challenge 2: Twelve.java 2 // Program prints the 12 days of Christmas song. 3 public class Twelve 4 { 5 // print the 12 days of Christmas song 6 public void printSong() 7 { 8 for ( int day = 1; day <= 12; day++ ) 9 { 10 System.out.print( "On the " ); 11 12 // add correct day to String 13 switch ( day ) 14 { 15 case 1: 16 System.out.print( "first" ); 17 break; 18 19 case 2: 20 System.out.print( "second" ); 21 break; 22 23 case 3: 24 System.out.print( "third" ); 25 break; 26 27 case 4: 28 System.out.print( "fourth" ); 29 break; 30 31 case 5: 32 System.out.print( "fifth" ); 33 break; 34 35 case 6: 36 System.out.print( "sixth" ); 37 break; 38 39 case 7: 40 System.out.print( "seventh" ); 41 break; 42 43 case 8: 44 System.out.print( "eighth" ); 45 break; 46 47 case 9: 48 System.out.print( "ninth" ); 49 break; 50 51 case 10: 52 System.out.print( "tenth" ); 53 break; 54 Postlab Activities Name: Programming Challenges Chapter 5 Control Statements: Part 2 205 55 case 11: 56 System.out.print( "eleventh" ); 57 break; 58 59 case 12: 60 System.out.print( "twelfth" ); 61 break; 62 } // end switch 63 64 System.out.println( 65 " day of Christmas, my true love gave to me:" ); 66 67 // add remainder of verse to String 68 switch ( day ) 69 { 70 case 12: 71 System.out.println( "Twelve lords-a-leaping," ); 72 73 case 11: 74 System.out.println( "Eleven pipers piping," ); 75 76 case 10: 77 System.out.println( "Ten drummers drumming," ); 78 79 case 9: 80 System.out.println( "Nine ladies dancing," ); 81 82 case 8: 83 System.out.println( "Eight maids-a-milking," ); 84 85 case 7: 86 System.out.println( "Seven swans-a-swimming," ); 87 88 case 6: 89 System.out.println( "Six geese-a-laying," ); 90 91 case 5: 92 System.out.println( "Five golden rings." ); 93 94 case 4: 95 System.out.println( "Four calling birds," ); 96 97 case 3: 98 System.out.println( "Three French hens," ); 99 100 case 2: 101 System.out.println( "Two turtle doves, and" ); 102 103 case 1: 104 System.out.println( "a Partridge in a pear tree." ); 105 } // end switch 106 107 System.out.println(); 108 } // end for 109 } // end method printSong 110 } // end class Twelve Postlab Activities Name: Programming Challenges 206 Control Statements: Part 2 Chapter5 1 // Programming Challenge 2: TwelveTest.java 2 // Test application for class Twelve 3 public class TwelveTest 4 { 5 public static void main( String args[] ) 6 { 7 Twelve application = new Twelve(); 8 application.printSong(); 9 } // end main 10 } // end class TwelveTest