methods: a deeper look - university of...

29
6 Methods: A Deeper Look OBJECTIVES 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

Upload: duongkhanh

Post on 12-Mar-2018

228 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

6Methods:A Deeper Look

O B J E C T I V E SIn this chapter you will learn:

■ How static methods and fields are associated with anentire class rather than specific instances of the class.

■ To use common Math methods available in the Java API.

■ To understand the mechanisms for passing informationbetween methods.

■ How the method call/return mechanism is supported bythe method call stack and activation records.

■ How packages group related classes.

■ How to use random-number generation to implementgame-playing applications.

■ To understand how the visibility of declarations is limitedto specific regions of programs.

■ What method overloading is and how to createoverloaded methods.

The greatest invention of thenineteenth century was theinvention of the method ofinvention.—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, bidtime return.—William Shakespeare

There is a point at whichmethods devour themselves.—Frantz Fanon

Page 2: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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

Page 3: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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

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

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

l) Imported by the compiler into all programs.

Page 4: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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 knownas 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 inmethod declaration.

18. Method nextInt of class Random generates a random int value in the range –2,147,483,648 to2,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, anerror 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 inwhich they are declared is active and they are destroyed when the block in which they are declared exits.

Page 5: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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

23. Define the term “method.”

A method is a program component that performs a specific task. A program may invoke a particular methodmany times to perform the method’s task. The actual statements defining a method are written only once andare 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 caninvoke an object’s method via the reference to the object followed by a dot (.) and the method name. A methodcan invoke a static method by following the static method’s class name with a dot and the static methodname.

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

Page 6: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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 eachprogram. [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;23 System.out.println( Math.sqrt( Math.pow( Math.abs( a ), 2 ) ) );45 int a = 6;67 System.out.println( Math.sqrt( Math.pow( Math.abs( a ), 2 ) ) );

6.06.0

Page 7: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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 else6 x -= 10;78 return x;9 }

1 int a = 6;23 System.out.println( method1( a ) );45 a = 15;67 System.out.println( method1( a ) );89 a = 10;

1011 System.out.println( method1( a ) );1213 a = -10;1415 System.out.println( method1( a ) );

165200

1 int a = 15;2 int b = 5;34 System.out.println( method1( method1( a ) ) + method1( b ) );56 a = 0;7 b = 0;89 System.out.println( method1( method1( a ) ) + method1( b ) );

1011 a = 5;

Page 8: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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;1314 System.out.println( method1( method1( a ) ) + method1( b ) );1516 a = -10;17 b = 10;1819 System.out.println( method1( method1( a ) ) + method1( b ) );

30301030

1 import java.util.Scanner;23 public class Greeting4 {5 int inputNumber; // number input by user6 String greetingString; // greeting to display to user78 public void greeting()9 {

10 Scanner input = new Scanner( System.in );1112 // obtain user input13 System.out.println(14 "Enter 1 for an English greeting\nEnter 2 for a Spanish greeting" );1516 inputNumber = input.nextInt(); // input integer from user1718 greet( inputNumber );1920 // call method greet to determine appropriate greeting21 System.out.println( greetingString );22 } // end method greeting2324 // the greet method25 public void greet ( int x )26 {27 if ( x == 1 )28 greetingString = "Hello."; // English greeting29 else if ( x == 2 )30 greetingString = "Hola."; // spanish greeting31 else32 greetingString = "Invalid input";33 } // end method greet34 } // end class Greeting

Page 9: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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 GreetingTest2 {3 public static void main( String args[] )4 {5 Greeting application = new Greeting();6 application.greeting();7 } // end main8 } // end class GreetingTest

Hello.

Hola.

Invalid input

Page 10: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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. Theproblem 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 replacedwith 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 theprogram. Compare your output with the sample output provided. Then answer the follow-up question. Thesource code for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel.

Lab ObjectivesThis 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 ProblemWrite a method minimum3 that returns the smallest of three floating-point numbers. Use the Math.min methodto 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 terminateOn UNIX/Linux/Mac OS X type <ctrl> d then press EnterOn Windows type <ctrl> z then press Enter

Or enter first number: 4Enter second number: 5Enter third number: 6Minimum is 4.000000

Type the end-of-file indicator to terminateOn UNIX/Linux/Mac OS X type <ctrl> d then press EnterOn Windows type <ctrl> z then press Enter

Or enter first number: ^Z

Page 11: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

Lab Exercises Name:

Lab Exercise 1 — Minimum

226 Methods: A Deeper Look Chapter6

Program Template

1 // Lab 1: Min.java2 // Program finds the minimum of 3 numbers3 import java.util.Scanner;45 public class Min6 {7 // find the minimum of three numbers8 public void findMinimum()9 {

10 Scanner input = new Scanner( System.in );1112 double one; // first number13 double two; // second number14 double three; // third number1516 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 <ctrl> d then press Enter",19 "On Windows type <ctrl> z then press Enter" );20 System.out.print( "Or enter first number: " );2122 while ( input.hasNext() )23 {24 one = input.nextDouble();2526 /* Write code to get the remainder of the inputs and27 convert them to double values */2829 /* Write code to display the minimum of the three floating-point numbers */3031 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 <ctrl> d then press Enter",34 "On Windows type <ctrl> z then press Enter" );35 System.out.print( "Or enter first number: " );36 } // end while37 } // end method findMinimum3839 // determine the smallest of three numbers40 /* write the header for the minimum3 method */41 {42 // determine the minimum value43 return /* Write code to compute the minimum of the three numbers44 using nested calls to Math.min */45 } // end method minimum346 } // end class Min

Fig. L 6.1 | Min.java.

Page 12: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

Lab Exercises Name:

Lab Exercise 1 — Minimum

Chapter 6 Methods: A Deeper Look 227

Problem-Solving Tips1. 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 ofanother call to Math.min. The return value of one Math.min method call will be used as an argumentpassed 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.java2 // Test application for class Min3 public class MinTest4 {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

Page 13: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

Lab Exercises Name:

Lab Exercise 1 — Minimum

228 Methods: A Deeper Look Chapter6

Solution

1 // Lab 1: Min.java2 // Program finds the minimum of 3 numbers3 import java.util.Scanner;45 public class Min6 {7 // find the minimum of three numbers8 public void findMinimum()9 {

10 Scanner input = new Scanner( System.in );1112 double one; // first number13 double two; // second number14 double three; // third number1516 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 <ctrl> d then press Enter",19 "On Windows type <ctrl> z then press Enter" );20 System.out.print( "Or enter first number: " );2122 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();2930 System.out.printf( " Minimum is %f\n",31 minimum3( one, two, three ) );3233 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 <ctrl> d then press Enter",36 "On Windows type <ctrl> z then press Enter" );37 System.out.print( "Or enter first number: " );38 } // end while39 } // end method findMinimum4041 // determine the smallest of three numbers42 public double minimum3( double one, double two, double three )43 {44 // use a nested pair of min statements45 return Math.min( Math.min( one, two ), three );46 } // end method minimum347 } // end class Min

Page 14: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

Lab Exercises Name:

Lab Exercise 1 — Minimum

Chapter 6 Methods: A Deeper Look 229

Follow-Up Question and Activity1. Modify the program in Lab Exercise 1 to compute the minimum of four double values.

1 // Lab 1: MinTest.java2 // Test application for class Min3 public class MinTest4 {5 public static void main( String args[] )6 {7 Min application = new Min();8 application.findMinimum();9 } // end main

10 } // end class MinTest

Page 15: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

Lab Exercises Name:

Lab Exercise 1 — Minimum

230 Methods: A Deeper Look Chapter6

Solution

1 // Lab 1: Min.java2 // Program finds the minimum of 4 numbers3 import java.util.Scanner;45 public class Min6 {7 // find the minimum of three numbers8 public void findMinimum()9 {

10 Scanner input = new Scanner( System.in );1112 double one; // first number13 double two; // second number14 double three; // third number15 double four; // fourth number1617 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 <ctrl> d then press Enter",20 "On Windows type <ctrl> z then press Enter" );21 System.out.print( "Or enter first number: " );2223 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();3233 System.out.printf( " Minimum is %f\n",34 minimum4( one, two, three, four ) );3536 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 <ctrl> d then press Enter",39 "On Windows type <ctrl> z then press Enter" );40 System.out.print( "Or enter first number: " );41 } // end while42 } // end method findMinimum4344 // determine the smallest of four numbers45 public double minimum4( double one, double two, double three, double four )46 {47 // use a nested pair of min statements48 return Math.min( Math.min( one, two ), Math.min( three, four ) );49 } // end method minimum450 } // end class Min

Page 16: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

Lab Exercises Name:

Lab Exercise 1 — Minimum

Chapter 6 Methods: A Deeper Look 231

1 // Lab 1: MinTest.java2 // Test application for class Min3 public class MinTest4 {5 public static void main( String args[] )6 {7 Min application = new Min();8 application.findMinimum();9 } // end main

10 } // end class MinTest

Page 17: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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. Theproblem 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 replacedwith 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 theprogram. Compare your output with the sample output provided. The source code for the template is availableat www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel.

Lab ObjectivesThis 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 ProblemA 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-hourperiod is $10.00. Assume that no car parks for longer than 24 hours at a time.Write an application that calculatesand displays the parking charges for each customer who parked in the garage yesterday. You should enter thehours parked for each customer. The program should display the charge for the current customer and shouldcalculate 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): 2Current charge: $2.00, Total receipts: $2.00Enter number of hours (a negative to quit): 10Current charge: $5.50, Total receipts: $7.50Enter number of hours (a negative to quit): -1

Page 18: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

Lab Exercises Name:

Lab Exercise 2 — Garage

234 Methods: A Deeper Look Chapter6

Program Template

1 // Lab 2: Garage.java2 // Program calculates charges for parking3 import java.util.Scanner;45 public class Garage6 {7 // begin calculating charges8 public void startCharging()9 {

10 Scanner input = new Scanner( System.in );1112 double totalReceipts = 0.0; // total fee collected for the day13 double fee; // the charge for the current customer14 double hours; // hours for the current customer1516 // read in the first customer's hours17 System.out.print(18 "Enter number of hours (a negative to quit): " );19 hours = input.nextDouble();2021 while ( hours >= 0.0 )22 {23 /* Write code here to calculate the fee and assign it to the variable fee */2425 /* Write code here to calculate the total receipts */2627 System.out.printf(28 "Current charge: $%.2f, Total receipts: $%.2f\n",29 fee, totalReceipts );3031 // read in the next customer's hours32 System.out.print(33 "Enter number of hours (a negative to quit): " );34 hours = input.nextDouble();35 } // end while loop36 } // end method startCharging3738 // determines fee based on time39 /* Write the header for the calculateCharges method */40 {41 // apply minimum charge42 /* Write a line of code that declares and initializes a variable43 with the minimum charge of $2 */4445 // add extra fees as applicable46 /* Write an if statement that determines whether hours is greater47 than 3.0 and, if so, calculates the additional charge. */4849 // apply maximum value if needed50 /* Write code here that determines whether the 10 hour maximum has been reached51 and if so sets the maximum charge */5253 /* Write a line of code that returns the calculated charge */54 } // end method calculateCharges55 } // end class Garage

Fig. L 6.3 | Garage.java.

Page 19: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

Lab Exercises Name:

Lab Exercise 2 — Garage

Chapter 6 Methods: A Deeper Look 235

Problem-Solving Tips1. 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 inputby 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.java2 // Test application for class Garage3 public class GarageTest4 {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.

Page 20: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

Lab Exercises Name:

Lab Exercise 2 — Garage

236 Methods: A Deeper Look Chapter6

Solution

1 // Lab 2: Garage.java2 // Program calculates charges for parking3 import java.util.Scanner;45 public class Garage6 {7 // begin calculating charges8 public void startCharging()9 {

10 Scanner input = new Scanner( System.in );1112 double totalReceipts = 0.0; // total fee collected for the day13 double fee; // the charge for the current customer14 double hours; // hours for the current customer1516 // read in the first customer's hours17 System.out.print(18 "Enter number of hours (a negative to quit): " );19 hours = input.nextDouble();2021 while ( hours >= 0.0 )22 {23 // calculate and print the charges24 fee = calculateCharges( hours );25 totalReceipts += fee;26 System.out.printf(27 "Current charge: $%.2f, Total receipts: $%.2f\n",28 fee, totalReceipts );2930 // read in the next customer's hours31 System.out.print(32 "Enter number of hours (a negative to quit): " );33 hours = input.nextDouble();34 } // end while loop35 } // end method startCharging3637 // determines fee based on time38 public double calculateCharges( double hours )39 {40 // apply minimum charge41 double charge = 2.0;4243 // add extra fees as applicable44 if ( hours > 3.0 )45 charge = 2.0 + 0.5 * Math.ceil( hours - 3.0 );4647 // apply maximum value if needed48 if ( charge > 10.0 )49 charge = 10.0;5051 return charge;52 } // end method calculateCharges53 } // end class Garage

Page 21: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

Lab Exercises Name:

Lab Exercise 2 — Garage

Chapter 6 Methods: A Deeper Look 237

1 // Lab 2: GarageTest.java2 // Test application for class Garage3 public class GarageTest4 {5 public static void main( String args[] )6 {7 Garage application = new Garage();8 application.startCharging();9 } // end main

10 } // end class GarageTest

Page 22: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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 experienceoutside the classroom and laboratory environment. They serve as a review after you have successfully completedthe 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;34 public class CodingEX15 {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 );1314 System.out.printf( "result: %d\n", result );15 } // end method remainder1617 public int modulus( int x )18 {19 int k = ( x % 7 );20 return k ;21 } // end method modulus22 } // end class CodingEX1

1 // Coding Exercise: Question 1:2 public class CodingEx1Test3 {4 public static void main( String args[] )5 {6 CodingEX1 application = new CodingEX1();7 application.remainder();8 } // end main9 } // end class CodingEx1Test

Page 23: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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 CodingEX23 {4 public void flip()5 {6 int tail = 0, head = 0, face;78 for ( int roll = 1; roll <= 10; roll++ ) {9 face = 1 + ( int ) ( Math.random() * 2 );

1011 switch ( face )12 {13 case 1:14 ++head;15 break;1617 case 2:18 ++tail;19 break;20 } // end switch21 } // end for2223 System.out.printf( "Tails\tHeads\n%d\t%d\n", tail, head );24 } // end method flip25 } // end class CodingEX2

1 // Coding Exercise: Question 2:2 public class CodingEx2Test3 {4 public static void main( String args[] )5 {6 CodingEx2 application = new CodingEx2();7 application.flip();8 } // end main9 } // end class CodingEx2Test

Page 24: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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 shouldreturn false. Incorporate this method into an application that enables the user to enter values to test themethod.

1 // Coding Exercise: Question 3:2 import java.util.Scanner;34 public class CodingEX35 {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();1415 System.out.println("Please Enter another integer: ");16 secondNum = input.nextInt();1718 divides = multiple(firstNum, secondNum);19 System.out.printf( "Is %d divisible by %d? %b\n", firstNum, secondNum, divides );20 }2122 public boolean multiple( int number, int factor )23 {24 if ( ( number % factor ) == 0 )25 return true;26 else27 return false;28 } // end method calculateTotal29 } // end class CodingEX3

1 // Coding Exercise: Question 3:2 public class CodingEx3Test3 {4 public static void main( String args[] )5 {6 CodingEx3 application = new CodingEx3();7 application.testDivisibility();8 } // end main9 } // end class CodingEx3Test

Page 25: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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 thevalue of that number divided by 2. Incorporate this method into an application that enables the user to entervalues to test the method.

1 // Coding Exercise: Question 4:2 import java.util.Scanner;34 public class CodingEX45 {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 );1314 System.out.printf( "Half of the number %d is %d\n", number, half );15 }1617 public int halve( int x )18 {19 return x / 2;20 } // end method halve21 } // end class CodingEX4

1 // Coding Exercise: Question 4:2 public class CodingEx4Test3 {4 public static void main( String args[] )5 {6 CodingEx4 application = new CodingEx4();7 application.halveNumber();8 } // end main9 } // end class CodingEx4Test

Page 26: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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 computesand returns the difference between the first and second number. Incorporate this method into an applicationthat enables the user to enter values to test the method.

1 // Chapter 6: Coding Exercise: Number 5:2 import java.util.Scanner;34 public class CodingEx55 {6 public void difference()7 {8 Scanner input = new Scanner( System.in );9

10 double firstNumber, secondNumber;1112 System.out.println( "Please enter your first floating-point number" );13 firstNumber = input.nextDouble();1415 System.out.println( "Please enter your second floating-point number" );16 secondNumber = input.nextDouble();1718 System.out.printf( "The difference between %.2f and %.2f is %.2f\n", firstNumber,19 secondNumber, diffDouble( firstNumber, secondNumber ) );20 }2122 public double diffDouble( double number1, double number2 )23 {24 return number1 - number2;25 } // end method difference26 } // end class CodingEx5

1 // Coding Exercise: Question 5:2 public class CodingEx5Test3 {4 public static void main( String args[] )5 {6 CodingEx5 application = new CodingEx5();7 application.difference();8 } // end main9 } // end class CodingEx5Test

Page 27: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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;34 public class CodingEx65 {6 public void square()7 {8 Scanner input = new Scanner( System.in );9

10 double squareSide;1112 System.out.println( "Please enter the side of the square: " );13 squareSide = input.nextDouble();1415 System.out.printf( "The area of the square is %.2f\n", area( squareSide ) );16 } // end method square1718 public double area( int side )19 {20 return side * side;21 } // end method areaSquare22 } // end class CodingEx6

1 // Coding Exercise: Question 6:2 public class CodingEx6Test3 {4 public static void main( String args[] )5 {6 CodingEx6 application = new CodingEx6();7 application.difference();8 } // end main9 } // end class CodingEx6Test

Page 28: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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 amountof time to complete. Write a Java program for each of the problems in this section. The answers to these problemsare available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel. Pseudocode, hints or sampleoutputs 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 andreturn values should be of type double. Incorporate this method into an application that enables the user toenter 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 terminateOn UNIX/Linux/Mac OS X type <ctrl> d then press EnterOn Windows type <ctrl> z then press Enter

Or Enter X1: 1Enter Y1: 1Enter X2: 4Enter Y2: 5Distance is 5.000000

Type the end-of-file indicator to terminateOn UNIX/Linux/Mac OS X type <ctrl> d then press EnterOn Windows type <ctrl> z then press Enter

Or Enter X1: ^Z

1 // Programming Challenge 1: Points.java2 // Program calculates the distance between two points.3 import java.util.Scanner;45 public class Points6 {7 // calculates the distance between two points8 public void calculateDistance()9 {

10 Scanner input = new Scanner( System.in );11

Page 29: Methods: A Deeper Look - University of Pittsburghpeople.cs.pitt.edu/~khalifa/hrs2422/activities/Labs/LabCh6Methods.pdf · Short Answer Chapter 6Methods: A Deeper Look 215 Name:

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 <ctrl> d then press Enter",15 "On Windows type <ctrl> z then press Enter" );16 System.out.print( "Or Enter X1: " );1718 // continually read in inputs until the user terminates19 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();2829 double distance = distance( x1, y1, x2, y2 );30 System.out.printf( "Distance is %f\n\n", distance );3132 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 <ctrl> d then press Enter",35 "On Windows type <ctrl> z then press Enter" );36 System.out.print( "Or Enter X1: " );37 } // end while38 } // end method calculateDistance3940 // calculate distance between two points41 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 distance46 } // end class Points

1 // Programming Challenge 1: PointsTest.java2 // Test application for class Points3 public class PointsTest4 {5 public static void main( String args[] )6 {7 Points application = new Points();8 application.calculateDistance();9 } // end main

10 } // end class PointsTest