6Methods: A Deeper Look OB J ECT IVES In this chapter you will learn: ■ How static methods and fields are associated with an entire class rather than specific instances of the class. ■ To use common Math methods available in the Java API. ■ To understand the mechanisms for passing information between methods. ■ How the method call/return mechanism is supported by the method call stack and activation records. ■ How packages group related classes. ■ How to use random-number generation to implement game-playing applications. ■ To understand how the visibility of declarations is limited to specific regions of programs. ■ What method overloading is and how to create overloaded methods. The greatest invention of the nineteenth century was the invention of the method of invention. —Alfred North Whitehead Call me Ishmael. —Herman Melville When you call me that, smile! —Owen Wister Answer me in one word. —William Shakespeare O! call back yesterday, bid time return. —William Shakespeare There is a point at which methods devour themselves. —Frantz Fanon Chapter 6 Methods: A Deeper Look 209 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, 22 Short Answer 23, 24, 25, 26, 27 Programming Output 28, 29, 30, 31, 32, 33, 34 Correct the Code 35, 36, 37, 38 Lab Exercises Exercise 1 — Minimum YES NO Follow-Up Question and Activity 1 Exercise 2 — Garage YES NO Follow-Up Question and Activity 1 Exercise 3 — Multiplication Test YES NO Follow-Up Questions and Activities 1, 2 Debugging YES NO Postlab Activities Coding Exercises 1, 2, 3, 4, 5, 6 Programming Challenges 1, 2 Chapter 6 Methods: A Deeper Look 211 Prelab Activities Name: Date: Section: Matching After reading Chapter 6 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 G A I B C H D F K J L 1. final 2. class 3. local variable’s scope 4. Math class 5. return-value-type 6. formal parameter 7. string concatenation 8. promotion rules 9. java.util package 10. arguments in a method call 11. overloaded methods 12. java.lang package a) Starts from the point of declaration of a variable and continues to the end of the block. b) Type of the result returned from a method to its caller. c) Declared in the parentheses of a method declaration. d) Describe the allowed implicit conversions between primitive types. e) Keyword that appears in declarations of constants. f) Contains class Random. g) Scope of a class’s fields and methods. h) Assembling smaller strings into larger strings using operator +. i) Contains methods that perform commonmathematical calcu- lations. j) Methods of the same name must have different sets of param- eters. k) Must match in number, type and order with the parameters in method declaration. l) Imported by the compiler into all programs. Prelab Activities Name: Fill in the Blank Chapter 6 Methods: A Deeper Look 213 Name: Date: Section: Fill in the Blank Fill in the blanks for each of the following statements: 13. The element of chance can be introduced in a program via an object of class Random . 14. A number added to a randomly generated number to change the starting value in a range of values is known as the shifting value . 15. A(n) static method is called by preceding the method name with its class name and a dot. 16. If a method does not return a value, the return value type must be void . 17. The arguments passed to a method should match in number , type and order with the parameters in method declaration. 18. Method nextInt of class Random generates a random int value in the range –2,147,483,648 to 2,147,483,647. 19. Using existing methods as building blocks to create new programs is called software reuse . 20. If more method calls occur than can have their activation records stored on the program execution stack, an error known as a(n) stack overflow occurs. 21. When a program calls a method, the called method must know how to return to its caller, so the return ad- dress of the calling method is pushed onto the program execution stack . 22. Local variables are created when program control reaches their declaration; they exist while the block in which they are declared is active and they are destroyed when the block in which they are declared exits. Prelab Activities Name: Short Answer Chapter 6 Methods: A Deeper Look 215 Name: Date: Section: Short Answer In the space provided, answer each of the given questions. Your answers should be concise; aim for two or three sentences. 23. Define the term “method.” A method is a program component that performs a specific task. A program may invoke a particular method many times to perform the method’s task. The actual statements defining a method are written only once and are hidden from other methods. 24. What are the three ways to call a method? A method in a class can invoke another method in the same class simply by its method name. A method can invoke an object’s method via the reference to the object followed by a dot (.) and the method name. A method can invoke a static method by following the static method’s class name with a dot and the static method name. 25. What are the similarities between using an enum class and using a set of final variables? Both can be used to clarify code by providing names for constant values. They also both allow the programmer to specify a value once and use its name throughout the code. 26. What are overloaded methods? Are methods with the same name that only differ in return type valid over- loaded methods? Overloaded methods are methods with the same name but different parameter lists. Methods that differ only in return type result in a compilation error. 27. Why do identifiers have scope? An identifier’s scope defines where the identifier can be referenced in a program. Some identifiers can be refer- enced throughout a program, and others can be referenced only from limited portions of a program. Prelab Activities Name: Programming Output Chapter 6 Methods: A Deeper Look 217 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.] 28. What is the output of the following code segment? Your answer: 29. What is output by the following code segment? Your answer: 1 int a = 5; 2 int b = -6; 3 System.out.println( Math.max( ( Math.abs( b ) ), a ) ); 6 1 int a = -6; 2 3 System.out.println( Math.sqrt( Math.pow( Math.abs( a ), 2 ) ) ); 4 5 int a = 6; 6 7 System.out.println( Math.sqrt( Math.pow( Math.abs( a ), 2 ) ) ); 6.0 6.0 Prelab Activities Name: Programming Output 218 Methods: A Deeper Look Chapter6 Use the following method declaration to answer Questions 30 and 31: 30. What is output by the following code segment? Your answer: 31. What is output by the following code segment? 1 public int method1( int x ) 2 { 3 if ( x <= 10 ) 4 x += 10; 5 else 6 x -= 10; 7 8 return x; 9 } 1 int a = 6; 2 3 System.out.println( method1( a ) ); 4 5 a = 15; 6 7 System.out.println( method1( a ) ); 8 9 a = 10; 10 11 System.out.println( method1( a ) ); 12 13 a = -10; 14 15 System.out.println( method1( a ) ); 16 5 20 0 1 int a = 15; 2 int b = 5; 3 4 System.out.println( method1( method1( a ) ) + method1( b ) ); 5 6 a = 0; 7 b = 0; 8 9 System.out.println( method1( method1( a ) ) + method1( b ) ); 10 11 a = 5; Prelab Activities Name: Programming Output Chapter 6 Methods: A Deeper Look 219 Your answer: Given the following class declaration, answer Questions 32, 33 and 34. 12 b = 15; 13 14 System.out.println( method1( method1( a ) ) + method1( b ) ); 15 16 a = -10; 17 b = 10; 18 19 System.out.println( method1( method1( a ) ) + method1( b ) ); 30 30 10 30 1 import java.util.Scanner; 2 3 public class Greeting 4 { 5 int inputNumber; // number input by user 6 String greetingString; // greeting to display to user 7 8 public void greeting() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 // obtain user input 13 System.out.println( 14 "Enter 1 for an English greeting\nEnter 2 for a Spanish greeting" ); 15 16 inputNumber = input.nextInt(); // input integer from user 17 18 greet( inputNumber ); 19 20 // call method greet to determine appropriate greeting 21 System.out.println( greetingString ); 22 } // end method greeting 23 24 // the greet method 25 public void greet ( int x ) 26 { 27 if ( x == 1 ) 28 greetingString = "Hello."; // English greeting 29 else if ( x == 2 ) 30 greetingString = "Hola."; // spanish greeting 31 else 32 greetingString = "Invalid input"; 33 } // end method greet 34 } // end class Greeting Prelab Activities Name: Programming Output 220 Methods: A Deeper Look Chapter6 32. What is displayed when the user enters 1? Your answer: 33. What is displayed when the user enters 2? Your answer: 34. What is displayed when the user enters 3? Your answer: 1 public class GreetingTest 2 { 3 public static void main( String args[] ) 4 { 5 Greeting application = new Greeting(); 6 application.greeting(); 7 } // end main 8 } // end class GreetingTest Hello. Hola. Invalid input Chapter 6 Methods: A Deeper Look 225 Lab Exercises Name: Date: Section: Lab Exercise 1 — Minimum This 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. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 6.1 and Fig. L 6.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 sample 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 6 of Java How to Program: Seventh Edi- tion. In this lab, you will practice: • Declaring and using methods. • Using Math class methods. The follow-up question and activity also will give you practice: • Modifying methods to perform different actions. Description of the Problem Write a method minimum3 that returns the smallest of three floating-point numbers. Use the Math.min method to implement minimum3. Incorporate the method into an application that reads three values from the user, de- termines the smallest value and displays the result. Sample Output Type the end-of-file indicator to terminate On UNIX/Linux/Mac OS X typed then press Enter On Windows type z then press Enter Or enter first number: 4 Enter second number: 5 Enter third number: 6 Minimum is 4.000000 Type the end-of-file indicator to terminate On UNIX/Linux/Mac OS X type d then press Enter On Windows type z then press Enter Or enter first number: ^Z Lab Exercises Name: Lab Exercise 1 — Minimum 226 Methods: A Deeper Look Chapter6 Program Template 1 // Lab 1: Min.java 2 // Program finds the minimum of 3 numbers 3 import java.util.Scanner; 4 5 public class Min 6 { 7 // find the minimum of three numbers 8 public void findMinimum() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 double one; // first number 13 double two; // second number 14 double three; // third number 15 16 System.out.printf( "%s\n %s\n %s\n", 17 "Type the end-of-file indicator to terminate", 18 "On UNIX/Linux/Mac OS X type d then press Enter", 19 "On Windows type z then press Enter" ); 20 System.out.print( "Or enter first number: " ); 21 22 while ( input.hasNext() ) 23 { 24 one = input.nextDouble(); 25 26 /* Write code to get the remainder of the inputs and 27 convert them to double values */ 28 29 /* Write code to display the minimum of the three floating-point numbers */ 30 31 System.out.printf( "\n%s\n %s\n %s\n", 32 "Type the end-of-file indicator to terminate", 33 "On UNIX/Linux/Mac OS X type d then press Enter", 34 "On Windows type z then press Enter" ); 35 System.out.print( "Or enter first number: " ); 36 } // end while 37 } // end method findMinimum 38 39 // determine the smallest of three numbers 40 /* write the header for the minimum3 method */ 41 { 42 // determine the minimum value 43 return /* Write code to compute the minimum of the three numbers 44 using nested calls to Math.min */ 45 } // end method minimum3 46 } // end class Min Fig. L 6.1 | Min.java. Lab Exercises Name: Lab Exercise 1 — Minimum Chapter 6 Methods: A Deeper Look 227 Problem-Solving Tips 1. Method minimum3 should receive three arguments of type double. 2. Method minumum3 should return a double. 3. In order to nest method calls to Math.min, place a method call to Math.min within the argument list of another call to Math.min. The return value of one Math.min method call will be used as an argument passed to the other call to method Math.min. 4. Be sure to follow the spacing and indentation conventions mentioned in the text. 5. If you have any questions as you proceed, ask your lab instructor for assistance. 1 // Lab 1: MinTest.java 2 // Test application for class Min 3 public class MinTest 4 { 5 public static void main( String args[] ) 6 { 7 Min application = new Min(); 8 application.findMinimum(); 9 } // end main 10 } // end class MinTest Fig. L 6.2 | MinTest.java Lab Exercises Name: Lab Exercise 1 — Minimum 228 Methods: A Deeper Look Chapter6 Solution 1 // Lab 1: Min.java 2 // Program finds the minimum of 3 numbers 3 import java.util.Scanner; 4 5 public class Min 6 { 7 // find the minimum of three numbers 8 public void findMinimum() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 double one; // first number 13 double two; // second number 14 double three; // third number 15 16 System.out.printf( "%s\n %s\n %s\n", 17 "Type the end-of-file indicator to terminate", 18 "On UNIX/Linux/Mac OS X type d then press Enter", 19 "On Windows type z then press Enter" ); 20 System.out.print( "Or enter first number: " ); 21 22 while ( input.hasNext() ) 23 { 24 one = input.nextDouble(); 25 System.out.print( "Enter second number: " ); 26 two = input.nextDouble(); 27 System.out.print( "Enter third number: " ); 28 three = input.nextDouble(); 29 30 System.out.printf( " Minimum is %f\n", 31 minimum3( one, two, three ) ); 32 33 System.out.printf( "\n%s\n %s\n %s\n", 34 "Type the end-of-file indicator to terminate", 35 "On UNIX/Linux/Mac OS X type d then press Enter", 36 "On Windows type z then press Enter" ); 37 System.out.print( "Or enter first number: " ); 38 } // end while 39 } // end method findMinimum 40 41 // determine the smallest of three numbers 42 public double minimum3( double one, double two, double three ) 43 { 44 // use a nested pair of min statements 45 return Math.min( Math.min( one, two ), three ); 46 } // end method minimum3 47 } // end class Min Lab Exercises Name: Lab Exercise 1 — Minimum Chapter 6 Methods: A Deeper Look 229 Follow-Up Question and Activity 1. Modify the program in Lab Exercise 1 to compute the minimum of four double values. 1 // Lab 1: MinTest.java 2 // Test application for class Min 3 public class MinTest 4 { 5 public static void main( String args[] ) 6 { 7 Min application = new Min(); 8 application.findMinimum(); 9 } // end main 10 } // end class MinTest Lab Exercises Name: Lab Exercise 1 — Minimum 230 Methods: A Deeper Look Chapter6 Solution 1 // Lab 1: Min.java 2 // Program finds the minimum of 4 numbers 3 import java.util.Scanner; 4 5 public class Min 6 { 7 // find the minimum of three numbers 8 public void findMinimum() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 double one; // first number 13 double two; // second number 14 double three; // third number 15 double four; // fourth number 16 17 System.out.printf( "%s\n %s\n %s\n", 18 "Type the end-of-file indicator to terminate", 19 "On UNIX/Linux/Mac OS X type d then press Enter", 20 "On Windows type z then press Enter" ); 21 System.out.print( "Or enter first number: " ); 22 23 while ( input.hasNext() ) 24 { 25 one = input.nextDouble(); 26 System.out.print( "Enter second number: " ); 27 two = input.nextDouble(); 28 System.out.print( "Enter third number: " ); 29 three = input.nextDouble(); 30 System.out.print( "Enter fourth number: " ); 31 four = input.nextDouble(); 32 33 System.out.printf( " Minimum is %f\n", 34 minimum4( one, two, three, four ) ); 35 36 System.out.printf( "\n%s\n %s\n %s\n", 37 "Type the end-of-file indicator to terminate", 38 "On UNIX/Linux/Mac OS X type d then press Enter", 39 "On Windows type z then press Enter" ); 40 System.out.print( "Or enter first number: " ); 41 } // end while 42 } // end method findMinimum 43 44 // determine the smallest of four numbers 45 public double minimum4( double one, double two, double three, double four ) 46 { 47 // use a nested pair of min statements 48 return Math.min( Math.min( one, two ), Math.min( three, four ) ); 49 } // end method minimum4 50 } // end class Min Lab Exercises Name: Lab Exercise 1 — Minimum Chapter 6 Methods: A Deeper Look 231 1 // Lab 1: MinTest.java 2 // Test application for class Min 3 public class MinTest 4 { 5 public static void main( String args[] ) 6 { 7 Min application = new Min(); 8 application.findMinimum(); 9 } // end main 10 } // end class MinTest Lab Exercises Name: Lab Exercise 2 — Garage Chapter 6 Methods: A Deeper Look 233 Name: Date: Section: Lab Exercise 2 — Garage This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into five parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 6.3 and Fig. L 6.4) 5. Problem-Solving Tips 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 sample 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. 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 6 of Java How to Program: Seventh Edi- tion. In this lab, you will practice: • Creating and using methods. • Using Math class methods. Description of the Problem A parking garage charges a $2.00 minimum fee to park for up to three hours. The garage charges an additional $0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $10.00. Assume that no car parks for longer than 24 hours at a time.Write an application that calculates and displays the parking charges for each customer who parked in the garage yesterday. You should enter the hours parked for each customer. The program should display the charge for the current customer and should calculate and display the running total of yesterday’s receipts. The program should use the method calculate- Charges to determine the charge for each customer. Sample Output Enter number of hours (a negative to quit): 2 Current charge: $2.00, Total receipts: $2.00 Enter number of hours (a negative to quit): 10 Current charge: $5.50, Total receipts: $7.50 Enter number of hours (a negative to quit): -1 Lab Exercises Name: Lab Exercise 2 — Garage 234 Methods: A Deeper Look Chapter6 Program Template 1 // Lab 2: Garage.java 2 // Program calculates charges for parking 3 import java.util.Scanner; 4 5 public class Garage 6 { 7 // begin calculating charges 8 public void startCharging() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 double totalReceipts = 0.0; // total fee collected for the day 13 double fee; // the charge for the current customer 14 double hours; // hours for the current customer 15 16 // read in the first customer's hours 17 System.out.print( 18 "Enter number of hours (a negative to quit): " ); 19 hours = input.nextDouble(); 20 21 while ( hours >= 0.0 ) 22 { 23 /* Write code here to calculate the fee and assign it to the variable fee */ 24 25 /* Write code here to calculate the total receipts */ 26 27 System.out.printf( 28 "Current charge: $%.2f, Total receipts: $%.2f\n", 29 fee, totalReceipts ); 30 31 // read in the next customer's hours 32 System.out.print( 33 "Enter number of hours (a negative to quit): " ); 34 hours = input.nextDouble(); 35 } // end while loop 36 } // end method startCharging 37 38 // determines fee based on time 39 /* Write the header for the calculateCharges method */ 40 { 41 // apply minimum charge 42 /* Write a line of code that declares and initializes a variable 43 with the minimum charge of $2 */ 44 45 // add extra fees as applicable 46 /* Write an if statement that determines whether hours is greater 47 than 3.0 and, if so, calculates the additional charge. */ 48 49 // apply maximum value if needed 50 /* Write code here that determines whether the 10 hour maximum has been reached 51 and if so sets the maximum charge */ 52 53 /* Write a line of code that returns the calculated charge */ 54 } // end method calculateCharges 55 } // end class Garage Fig. L 6.3 | Garage.java. Lab Exercises Name: Lab Exercise 2 — Garage Chapter 6 Methods: A Deeper Look 235 Problem-Solving Tips 1. The calculateCharges method should take one argument and return a double. 2. To calculate the fee in line 24, call method calculateCharges and pass it the number of hours input by the user. Assign the returned value to variable fee. 3. Be sure to follow the spacing and indentation conventions mentioned in the text. 4. If you have any questions as you proceed, ask your lab instructor for assistance. 1 // Lab 2: GarageTest.java 2 // Test application for class Garage 3 public class GarageTest 4 { 5 public static void main( String args[] ) 6 { 7 Garage application = new Garage(); 8 application.startCharging(); 9 } // end main 10 } // end class GarageTest Fig. L 6.4 | GarageTest.java. Lab Exercises Name: Lab Exercise 2 — Garage 236 Methods: A Deeper Look Chapter6 Solution 1 // Lab 2: Garage.java 2 // Program calculates charges for parking 3 import java.util.Scanner; 4 5 public class Garage 6 { 7 // begin calculating charges 8 public void startCharging() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 double totalReceipts = 0.0; // total fee collected for the day 13 double fee; // the charge for the current customer 14 double hours; // hours for the current customer 15 16 // read in the first customer's hours 17 System.out.print( 18 "Enter number of hours (a negative to quit): " ); 19 hours = input.nextDouble(); 20 21 while ( hours >= 0.0 ) 22 { 23 // calculate and print the charges 24 fee = calculateCharges( hours ); 25 totalReceipts += fee; 26 System.out.printf( 27 "Current charge: $%.2f, Total receipts: $%.2f\n", 28 fee, totalReceipts ); 29 30 // read in the next customer's hours 31 System.out.print( 32 "Enter number of hours (a negative to quit): " ); 33 hours = input.nextDouble(); 34 } // end while loop 35 } // end method startCharging 36 37 // determines fee based on time 38 public double calculateCharges( double hours ) 39 { 40 // apply minimum charge 41 double charge = 2.0; 42 43 // add extra fees as applicable 44 if ( hours > 3.0 ) 45 charge = 2.0 + 0.5 * Math.ceil( hours - 3.0 ); 46 47 // apply maximum value if needed 48 if ( charge > 10.0 ) 49 charge = 10.0; 50 51 return charge; 52 } // end method calculateCharges 53 } // end class Garage Lab Exercises Name: Lab Exercise 2 — Garage Chapter 6 Methods: A Deeper Look 237 1 // Lab 2: GarageTest.java 2 // Test application for class Garage 3 public class GarageTest 4 { 5 public static void main( String args[] ) 6 { 7 Garage application = new Garage(); 8 application.startCharging(); 9 } // end main 10 } // end class GarageTest Chapter 6 Methods: A Deeper Look 253 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 method that takes an integer as an argument and returns the remainder of that value divided by 7. Incorporate that method into an application that enables the user to enter values to test the method. 1 // Coding Exercise: Question 1: 2 import java.util.Scanner; 3 4 public class CodingEX1 5 { 6 public void remainder() 7 { 8 Scanner input = new Scanner( System.in ); 9 10 System.out.println( "Enter first floating-point value" ); 11 int number1 = input.nextInt(); 12 int result = modulus( number1 ); 13 14 System.out.printf( "result: %d\n", result ); 15 } // end method remainder 16 17 public int modulus( int x ) 18 { 19 int k = ( x % 7 ); 20 return k ; 21 } // end method modulus 22 } // end class CodingEX1 1 // Coding Exercise: Question 1: 2 public class CodingEx1Test 3 { 4 public static void main( String args[] ) 5 { 6 CodingEX1 application = new CodingEX1(); 7 application.remainder(); 8 } // end main 9 } // end class CodingEx1Test Postlab Activities Name: Coding Exercises 254 Methods: A Deeper Look Chapter6 2. Write a Java application that uses random numbers to simulate 10 flips of a coin. 1 // Coding Exercise: Question 2: 2 public class CodingEX2 3 { 4 public void flip() 5 { 6 int tail = 0, head = 0, face; 7 8 for ( int roll = 1; roll <= 10; roll++ ) { 9 face = 1 + ( int ) ( Math.random() * 2 ); 10 11 switch ( face ) 12 { 13 case 1: 14 ++head; 15 break; 16 17 case 2: 18 ++tail; 19 break; 20 } // end switch 21 } // end for 22 23 System.out.printf( "Tails\tHeads\n%d\t%d\n", tail, head ); 24 } // end method flip 25 } // end class CodingEX2 1 // Coding Exercise: Question 2: 2 public class CodingEx2Test 3 { 4 public static void main( String args[] ) 5 { 6 CodingEx2 application = new CodingEx2(); 7 application.flip(); 8 } // end main 9 } // end class CodingEx2Test Postlab Activities Name: Coding Exercises Chapter 6 Methods: A Deeper Look 255 3. Write a method multiple that takes two integers as its arguments and returns true if the first integer is di- visible evenly by the second one (i.e., there is no remainder after division); otherwise, the method should return false. Incorporate this method into an application that enables the user to enter values to test the method. 1 // Coding Exercise: Question 3: 2 import java.util.Scanner; 3 4 public class CodingEX3 5 { 6 public void testDivisibility() 7 { 8 Scanner input = new Scanner( System.in ); 9 10 int firstNum, secondNum; 11 boolean divides; 12 System.out.println("Please Enter an integer: "); 13 firstNum = input.nextInt(); 14 15 System.out.println("Please Enter another integer: "); 16 secondNum = input.nextInt(); 17 18 divides = multiple(firstNum, secondNum); 19 System.out.printf( "Is %d divisible by %d? %b\n", firstNum, secondNum, divides ); 20 } 21 22 public boolean multiple( int number, int factor ) 23 { 24 if ( ( number % factor ) == 0 ) 25 return true; 26 else 27 return false; 28 } // end method calculateTotal 29 } // end class CodingEX3 1 // Coding Exercise: Question 3: 2 public class CodingEx3Test 3 { 4 public static void main( String args[] ) 5 { 6 CodingEx3 application = new CodingEx3(); 7 application.testDivisibility(); 8 } // end main 9 } // end class CodingEx3Test Postlab Activities Name: Coding Exercises 256 Methods: A Deeper Look Chapter6 4. Write a method halve that takes one floating-point value of type double as its argument and returns the value of that number divided by 2. Incorporate this method into an application that enables the user to enter values to test the method. 1 // Coding Exercise: Question 4: 2 import java.util.Scanner; 3 4 public class CodingEX4 5 { 6 public void halveNumber() 7 { 8 Scanner input = new Scanner( System.in ); 9 10 System.out.println( "Please Enter an integer: " ); 11 int number = input.nextInt(); 12 int half = halve( number ); 13 14 System.out.printf( "Half of the number %d is %d\n", number, half ); 15 } 16 17 public int halve( int x ) 18 { 19 return x / 2; 20 } // end method halve 21 } // end class CodingEX4 1 // Coding Exercise: Question 4: 2 public class CodingEx4Test 3 { 4 public static void main( String args[] ) 5 { 6 CodingEx4 application = new CodingEx4(); 7 application.halveNumber(); 8 } // end main 9 } // end class CodingEx4Test Postlab Activities Name: Coding Exercises Chapter 6 Methods: A Deeper Look 257 5. Write a method diffDouble that takes two floating-point values of type double as arguments and computes and returns the difference between the first and second number. Incorporate this method into an application that enables the user to enter values to test the method. 1 // Chapter 6: Coding Exercise: Number 5: 2 import java.util.Scanner; 3 4 public class CodingEx5 5 { 6 public void difference() 7 { 8 Scanner input = new Scanner( System.in ); 9 10 double firstNumber, secondNumber; 11 12 System.out.println( "Please enter your first floating-point number" ); 13 firstNumber = input.nextDouble(); 14 15 System.out.println( "Please enter your second floating-point number" ); 16 secondNumber = input.nextDouble(); 17 18 System.out.printf( "The difference between %.2f and %.2f is %.2f\n", firstNumber, 19 secondNumber, diffDouble( firstNumber, secondNumber ) ); 20 } 21 22 public double diffDouble( double number1, double number2 ) 23 { 24 return number1 - number2; 25 } // end method difference 26 } // end class CodingEx5 1 // Coding Exercise: Question 5: 2 public class CodingEx5Test 3 { 4 public static void main( String args[] ) 5 { 6 CodingEx5 application = new CodingEx5(); 7 application.difference(); 8 } // end main 9 } // end class CodingEx5Test Postlab Activities Name: Coding Exercises 258 Methods: A Deeper Look Chapter6 6. Write a method area that computes and returns the area of a square. Incorporate this method into an ap- plication that allows the user to enter the length of one side of the square. 1 // Chapter 6: Coding Exercise: Number 6: 2 import java.util.Scanner; 3 4 public class CodingEx6 5 { 6 public void square() 7 { 8 Scanner input = new Scanner( System.in ); 9 10 double squareSide; 11 12 System.out.println( "Please enter the side of the square: " ); 13 squareSide = input.nextDouble(); 14 15 System.out.printf( "The area of the square is %.2f\n", area( squareSide ) ); 16 } // end method square 17 18 public double area( int side ) 19 { 20 return side * side; 21 } // end method areaSquare 22 } // end class CodingEx6 1 // Coding Exercise: Question 6: 2 public class CodingEx6Test 3 { 4 public static void main( String args[] ) 5 { 6 CodingEx6 application = new CodingEx6(); 7 application.difference(); 8 } // end main 9 } // end class CodingEx6Test Postlab Activities Name: Programming Challenges Chapter 6 Methods: A Deeper Look 259 Name: Date: Section: Programming Challenges The Programming Challenges are more involved than the Coding Exercises and may require a significant amount of time to complete. Write a Java program for each of the problems in this section. The answers to these problems are available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel. Pseudocode, hints or sample outputs are provided for each problem to aid you in your programming. 1. Write method distance to calculate the distance between two points (x1, y1) and (x2, y2). All numbers and return values should be of type double. Incorporate this method into an application that enables the user to enter the coordinates of the points. Hints: • The distance between two points can be calculated by taking the square root of ( x2 - x1 ) 2 + ( y2 - y1 ) 2 • Use Math class methods to compute the distance. • Your output should appear as follows: Solution Type the end-of-file indicator to terminate On UNIX/Linux/Mac OS X type d then press Enter On Windows type z then press Enter Or Enter X1: 1 Enter Y1: 1 Enter X2: 4 Enter Y2: 5 Distance is 5.000000 Type the end-of-file indicator to terminate On UNIX/Linux/Mac OS X type d then press Enter On Windows type z then press Enter Or Enter X1: ^Z 1 // Programming Challenge 1: Points.java 2 // Program calculates the distance between two points. 3 import java.util.Scanner; 4 5 public class Points 6 { 7 // calculates the distance between two points 8 public void calculateDistance() 9 { 10 Scanner input = new Scanner( System.in ); 11 Postlab Activities Name: Programming Challenges 260 Methods: A Deeper Look Chapter6 12 System.out.printf( "%s\n %s\n %s\n", 13 "Type the end-of-file indicator to terminate", 14 "On UNIX/Linux/Mac OS X type d then press Enter", 15 "On Windows type z then press Enter" ); 16 System.out.print( "Or Enter X1: " ); 17 18 // continually read in inputs until the user terminates 19 while ( input.hasNext() ) 20 { 21 double x1 = input.nextDouble(); 22 System.out.print( "Enter Y1: " ); 23 double y1 = input.nextDouble(); 24 System.out.print( "Enter X2: " ); 25 double x2 = input.nextDouble(); 26 System.out.print( "Enter Y2: " ); 27 double y2 = input.nextDouble(); 28 29 double distance = distance( x1, y1, x2, y2 ); 30 System.out.printf( "Distance is %f\n\n", distance ); 31 32 System.out.printf( "%s\n %s\n %s\n", 33 "Type the end-of-file indicator to terminate", 34 "On UNIX/Linux/Mac OS X type d then press Enter", 35 "On Windows type z then press Enter" ); 36 System.out.print( "Or Enter X1: " ); 37 } // end while 38 } // end method calculateDistance 39 40 // calculate distance between two points 41 public double distance( double x1, double y1, double x2, double y2 ) 42 { 43 return Math.sqrt( Math.pow( ( x1 - x2 ), 2 ) + 44 Math.pow( ( y1 - y2 ), 2 ) ); 45 } // end method distance 46 } // end class Points 1 // Programming Challenge 1: PointsTest.java 2 // Test application for class Points 3 public class PointsTest 4 { 5 public static void main( String args[] ) 6 { 7 Points application = new Points(); 8 application.calculateDistance(); 9 } // end main 10 } // end class PointsTest