chapter 7 methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. determine the type...

22
Chapter 7 Methods O bject-oriented programs use classes with methods to perform tasks. A program often performs several tasks, each with its own level of complexity. To manage these tasks, they are broken down into methods. This chapter discusses top-down program development and writing and documenting methods. Program Development Using Methods The solution to a task can be developed by breaking the task down into smaller subtasks. These subtasks can then be reduced to yet simpler tasks. This process can be continued until the original task is broken down into units that each describe a specific goal. As the task is broken down into smaller subtasks and then further into units, more detail for achieving the specific goal is added. This problem-solving approach describes a software development process called top-down development. In top-down development, the first level of subtasks translates into the main() method. Levels of tasks below main() are developed into a series of additional methods. Using methods to define tasks is called procedural abstraction. For example, consider the following program specification: TempConverter allows the user to convert a temperature from either Fahrenheit to Celsius or Celsius to Fahrenheit. The algorithm for this application breaks the program specification down into the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula. Step 2 can then be broken down into another level of subtasks: 2a. Prompt the user for a Celsius temperature. Convert the temperature to Fahrenheit using the formula: F=9/ 5C + 32. Display the temperature. 2b. Prompt the user for a Fahrenheit temperature. Convert the temperature to Celsius using the formula: C=5/ 9(F – 32). Display the temperature. Chapter 7 Methods O bject-oriented programs use classes with methods to perform tasks. A program often performs several tasks, each with its own level of ks, each w complexity. To manage these tasks, they are broken down into methods. e broken dow The solution to a task can be developed by breaking the task down into k can be de d by smaller subtasks. These subtasks can then be reduced to yet simpler tasks. hese subtasks ca This process can be continued until the original task is broken down into e continued unti units that each describe a specific goal. As the task is broken down into ch descr e a specific smaller subtasks and then further into units, more detail for achieving the asks and th furthe specific goal is added. This problem-solving approach describes a software goal is added. This p oblem-s development process called top-down development. lopment process calle -dow In top-down development, the first level of subtasks translates into the n top-down develo main() Levels of tasks below main() are developed into a series Le method. method. of additional methods. al me

Upload: dokien

Post on 30-Apr-2019

230 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

O bject-or iented program s u se classes w ith m ethod s to p erform tasks. A program often perform s several tasks, each w ith its ow n level of complexity. To manage these tasks, they are broken dow n into methods. This chapter d iscusses top-dow n program development and w riting and documenting methods.

Program Development Using Met hods The solution to a task can be developed by breaking the task dow n into smaller subtasks. These subtasks can then be reduced to yet simpler tasks. This process can be continued u ntil the original task is broken dow n into u nits that each describe a specific goal. As the task is broken dow n into smaller subtasks and then fu rther into units, more detail for achieving the specific goal is added. This problem-solving approach describes a software development process called top-down development.

In top-dow n development, the first level of subtasks translates into the main() method. Levels of tasks below main() are developed into a series of add itional methods. Using methods to define tasks is called procedural abstraction. For example, consider the follow ing program specification:

TempConverter allows the u ser to convert a temperatu re from either Fahrenheit to Celsius or Celsius to Fahrenheit.

The algorithm for th is application breaks the program specification dow n into the first level of subtasks:

1. Determ ine the type of conversion to be done.

2. Convert the temperatu re using the appropriate formula.

Step 2 can then be broken dow n into another level of subtasks:

2a. Prompt the user for a Celsius temperatu re. Convert the temperatu re to Fahrenheit using the formula: F=9/ 5C + 32. Display the temperatu re.

2b. Prompt the user for a Fahrenheit temperatu re. Convert the temperatu re to Celsius using the formula: C=5/ 9(F – 32). Display the temperatu re.

Chapter 7Met hods

O bject-or iented program s u se classes w ith m ethod s to p erform tasks. A program often perform s several tasks, each w ith its ow n level of ks, each wcomplexity. To manage these tasks, they are broken dow n into methods. e broken dow

The solution to a task can be developed by breaking the task dow n into k can be de d bysmaller subtasks. These subtasks can then be reduced to yet simpler tasks.hese subtasks caThis process can be continued u ntil the original task is broken dow n into e continued u ntiu nits that each describe a specific goal. As the task is broken dow n into ch descr e a specific smaller subtasks and then fu rther into units, more detail for achieving the asks and th furthespecific goal is added. This problem-solving approach describes a software goal is added. This p oblem-sdevelopment process called top-down development.lopment process calle -dow

In top-dow n development, the first level of subtasks translates into the n top-dow n develomain() Levels of tasks below main() are developed into a series Le method. method. of add itional methods. Ual me

Page 2: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

Top-dow n development and procedu ral abstraction were used to break the program specification dow n into levels of subtasks, as show n on the previous page. Outlin ing the levels of subtasks in pseudocode defines a main() method and two other methods:

mai n( )Pr ompt t he user f or t he conver s i on t ype.Execut e t he appr opr i at e met hod t o conver t t he t emper at ur e.

f ahr enhei t ToCel s i us( )Pr ompt t he user f or a t emper at ur e i n degr ees Fahr enhei tConver t t he t emper at ur e t o degr ees Cel s i usDi s pl ay t he t emper at ur e

cel s i us ToFahr enhei t ( )Pr ompt t he user f or a t emper at ur e i n degr ees Cel s i usConver t t he t emper at ur e t o degr ees Fahr enhei tDi s pl ay t he t emper at ur e

The TempConverter application implements the pseudocode above:

i mpor t j ava. ut i l . Scanner ; publ i c cl as s TempConver t er { publ i c s t at i c voi d f ahr enhei t ToCel s i us( ) { doubl e f Temp, cTemp; Scanner i nput = new Scanner ( Sys t em. i n) ; Sys t em. out . pr i nt ( "Ent er a Fahr enhei t t emper at ur e: ") ; f Temp = i nput . next Doubl e( ) ; i nput . cl os e( ) ; cTemp = ( doubl e) 5/ ( doubl e)9*( f Temp - 32) ; Sys t em. out . pr i nt l n( "The Cel s i us t emper at ur e i s " + cTemp) ; }

publ i c s t at i c voi d cel s i us ToFahr enhei t ( ) { doubl e cTemp, f Temp; Scanner i nput = new Scanner ( Sys t em. i n) ; Sys t em. out . pr i nt ( "Ent er a Cel s i us t emper at ur e: ") ; cTemp = i nput . next Doubl e( ) ; i nput . cl os e( ) ; f Temp = ( doubl e)9/ ( doubl e) 5*cTemp + 32; Sys t e m. out . pr i nt l n( " The Fa hr e nhe i t t e mpe r a t u r e i s " + f Temp) ; }

publ i c s t at i c voi d mai n( St r i ng[ ] ar gs ) { i nt choi ce; Scanner i nput = new Scanner ( Sys t em. i n) ; / * Pr ompt us er f or t ype of conver s i on */ Sys t em. out . pr i nt l n( "1. Fahr enhei t t o Cel s i us conver s i on.") ; Sys t em. out . pr i nt l n( "2. Cel s i us t o Fahr enhei t conver s i on.") ; Sys t em. out . pr i nt ( "Ent er your choi ce: ") ; choi ce = i nput . next I nt ( ) ; i f ( choi ce == 1) { f ahr enhei t ToCel s i us( ) ; } el s e { cel s i us ToFahr enhei t ( ) ; } i nput . cl os e( ) ; }}

Page 3: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

The TempConverter controlling class contains two method s as well as a main() method. The methods are executed when they are called. A method call consists of the method name followed by parentheses. The i f statement in the main() method on the previous page contains two method calls, f ahr enhei t ToCel s i us( ) and cel s i us ToFahr enhei t ( ) .

TempConverter produces output sim ilar to:

In th is ru n of the ap plicat ion , the u ser entered 1 and therefore the fahrenheitToCelsius() method was called.

Writ ing Met hods A method consists of a declaration and a body. The method declaration includes access level, return type, name, and parameters, if any. The method body contains the statements that implement the method. A method takes the form:

<access _ l evel > <r et ur n _ t ype> <name>( <par amet er s >) { <s t at ement s >}

For exam ple, con sid er the fah ren heitToCelsiu s () m ethod from the TempConverter application:

publ i c s t at i c voi d f ahr enhei t ToCel s i us( ) { doubl e f Temp, cTemp; Scanner i nput = new Scanner ( Sys t em. i n) ; Sys t em. out . pr i nt ( "Ent er a Fahr enhei t t emper at ur e: ") ; f Temp = i nput . next Doubl e( ) ; i nput . cl ose( ) ; cTemp = ( doubl e) 5/ ( doubl e)9*( f Temp - 32) ; Sys t em. out . pr i nt l n( "The Cel s i us t emper at ur e i s " + cTemp); }

The method above is a class method w ith access level publ i c, retu rn type voi d, name fahrenheitToCelsius, and no parameters. The access level of a method determines if other classes can call the method. The keyword publ i c is an access modifier. A public method can be called by any other method. The access level of a method can also be thought of as its visibility. Access levels are d iscussed fu rther in Chapter 8.

The keyword s t at i c declares the method a class method. A class method can be called from the class itself. Methods that are not class methods must be called from an instantiated object of that class.

The retu rn type voi d means that the method w ill not retu rn a value, and parameters are specified when a method needs values to perform its task. The body of the method starts w ith the first opening brace ({) and ends w ith the closing brace (}).

The methods are executed when they are called. A method call consists of the method name followed by parentheses. T

A method consists of a declaration and a body. The method declaration declara dy. The mincludes access level, return type, name, and parameters, if any. The method e, nambody contains the statements that implement the method. A method takesmplemthe form:

<access _ l evel > <r et ur n _ t ype> <name>( <par am> <r et ur n _ > <n et er s >) {mm_<s t at ement s >nt s >

}

publ i c s t at i c voi d f ahr enhei t ToCel s i us( ) {publ i c s t at i c voi hr enh

The method above is a class method w ith access level c, retu rn publ itype d, name fahrenheitToCelsius, and no parameters. The access levelvoiof a method determines if other classes can call the method. The keyword

is an access modifier. A public method can be called by any other publ i c method. The access level of a method can also be thought of as its visibility.

The keyword declares the method a class method. A class method s t at i c can be called from the class itself. M

The retu rn type means that the method w ill not retu rn a value,voi d and parameters are specified when a method needs values to perform itstask. The body of the method starts w ith the first opening brace ({) and ends w ith the closing brace (}).

Page 4: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

Method names shou ld ind icate an action. Verbs m ake good method names. A method name shou ld also begin w ith a lowercase letter and then an uppercase letter should begin each word within the name. Method names may not contain spaces.

Methods can also have their ow n set of variables, constants, and objects. Variable, constant, and object declarations in the body of a method have a scop e th at extend s from the d eclarat ion to the end of the m ethod body. These variables, constants, and objects are said to be local to the method because their scope is lim ited to that method. For example, the fahrenheitToCelsius() method contains local variables f Temp and cTemp and a local object named i nput .

Review : TimeConver t erCreate a TimeConverter application that allows the user to choose among converting hours to m inutes, days to hours, m inutes to hours, or hours to days. Use methods as appropriate.

Met hod Parameters A method declaration can include method parameters, which accept values from the method call. The data passed to the method can then be used inside the method to perform its task. For example, the d rawBar() method includes an i nt parameter named l engt h:

publ i c s t at i c voi d dr awBar ( i nt l engt h) {

f or ( i nt i = 0; i < l engt h; i ++) { Sys t em. out . pr i nt ( "*") ; } Sys t em. out . pr i nt l n( ) ;}

Data is given, or passed, to a method by enclosing the data in parentheses in the method call. The value or variable passed to a method is called the argument. For example, the RightTriangle application makes six calls to d rawBar(). Each call passes a d ifferent variable argu ment:

publ i c cl as s Ri ght Tr i angl e { publ i c s t at i c voi d dr awBar ( i nt l engt h) { f or ( i nt i = 1; i <= l engt h; i ++) { Sys t em. out . pr i nt ( "*") ; } Sys t em. out . pr i nt l n( ) ; }

publ i c s t at i c voi d mai n( St r i ng[ ] ar gs ) { / * dr aw a r i ght t r i angl e wi t h bas e s i ze 6 */ f or ( i nt i = 1; i <= 6; i ++) { dr awBar ( i ) ; } }}

Method names shou ld ind icate an action. Verbs m ake good method names. A method name shou ld also begin w ith a lowercase letter and then an uppercase letter should begin each word within the name. Method names may not contain spaces.

Methods can also have their ow n set of variables, constants, and objects. Variable, constant, and object declarations in the body of a method have a scop e th at extend s from the d eclarat ion to the end of the m ethod body. These variables, constants, and objects are said to be local to the method because their scope is lim ited to that method.

A method declaration can include method parameters, which accept valuescan include d pafrom the method call. The data passed to the method can then be usedl. The data pasinside the method to perform its task. F perform its task

Data is given, or passed, to a method by enclosing the data in parentheses Data isin the method call. The value or variable passed to a method is called the in the meargument. argumen

Page 5: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

The RightTriangle application produces the output:

In Java, arguments are passed by value, which means that the data stored in an argument is passed. An argument that is a primitive data type gives the method a copy of its value. An argu ment that is an object gives the method a copy of its reference that points to methods for changing object data. Therefore, a method can change the data stored in an object because it has access to the object’s methods, but it cannot change the data stored in a prim itive variable becau se the method does not have access to the actual location of the prim itive data.

When a method declaration includes more than one parameter, the parameters are separated by com mas. For example, a mod ified d rawBar() has an i nt parameter for the length of the bar and a String parameter for the character to u se to d raw the bar:

publ i c s t at i c voi d dr awBar ( i nt l engt h, St r i ng mar k) {

f or ( i nt i = 1; i <= l engt h; i ++) { Sys t em. out . pr i nt ( mar k) ; } Sys t em. out . pr i nt l n( ) ;}

A call to the modified d rawBar() method includes two arguments sepa-rated by com mas:

dr awBar ( 6, "$") ;

This call produces the follow ing output:

The order of the argu ments in a method call is important because the first argu ment corresponds to the first parameter in the method declara-tion, the second argu ment corresponds to the second parameter, and so on. Note that argument names do not necessarily match parameter names. Descriptive variable names shou ld be used throughout a program without regard to matching parameter names in a method declaration.

Review : SpanishNumbersCreate a SpanishNumbers application that d isplays nu mbers 1 through 10 in Spanish. A method w ith an i nt parameter shou ld d isplay the Spanish word for the number passed. A loop structu re in the main() method shou ld be used to call the method ten times. The Spanish word equ ivalents for numbers 1 through 10 are:

1 u no 6 seis2 dos 7 siete3 tres 8 ocho4 cuatro 9 nueve5 cinco 10 d iez

In Java, arguments are passed by value, which means that the data stored inn an argument is passed. An argument that is a primitive data type gives

of its value. An argu ment that is an object gives the the method a copy method a copy of its reference that points to methods for changing object data. Therefore, a method can change the data stored in an object because it has access to the object’s methods, but it cannot change the data stored in a prim itive variable becau se the method does not have access to theactual location of the prim itive data.

When a method declaration includes more than one parameter, theore than oneparameters are separated by com mas. Fy co

The order of the argu ments in a method call is important because the The first argu ment corresponds to the first parameter in the method declara-irst ation, the second argu ment corresponds to the second parameter, and so tionon. Note that argument names do not necessarily match parameter names. Descriptive variable names shou ld be used throughout a program without regard to matching parameter names in a method declaration.

Page 6: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

Review : DisplayBox – par t 1 of 2Create a DisplayBox application that prompts the user for a height and width and then d isplays a box of that size. The DisplayBox application shou ld include a method named d rawBox() that has two parameters and makes calls to the d rawBar() method.

Met hod Overloading The method declaration is u sed by the compiler to determ ine which method to execute. Therefore, method names do not have to be u nique as long as the parameters are d ifferent for methods w ith the same name. Method overloading is when more than one method of the same name is included in a class. For example, the follow ing application contains two d rawBar() methods:

publ i c cl as s Met hodOver l oadi ngExampl e {

publ i c s t at i c voi d dr awBar ( i nt l engt h) { f or ( i nt i = 1; i <= l engt h; i ++) { Sys t em. out . pr i nt ( "*") ; } Sys t em. out . pr i nt l n( ) ; }

publ i c s t at i c voi d dr awBar ( i nt l engt h, St r i ng mar k) { f or ( i nt i = 1; i <= l engt h; i ++) { Sys t em. out . pr i nt ( mar k) ; } Sys t em. out . pr i nt l n( ) ; }

publ i c s t at i c voi d mai n( St r i ng[ ] ar gs ) { dr awBar ( 10) ; dr awBar ( 5, "@") ; }}

The MethodOverload ing application produces the output:

Note that the first call in main() executes the drawBar() method containing only one parameter. The second call executes the d rawBar() method that contains two parameters. The compiler uses the types, order, and number of parameters to determ ine which method to execute.

The method declaration is u sed by the compiler to determ ine which method to execute. Therefore, method names do not have to be u nique as long as the parameters are d ifferent for methods w ith the same name. Method overloading is when more than one method of the same name is included in a class.

The compiler uses the types, order, and number of parameters to determ ine which method to execute.

Page 7: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

Review : DisplayBox – par t 2 of 2Mod ify the DrawBox application to ask the user if a specific character shou ld be used for the d isplay. For example, the prompt cou ld be “Do you want to enter a character to use to d isplay the box? (enter y for yes):” If the user types y, then prompt the user for the character. Otherw ise, the defau lt character shou ld be used. The mod ified application shou ld contain overloaded d rawBox() and d rawBar() methods.

The ret urn St atement A method can retu rn a value. For example, the cubeOf() method returns the cube of its parameter:

publ i c s t at i c doubl e cubeOf( doubl e x) { doubl e xCubed; xCubed = x * x * x; r et ur n( xCubed) ;}

The r et ur n statement is used to send a value back to the calling statement. A r et ur n statement can retu rn only one value.

A method that retu rns a value mu st include the retu rn typ e in the m ethod d eclarat ion . For exam ple, the cu beOf() m ethod d eclarat ion declares a retu rn type doubl e. Retu rn types can be prim itive types, such as i nt , doubl e, and bool ean, or abstract types, such as the String class. The retu rn type voi d is u sed when there w ill be no retu rn value. A method declared as voi d does not contain a r et ur n statement.

A method that retu rn s a value is called from a statement that w ill make use of the retu rned value, such as an expression or an assignment statement. For example, the follow ing application calls cubeOf() from an assignment statement:

publ i c cl as s CubeCal cul at or { publ i c s t at i c doubl e cubeOf( doubl e x) { doubl e xCubed; xCubed = x * x * x; r et ur n( xCubed) ; }

publ i c s t at i c voi d mai n( St r i ng[ ] ar gs ) { doubl e num = 2.0; doubl e cube; cube = cubeOf( num); Sys t em. out . pr i nt l n( cube) ; }}

The CubeCalcu lator application produces the following output:

A method can retu rn a value. F

The statement is used to send a value back to the calling statement.send ar et ur n A statement can retu rn only one value.y one r et ur n

A method that retu rns a value mu st include the retu rn typ e in the rns a val st incFor exam ple, the cu beOf() m ethod d eclarat ionFor exam p em ethod d eclarat ion . n .

declares a retu rn typype e.. Retu rn types can be prim itive types, suchRetudoubldoas e, andand eanean, or , o types, such as the String class. The abstract stri nt , doubl boolb lretu rn type is u sed when there w ill be no retu rn value. A methodis u s when thvoi dvoi d declared as as does not contain aes not coontain statement.voi dvo d r et ur n

A method that retu rn s a value is called from a statement that w illmethod that retu rn lue as an expression or an assignmentmake use of the retu rned value, such ke use of the retu rn

statement. ent.

Page 8: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

Review : Exponent iat ionCreate an Exponentiation application that prompts the user for two numbers and then d isplays the first num-ber raised to the power of the second number. The application shou ld include a method named powerOf() that retu rns its first parameter raised to the power of its second parameter.

Document ing Met hods Methods should be carefu lly commented so that a reader of the program u nderstands what task the method is perform ing and what data, if any, w ill be retu rned by the method. Method documentation is in the form of docu mentation com ments (/ ** */ ) that appear just above the method declaration. For example, the d rawBar() method w ith documentation:

/ ** * Pr i nt a bar of as t er i s ks acr os s t he scr een. * pr e: l engt h > 0 * pos t : Bar dr awn of l engt h char act er s , i ns er t i on * poi nt moved t o next l i ne. */publ i c s t at i c voi d dr awBar ( i nt l engt h) {

f or ( i nt i = 0; i < l engt h; i ++) { Sys t em. out . pr i nt ( "*") ; } Sys t em. out . pr i nt l n( ) ;}

The assu mptions, or in itial requ irements, of a method are stated in the docu mentation in a section called the precondition, or just pr e. Note that the pre for d rawBar() states that l engt h must be greater than 0, but not that l engt h must be an i nt . Information that the compiler w ill verify, such as data types, shou ld not be stated in method documentation.

The postcondition section of the documentation, or pos t , states what must be true after the method has been executed. However, the post shou ld not state how the method accomplished its task.

A m ethod m ay not h ave a p recond it ion , bu t every m ethod mu st have a postcond ition. For example, below is the cubeOf() method w ith docu mentation:

/ ** * Cal cul at es t he cube of a number . * pr e: none * pos t : x cubed r et ur ned */publ i c s t at i c doubl e cubeOf( doubl e x) { doubl e xCubed; xCubed = x * x * x; r et ur n( xCubed);}

Methods should be carefu lly commented so that a reader of the program u nderstands what task the method is perform ing and what data, if any, w ill be retu rned by the method. Method documentation is in the form of docu mentation com ments (/(( ) that appear just above the method/ ** */ )declaration. F

/ *** Pr i nt a bar of as t er i s ks acr os s t he scr een.he s* pr e: l engt h > 0p g* pos t : Bar dr awn of l engt h char act er s , i ns er t i onof l eng , i ns er tp gg* poi nt moved t o next l i ne.i ne.mm*/

The assu mptions, or in itial requ irements, of a method are stated in the su mptions, or in itial requ iremdocu mentation in a section called the precondition, or just mentation in a section d th e. pr e

Information that the compiler w ill verify, such as

true after the method has been executed. However, the post shou ld nottrue astate how the method accomplished its task.e how

A m ethod m ay not h ave a p recond it ion , bu t every m ethod mu stA have a postcond ition.

postcondition section of the documentation, or nd , states what must pos tbebee e

data types, shou ld not be stated in method documentation., shou ld n

TTThe p

Page 9: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

To sum marize, the gu idelines for w riting pre and post cond itions are:

• The precond ition states what must be true at the beginning of a method for the method to work properly.

• The postcond ition states what must be true after the method has executed if the method has worked properly.

• Precond itions and postcond itions shou ld not state facts that the compiler w ill verify. They shou ld also not refer to variables or information outside the method.

• The postcond ition shou ld not state how the method accomplished its task.

ReviewMod ify each of the Reviews in th is chapter so that the methods are properly documented.

Chapter 7 Case St udy

This case study w ill focus on top-dow n development and procedural abstract ion. Testing and debugging method s in isolation w ill also be demonstrated.

An application for generating a letter grade based on a numeric grade w ill be created. The GradeConverter application allows the user to enter a numeric grade and then a letter grade is d isplayed. The user may then choose to enter another grade or qu it.

GradeConverter Specification

The GradeConverter application prompts the user for a numeric grade in the range 0 to 100 or a –1 to end the application. When a valid nu meric grade is entered, the correspond ing letter grade is then d isplayed. Grades from 90 to 100 are an A, grades from 80 to 89 are a B, grades from 70 to 79 are a C, grades from 60 to 69 are a D, and grades below 60 are an F. After d isplaying the correspond ing letter grade, the user is prompted to enter another letter grade or can choose to qu it the application.

The GradeConverter interface shou ld include a prompt asking for the nu meric grade. The prompt shou ld give the option of qu itting the appli-cation. After d isplaying the letter grade, the user shou ld be prompted to enter another numeric grade or qu it the application.

The GradeConverter output sketch:

����������������������������������������������������������������������������������������������������������������������������������������������������������������

To sum marize, the gu idelines for w riting pre and post cond itions are:

• The precond ition states what must be true at the beginning of amethod for the method to work properly.

• The postcond ition states what must be true after the method hasexecuted if the method has worked properly.

• Precond itions and postcond itions shou ld not state facts that the compiler w ill verify. They shou ld also not refer to variables orinformation outside the method.

• The postcond ition shou ld not state how the method accomplishedits task.

Page 10: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

The GradeConverter algorithm:

1. Prompt the user for a number.

2. Determ ine the letter grade that correspond s to the entered numeric grade and d isplay the resu lt.

3. Repeat steps 1 and 2 u ntil the user chooses to qu it.

The GradeConverter flowchart:

�����

���������������������������

����������������������������������

���

GradeConverter Code Design

Using the top -dow n development approach, the algorithm is fu rther refined :

Step 1 of the algorithm can be broken dow n fu rther:

1a. Display a prompt that gives the user the option to qu it.

Check that the number entered is valid. It shou ld correspond to either a sentinel value that ind icates the user wants to qu it or a number in the range 0 through 100.

Step 2 of the algorithm can be broken dow n fu rther:

2a. Determ ine if the numeric grade is between 90 to 100, 80 to 89, 70 to 79, 60 to 69, or 0 to 59.

Assign the letter A to a grade from 90 to 100, a letter B to a grade from 80 to 89, the letter C to a grade from 70 to 79, the letter D to a grade from 60 to 69, and the letter F to a grade from 0 to 59.

Page 11: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

Using the flowchart, algorithm, and procedural abstraction, the pseudo-code for the GradeConverter application can be created . The code w ill include a loop structure to get the user’s input and two add itional methods. One method w ill determ ine if the input is valid and another determ ines which letter corresponds to the numeric grade:

mai n( )Pr ompt t he user f or a numberwhi l e ( number ! = -1) { i f ( i sVal i dNumber ( number )) { get Let t er Gr ade( number ) Di s pl ay mes s age wi t h l et t er gr ade } Pr ompt t he user f or a number}

i sVal i dNumber ( user Num, maxNum, mi nNum)i f ( mi nNum <= us er Num <= maxNum) { r et ur n ( t r ue) ;} el s e { r et ur n( f al se) ;}

get Let t er Gr ade( numer i cGr ade)i f ( numer i cGr ade < 60) { r et ur n ( "F") ;} el s e i f ( numer i cGr ade < 70) { r et ur n ( "D") ;} el s e i f ( numer i cGr ade < 80) { r et ur n ( "C") ;} el s e i f ( numer i cGr ade < 90) { r et ur n ( "B") ;} el s e { r et ur n ( "A") ;}

GradeConverter Implementation

Testing methods in isolation is important to ensu re that the program as a whole w ill ru n w ithout error. When testing a method, statements in main() shou ld call the method using test data. The main() method shou ld not call any other method or perform any other task except test the current method.

Rather than w riting code for the entire application at once, one method at a time will be added and then tested. When testing the methods is com-plete, the main() method will be rewritten to implement the GradeConverter pseudocode.

Testing methods in isolation is important to ensu re that the program g methodass a whole w ill ru n w ithout error. When testing a method, statements in w illmain() shou ld call the method using test data. The main() method shou ld main()

other method or perform any other task except test the current not call any not callmethod.ethod

Rather than w riting code for the entire application at once, one method at a time will be added and then tested. W

Page 12: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

The isValidNu mber() method is the first method w ritten and tested :

publ i c cl as s Gr adeConver t er {

/ ** * Det er mi nes i f a numer i c ent r y i s val i d. * pr e: none * pos t : t r ue r et ur n i f mi nNum <= user Num <= maxNum; * f al s e r et ur ned ot her wi s e */ publ i c s t at i c bool ean i sVal i dNumber ( i nt us er Num, i nt mi nNum, i nt maxNum) { i f ( mi nNum <= user Num && us er Num <= maxNum) { r et ur n( t r ue) ; } el s e { r et ur n( f al s e) ; } }

publ i c s t at i c voi d mai n( St r i ng[ ] ar gs ) { f i nal i nt mi nVal ue = 0; f i nal i nt maxVal ue = 100; i nt numer i cGr ade; numer i cGr ade = 0; i f ( i sVal i dNumber ( numer i cGr ade, mi nVal ue, maxVal ue)) { Sys t em. out . pr i nt l n( numer i cGr ade + " i s val i d.") ; } el s e { Sys t em. out . pr i nt l n( numer i cGr ade + " i s NOT val i d.") ; }

numer i cGr ade = 100; i f ( i sVal i dNumber ( numer i cGr ade, mi nVal ue, maxVal ue)) { Sys t em. out . pr i nt l n( numer i cGr ade + " i s val i d.") ; } el s e { Sys t em. out . pr i nt l n( numer i cGr ade + " i s NOT val i d.") ; }

numer i cGr ade = -1; i f ( i sVal i dNumber ( numer i cGr ade, mi nVal ue, maxVal ue)) { Sys t em. out . pr i nt l n( numer i cGr ade + " i s val i d.") ; } el s e { Sys t em. out . pr i nt l n( numer i cGr ade + " i s NOT val i d.") ; }

numer i cGr ade = 101; i f ( i sVal i dNumber ( numer i cGr ade, mi nVal ue, maxVal ue)) { Sys t em. out . pr i nt l n( numer i cGr ade + " i s val i d.") ; } el s e { Sys t em. out . pr i nt l n( numer i cGr ade + " i s NOT val i d.") ; } }}

The statements in main() test the isValid Nu mber() method w ith data that includes bou ndary values. A boundary value is data that is just inside or just outside the range of valid values. For example, the value 100 lies just inside the high end of the range of valid grades. Testing the method w ith th is data verifies that the <= operator was used rather than the < operator. The GradeConverter application produces the follow ing output:

Page 13: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

Next, the getLetterGrade() method is added and the main() statements are changed to test that method:

publ i c cl as s Gr adeConver t er {

/ ** * Det er mi nes i f a numer i c ent r y i s val i d. * pr e: none * pos t : t r ue has been r et ur ned i f mi nNum <= user Num <= maxNum; * f al s e has been r et ur ned ot her wi se */ publ i c s t at i c bool ean i sVal i dNumber ( i nt us er Num, i nt mi nNum, i nt maxNum) { i f ( mi nNum <= us er Num && user Num <= maxNum) { r et ur n( t r ue) ; } el s e { r et ur n( f al se) ; } }

/ ** * Det er mi nes t he l et t er gr ade t hat cor r es ponds t o t he numer i c gr ade. * pr e: 0 <= numGr ade <= 100 * pos t : The l et t er gr ade A, B, C, D, or F has been r et ur ned. */ publ i c s t at i c St r i ng get Let t er Gr ade( i nt numGr ade) { i f ( numGr ade < 60) { r et ur n( "F") ; } el s e i f ( numGr ade < 70){ r et ur n( "D") ; } el s e i f ( numGr ade < 80) { r et ur n( "C") ; } el s e i f ( numGr ade < 90) { r et ur n( "B") ; } el s e { r et ur n( "A") ; } }

publ i c s t at i c voi d mai n( St r i ng[ ] ar gs ) { i nt numer i cGr ade; numer i cGr ade = 90; Sys t em. out . pr i nt l n( numer i cGr ade + " i s " + get Let t er Gr ade( numer i cGr ade)) ; numer i cGr ade = 89; Sys t em. out . pr i nt l n( numer i cGr ade + " i s " + get Let t er Gr ade( numer i cGr ade)) ; numer i cGr ade = 80; Sys t em. out . pr i nt l n( numer i cGr ade + " i s " + get Let t er Gr ade( numer i cGr ade)) ; numer i cGr ade = 79; Sys t em. out . pr i nt l n( numer i cGr ade + " i s " + get Let t er Gr ade( numer i cGr ade)) ; numer i cGr ade = 70; Sys t em. out . pr i nt l n( numer i cGr ade + " i s " + get Let t er Gr ade( numer i cGr ade)) ; numer i cGr ade = 69; Sys t em. out . pr i nt l n( numer i cGr ade + " i s " + get Let t er Gr ade( numer i cGr ade)) ; numer i cGr ade = 60; Sys t em. out . pr i nt l n( numer i cGr ade + " i s " + get Let t er Gr ade( numer i cGr ade)) ; numer i cGr ade = 59; Sys t em. out . pr i nt l n( numer i cGr ade + " i s " + get Let t er Gr ade( numer i cGr ade)) ; } }

Page 14: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

Bou ndary values for getLetterGrade() are tested w ith statements in main(). Ru nning GradeConverter d isplays the output:

After verifying that the method s are working as expected, the final GradeConverter application can be completed :

/ * * Gr adeConver t er .j ava */ i mpor t j ava. ut i l . Scanner ; / ** * Di s pl ay t he l et t er gr ade t hat cor r es ponds t o t he numer i c * gr ade ent er ed by t he us er . */ publ i c cl as s Gr adeConver t er {

/ ** * Det er mi nes i f a numer i c ent r y i s val i d. * pr e: none * pos t : t r ue has been r et ur ned i f mi nNum <= user Num <= maxNum; * f al s e has been r et ur ned ot her wi s e */ publ i c s t at i c bool ean i sVal i dNumber ( i nt us er Num, i nt mi nNum, i nt maxNum) { i f ( mi nNum <= user Num && us er Num <= maxNum) { r et ur n( t r ue) ; } el s e { r et ur n( f al s e) ; } } / ** * Det er mi nes t he l et t er gr ade t hat cor r es ponds t o t he numer i c gr ade. * pr e: 0 <= numGr ade <= 100 * pos t : The l et t er gr ade A, B, C, D, or F has been r et ur ned. */ publ i c s t at i c St r i ng get Let t er Gr ade( i nt numGr ade) { i f ( numGr ade < 60) { r et ur n( "F") ; } el s e i f ( numGr ade < 70){ r et ur n( "D") ; } el s e i f ( numGr ade < 80) { r et ur n( "C") ; } el s e i f ( numGr ade < 90) { r et ur n( "B") ; } el s e { r et ur n( "A") ; } }

Page 15: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

publ i c s t at i c voi d mai n( St r i ng[ ] ar gs ) { f i nal i nt FLAG = -1; f i nal i nt mi nVal ue = 0; f i nal i nt maxVal ue = 100; i nt numer i cGr ade; St r i ng l et t er Gr ade; Scanner i nput = new Scanner ( Sys t em. i n) ; Sys t em. out . pr i nt ( "Ent er a numer i c gr ade ( -1 t o qui t ) : ") ; numer i cGr ade = i nput . next I nt ( ) ; whi l e ( numer i cGr ade ! = FLAG) { i f ( i sVal i dNumber ( numer i cGr ade, mi nVal ue, maxVal ue)) { l et t er Gr ade = get Let t er Gr ade( numer i cGr ade) ; Sys t em. out . pr i nt l n( "The gr ade " + numer i cGr ade + " i s a( n) " + l et t er Gr ade + ".") ; } el s e { Sys t em. out . pr i nt l n( "Gr ade ent er ed i s not val i d.") ; } Sys t em. out . pr i nt ( "Ent er a numer i c gr ade ( -1 t o qui t ) : ") ; numer i cGr ade = i nput . next I nt ( ) ; } } }

The GradeConverter application produces output sim ilar to:

GradeConverter Testing and Debugging

Testing done at th is point shou ld test the logic in main () because the other methods have already been verified. The logic in main() is simple. Therefore, testing need only include verifying that the loop control vari-able is working as expected, the user is able to enter grades as expected, and that letter grades are retu rned for values entered by the user in the range 0 though 100.

Review : GradeConver t erMod ify the GradeConverter Case Study to d isplay an A+ for a grade of 100, a B+ for a grade of 89, a C+ for a grade of 79, and a D+ for a grade of 69.

Chapter Summary

Th is chap ter introduced a new level of software development that included w riting methods to perform tasks. In the software development process, top-down development is a problem-solving approach that breaks a task dow n into smaller subtasks and then further into units. Implementing these tasks w ith methods is called procedural abstraction.

Page 16: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

Method s are executed in a statement by includ ing the method name followed by parentheses. A statement that executes a method is said to call the method. When a method requ ires data to perform its tasks, the data is included inside the parentheses in the method call. A method that retu rns data must be called from an assignment statement or from inside an expression.

A method includes a declaration and a body. The method declaration includes the access level, retu rn type, if any, method name, and param-eters for receiving data, if necessary. The access level of a method can be declared publ i c, which means that the method can be called from a statement in any other method. The keyword publ i c is called an access modifier. A method declaration that includes the keyword s t at i c is a class method, which can be called from the class itself.

The retu rn type of a method declares what type of value w ill be given back to the calling statement. The retu rn type voi d ind icates that the method will not retu rn a value at all. Retu rn types can be primitive types, such as i nt and doubl e, or abstract data types, such as String. Methods that retu rn a value must include a r et ur n statement in the method body.

A method can have multiple parameters. Arguments in a method call must be passed to a method in the same order as the parameter declara-tions. Method s w ith the same name, but w ith d ifferent parameters are said to be overloaded. The compiler determ ines which method to call by the types, order, and number of parameters in overloaded methods.

Prim itive argu ments are passed by value, which means that the data stored in the argu ment is passed, not a reference to the argu ment loca-tion. A method can only use the argument values in the task it performs. A method cannot change the data stored in an argu ment.

The body of a method can include variable, constant, and object decla-rations. These declarations are said to be local because they have a scope that extends just from the declaration to the end of the method body.

Carefu l docu mentation is important for the reader of a program to u nderstand a method. Method documentation is enclosed by / ** */ and includes a brief description of the method, a precond ition, and a postcon-d ition. Every method must have a postcond ition, but not every method requ ires a precond ition.

Code conventions introduced in th is chapter are:

• Method names shou ld ind icate an action and begin w ith a lower-case letter and then an uppercase letter shou ld begin each word w ith in the name.

• Method docu mentation shou ld be enclosed in / ** */ com ment blocks.

• Method docu mentation shou ld include a brief description of the task the method performs, a precond ition, and a postcond ition.

Page 17: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

Vocabulary

Access level The part of a method declaration that determ ines if the method can be called by other classes.

Access mod if ier A keyword in the declarat ion of a method that determ ines the access level of a method.

Argu m en t The va lu e or var iable p assed to a method.

Call A statement that contains a method name followed by parentheses.

Bou ndary value A value that lies just inside or ju st outside the range of valid values.

Class method A method that can be called from the class itself.

Local Variables, constants, and objects that are declared within a method and therefore have a scope lim ited to that method.

Method b ody The statements that implement a method.

Method declarat ion The first line of a method, which contains the method name, access level, retu rn type, and parameters, if any.

Method overload ing Writing more than one method of the same name in a class.

Method parameters The part of a method declara-tion that accepts values from the method call.

Pass Giving data to a method by enclosing the data in parentheses in the method call.

Pass by value Passing the value of an argument to a method. The type of data passed depends on whether the argument is a prim itive or an object.

Precond ition The part of a method’s documentation that states the assumptions, or in itial requ irements, of the method. Also called pre.

Procedu ral abstraction Breaking a task dow n into methods.

Postcond ition The part of a method’s docu menta-tion that states what must be true after the method has been executed. Also called post.

Top -d ow n d evelop m en t A p roblem -solv ing approach where a task is broken dow n into subtasks and then the subtasks are reduced to yet simpler tasks.

Visibility The access level of a method.

Java

/ ** */ Used to enclose docu mentation com ments for a method.

publ i c An access mod ifier used in the declaration of a method to ind icate that the method is visible to any other class.

s t at i c A keyword used in the declaration of a method to ind icate that the method is a class method.

voi d A keyword used in the declaration of a method to ind icate that the method w ill not retu rn a value.

r et ur n Statement used to send a value from a method back to the calling statement.

Page 18: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

Crit ical Thinking

1. Use top -dow n d evelopm ent and p rocedu ral abstraction to w rite pseudocode for the follow-ing specification:

The Pizza ap plicat ion a llow s the u ser to choose to d isplay the instructions for mak-ing a pizza in either English or Spanish.

2. Explain the d ifference between method declara-tion and method body.

3. What type of keyword is u sed to change the access level of a method?

4. What is another word used for describing the access level of a method?

5. Explain the scope of each of the variables in the code below:

publ i c cl as s ScopeExampl e { publ i c s t at i c voi d mai n( St r i ng[ ] ar gs ) { i nt var 1; f or ( i nt var 2 = 0; var 2 < 5; var 2++) { met hod1( ) ; } }

publ i c s t at i c voi d met hod1( ) { i nt var 3; f or ( i nt var 4 = 0; var 4 < 2; var 4++) { var 3 += 1; } } }

6. Write a method declaration for each of the fol-low ing descriptions:

a) A class method named getVowels that can be called by any other method, requires a String parameter, and retu rns an integer value.

b) A class method named extractDigit that can be called by any other method, requ ires an integer parameter, and retu rns an integer value.

c) A class method named insertString that can be called by any other method, requ ires a String parameter and an integer parameter, and retu rns a String parameter.

7. a) H ow d oes the com piler d ist ingu ish one method from another?

b) Can two methods in the same class have the same name? Explain.

8. a) What is the r et ur n statement u sed for? b) How m any values can a r et ur n statement

send back to the calling statement? c) How is the declaration of a method retu rn-

ing a value d ifferent from the declaration of a method that does not retu rn a value?

9. Find and explain the error in the code below:

publ i c cl as s Met hodCal l Exampl e { publ i c s t at i c voi d mai n( St r i ng[ ] ar gs ) { i nt num; doSomet hi ng( ) ; num = doSomet hi ng( ) ; }

publ i c s t at i c i nt doSomet hi ng( ) { r et ur n( 5) ; } }

10. a) What type of com ments shou ld be used for describing a method?

b) What three th ings shou ld the com ments for a method describe?

True/ False

11. Determ ine if each of the follow ing are true or false. If false, explain why.

a) Breaking a task dow n into methods is called procedural abstraction.

b) A method call consists of the method decla-ration in an assignment statement.

c) A void method must retu rn a value. d) An access mod ifier declares the retu rn type

of a method. e) The keyword s t at i c declares a method is a

class method. f) Method parameters are enclosed by braces

({}). g) Local variables can be used by any method

in a class. h) The value of an argument passed to a method

can be changed in an assignment statement in the method.

i) Method overload ing means that an applica-tion contains more than 10 methods.

j) The r et ur n statement is u sed to send a value back to the calling statement.

k) The precond ition of a method states the data types of the method’s parameters.

l) The postcondition of a method describes the way the method accomplishes its task.

Page 19: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

Exercises

Exercise 1 ——————————————————————— HouseCreate a Hou se application that calls method s add Roof(), addBase(), and addWalk() to d isplay the follow ing:

Exercise 2 ————————————————— MetricConve rsionThe follow ing formulas can be used to convert English u nits of measu rements to metric u nits:

inches * 2.54 = centimeters

feet * 30 = centimeters

yards * 0.91 = meters

m iles * 1.6 = kilometers

Create a MetricConversion application that d isplays a menu of conversion choices and then prompts the user to choose a conversion. Conversion choices shou ld include inches to centimeters, feet to cen-timeters, yards to meters, m iles to kilometers, and vice versa. The application shou ld include separate methods for doing each of the conversions. Application output shou ld look sim ilar to:

Exercise 3 ö —————————————————— Prime Numb e rMod ify the PrimeNu mber application created in Chapter 6 Exercise 1 to include a method named isPrime(). The isPrime() method shou ld requ ire one parameter and retu rn a Boolean value.

Page 20: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

Exercise 4 ———————————————————— IsoTriangleCreate an IsoTriangle application that prompts the user for the size of an isosceles triangle and then d isplays the triangle w ith that many lines. The IsoTriangle application code shou ld include:

• the d rawBar() method from the chapter.

• An addSpaces() method which “prints” spaces.

Application output shou ld look sim ilar to:

Exercise 5 ————————————————————— Add CoinsCreate an AddCoins application that prompts the u ser for the nu mber of penn ies, n ickels, d imes, and quarters, and then d isplays their total dollar amou nt. The AddCoins application shou ld include a getDollarAmou nt() method that has fou r int parameters correspond ing to the nu mber of pennies, n ickels, d imes, and quarters, and retu rns a String that correspond s to the dollar value of the coins. Note that the String retu rned shou ld include the cu rrency sign ($). Application output shou ld look sim ilar to:

Exercise 6 ————————————————— Pythagore anTrip leCreate a PythagoreanTriple application that d isplays all pythagorean triples w ith values of A and B less than 100. A pythagorean triple is a set of three integers that make the equation a2 + b2 = c2 true. The application shou ld include a PerfectSquare() method that uses the solution from the PerfectSquare review in Chapter 6. (H int: You w ill need to generate all possible combinations of A and B and d isplay just those that work.)

Page 21: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

Exercise 7 ———————————————————Pe rfe ctInte ge rsCreate a PerfectIntegers application that d isplays all perfect integers up to 100. A perfect integer is a nu mber which is equal to the su m of all its factors except itself. For example, 6 is a perfect nu mber because 1 + 2 + 3 = 6. The application shou ld include a bool ean method isPerfect().

Exercise 8 ————————————————————————HiLoa) In the Hi-Lo game, the player begins with a score of 1000. The player is prompted for the

nu mber of points to risk and a second prompt asks the player to choose either H igh or Low. The player’s choice of either High or Low is compared to random number between 1 and 13, inclusive. If the number is between 1 and 6 inclusive, then it is considered “low”. A number between 8 and 13 inclusive is “h igh”. The nu mber 7 is neither h igh nor low, and the player loses the points at r isk. If the player had guessed correctly, the points at risk are doubled and added to the total points. For a w rong choice, the player loses the points at risk. Create a H iLo application based on this specification. Application output shou ld look sim ilar to:

b) Mod ify the application to allow the player to continue u ntil there are 0 points left. At the end of the game, d isplay the number of guesses the user took before ru nning out of points.

Page 22: Chapter 7 Methods - cdn-cms.f-static.com fileinto the first level of subtasks: 1. Determine the type of conversion to be done. 2. Convert the temperature using the appropriate formula

Chapter 7 Methods

Exercise 9 ———————————————————————— NimThe game of Nim starts w ith a random nu mber of stones between 15 and 30. Two players alternate tu rns and on each tu rn may take either 1, 2, or 3 stones from the pile. The player forced to take the last stone loses. Create a Nim application that allows the user to play against the computer. In th is version of the game, the application generates the nu mber of stones to begin w ith, the nu mber of stones the computer takes, and the user goes first. The Nim application code shou ld :

• prevent the u ser and the computer from taking an illegal nu mber of stones. For example, neither shou ld be allowed to take three stones when there are only 1 or 2 left.

• include an isValidEntry() method to check user input.

• include a d rawStones() method that generates a random number from 1 to 3 for the number of stones the computer d raws.

• include separate methods to hand le the user’s tu rn and the computer’s tu rn.

Application output shou ld look sim ilar to that show n on the next page:

Exercise 10 ö ————————————————— Gue ssing GameThe GuessingGame application mod ified in Chapter 6 Exercise 8 shou ld include a separate method for d isplaying a h int to the user. Mod ify the GuessingGame application as follows:

a) Mod ify the algorithm to include a call to a method named giveH int(), which d isplays a h int, but does not retu rn a value.

b) Mod ify the flowchart based on the algorithm mod ifications.

c) Mod ify the GuessingGame code. Application output shou ld look sim ilar to: