0% found this document useful (0 votes)
60 views

Chapter 07

This document discusses object-oriented programming concepts like classes, methods, and top-down development. It provides an example of how to break down a temperature conversion program into methods using top-down design. The temperature conversion program is broken into a main method and two additional methods to convert between Fahrenheit and Celsius. The methods are then implemented in code with declarations that specify the access level, return type, name, and parameters. When called in the main method, the additional methods perform the temperature conversions.

Uploaded by

aclivis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Chapter 07

This document discusses object-oriented programming concepts like classes, methods, and top-down development. It provides an example of how to break down a temperature conversion program into methods using top-down design. The temperature conversion program is broken into a main method and two additional methods to convert between Fahrenheit and Celsius. The methods are then implemented in code with declarations that specify the access level, return type, name, and parameters. When called in the main method, the additional methods perform the temperature conversions.

Uploaded by

aclivis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Methods

\-, bject-orientedprograms use classeswith methods to perform


tasks.A program often performs severaltasks,eachwith its own level of
complexity. To manage these taskt they are broken down into methods.
This chapter discussestop-down program developmentand writing and
documenting methods.

The solution to a task can be developedby breaking the task down into
TIP Top-downdevelopmenr
smaller subtasks.Thesesubtaskscan then be reduced to yet simpler tasks.
is alsocalledtop-downdesign
or step-wiserefinement. This processcanbe continueduntil the original task is broken down into
units that each describe a specific goal. As the task is broken down into
smaller subtasksand then further into units, more detail for achieving the
specificgoal is added.This problem-solvingapproachdescribesa software
top-down development developmentprocesscalled top-down deaelopment.
In top-down development,the first level of subtaskstranslatesinto the
main0 method. Levels of tasks below mainQ are developed into a series
procedural abstraction of additional methods. Using methods to define tasks is called procedural
abstraction.
For example,considerthe following program specification:
TempConverterallows the user to convert a temperature from
either Fahrenheit to Celsius or Celsius to Fahrenheit.
The algorithm for this application breaks the program specificationdown
into the first level of subtasks:
1. Determine the type of conversionto 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.

Chapter7 Methods

: -v
I
Top-down development and procedural abstraction were used to break
the program specification down into levels of subtasks,as shown on the
previous page, Outlining the levels of subtasksin pseudocodedefines a
mainQ method and two other rnethods:
main ( )
Pronrpt the user for the conversion type.
Execute the appropriate methoil to convelt the ternperature.

fahreaheitToCelsius ()
Prompt the user for a tenperature in ilegrees Fahrenheit
Convert the temperature to clegrees Celsius
Display the temperature

celsiusToFahrenheit ()
Prompt the user for
a temperature in clegrees Celsius
Convert the temperature to tlegrees Fahrenheit
Display the temperature

The TempConverter application implements the pseudocode above:

import java. util. Scanner;

public class TernpConverter {

public static
voicl fahrenheitToCelsius 0 {
double fTernp, cTenp;
Scanner input = new Scanner(System.in);

Systen.out.priat("Enter a Fahrenheit temperature: ");


fTemp = input.nextDouble0;
input. close ( );

cTemp = (double)S/(double)9*(fTemp - 32);


System.out.println("The Celsius temperature is " + cTemp);
]
public static voiil celsiusToFahrenheit0 {
clouble cTemp, fTemp;
Scanner input = new Scanner(System.in);

ods mustbe partof System.out.print("Enter a Celsius tenperature: ");


cTemp = input.nextDouble 0;
input. close 0;

fTemp = (tlouble)9/(clouble)S*cTemp + 32;


System.out.priatln("The Fahreaheit temperature is
+ fTernp);
l

public statj-c voicl main(Stringl] args) {


int choice;
Scanner input = new Scanner(System.in);

/* Prompt user for type of conversion */


System.out.println("1-. Fahrenheit to Celsius conversion. " );
Systen.out.println("2. Celsius to Fahrenheit conversion. " );
System.out.print("Enter your choice: ");
choice = input.nextlnt0 ;
if (choice == 1) t
fahrenheitToCelsius ();
] else {
celsiusToFahrenheit. ();
]
fI 4-P^ u
, ,sr , ^1 ^-^
erusE
/\ .
\, ,
1

Chapter7 Methads
call The TempConvertercontrolling classcontains two methods as well
as a main0 method. The methods are executedwhen they are called.A
method callconsistsof the method name followed by parentheses.The tr
statementin the main0 method on the previous pagecontainstwo method
calls, fahrenheitToCelsius ( ) and celsiusToFahrenheit 0.

TempConverter
producesoutput similar to:

1. Fahrenheitto Celsius conuersion.


2. Celsius to Fahrenheit conuersion.
Enter gour choice: 1
Enter a Fahrenheit temperaturer 32
T h e C e l s i u s t e m p e r a t u F ei s 0 . 0

In this run of the application,the user enteredr and thereforethe


fahrenheitToCelsius0 methodwascalled.

method declaratian A method consistsof a declarationand a body. The methoddeclaration


includesaccesslevel,return type, name,and parameters,if any.Themethod
method bodv bodycontainsthe statementsthat implement the method. A method takes
the form:
<access _ level> <return _ type> < n a m e >( < p a r a m e t e r s > ) {
<sCatements>
]
For example, consider the fahrenheitToCelsius0 method from the
TempConverterapplication:
public static void fahrenheitToCelsj-us0 {
double fTemp, cTernp;
Scanner input = new Scanner(System.in);

System.out.print("Enter a Fahrenheit temperature: ");


fTemP = inPut nextDouble 0;
input. close 0 ;

cTemp= (double)5/(double)9*(fTemp - 32);


System.out.println("The Celsius temperature is + cTemp)
]
The method aboveis a classmethod with accesslevel public, return
accesslevel type voiil, name fahrenheitToCelsius,and no parameters.The accessleael
of a method determinesif other classescan call the method.The keyword
accessmodifier public is an accessmodifier.A public method can be called by any other
visibility method.The accesslevelof a method can alsobe thought of asits uisibility.
Accesslevels are discussedfurther in Chapter 8.

classmethod The keyword sraric declaresthe method a classmethod.A classmethod


canbe called from the classitself. Methods that are not classmethods must
be called from an instantiatedobjectof that class.

void The return type void means that the method will not return a value,
and parametersare specifiedwhen a method needsvaluesto perform its
task. The body of the method starts with the first opening brace (t) and
endswith the closingbrace(t).

Chapter7 Methods
naming conventions Method names should indicate an action. Verbs make good method
names.A method name should also begin with a lowercaseletter and
then an uppercaseletter should begin eachword within the name.Method
names may not contain spaces.

local scope Methods can also havetheir own set of variables,constants,and objects.
Variablg constant and object declarations in the body of a method have
a scopethat extends from the declaration to the end of the method
body. Thesevariables,constants,and objectsare said tobe localto the
method becausetheir scopeis limited to that method. For example,the
fahrenheitToCelsius0method containslocal variablesfTempand cTenpand
a local object named input.

Createa TimeConverter application that allows the user to chooseamong converting hours to minutes, days
to hours,minutes to hours,or hours to days.Use methodsas appropriate.

A method declarationcan include methodparameters,which acceptvalues


from the method call. The data passedto the method can then be used
terms "parameter" inside the method to perform its task.For example,the drawBar0 method
ment"areoftenused
includesdn inr parameternamed lensth:
synonymously.
public static voicl drawBar(int length) {

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


S Y s t e m .o u t . p r i n t ( " * " ) ;
]
System. out. println () ;
]
passingdata Data is givery ot passed,
to a method by enclosingthe data in parentheses
in the method call. The value or variable passedto a method is called the
argument argument.For example,the RightTriangleapplication makes six calls to
drawBarQ.Eachcall passesa different variableargument:
public class RightTriangle {
-.+ir:-..,-
'flff),ffi
t"rr "formal
parame- public static voiil drawBar(int length) {
ter'o?9sometimes usedto refer
to a parameterin the method for (i-nt i = 1; i <= length; i++) {
d e c l a r a t i o na, n d t h e t e r m System. out. print ( "*" ) ;
"actualparameter"is usedto ]
System. out. printfn () ;
r e f e rt o t h e a r g u m e n tb e i n g
passedto the method. ]

public static voiil nain(String[] args) {

/* draw a right triangle with base si.ze 6 */


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

Chapter7 Methods
The RightTriangle application produces the output:

*
*x

xxx'-
xxxxx
xxxxxx

passby value In Java,arguments arc passedby aalue,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 argument that is an object gives the
method a copy of its referencethat points to methodsfor changing object
data.Therefore,a method can changethe data storedin an objectbecause
it has accessto the object'smethods, but it cannot change the data stored
in a primitive variable becausethe method does not have accessto the
actual location of the primitive data.
multiple parameters When a method declaration includes more than one parameter, the
parametersare separatedby commas,For example,a modified drawBar0
has an inr parameterfor the length of the bar and a String parameterfor
the characterto use to draw the bar:

TIP Passing an argumentof a public static voiil ilrawBar(int length, String mark) {
typethat is not expectedby a
for (int i = 1; i <= length; i++) {
methodgenerates theexception
S y s t e m .o u t . p r i n t (mark) ;
IIlegalArgu
mentException.
]
S y s t e m .o u t . p r i n t l n ();
]
A call to the modified drawBar0 method includes two arguments sepa-
ratedby commas:
drawBar(6, "$");

This call producesthe following output:

$$$ss$
The order of the argumentsin a method call is important becausethe
first argumentcorrespondsto the first parameterin the method declara-
tion, the secondargument correspondsto the secondparameter,and so
on. Note that argument namesdo not necessarilymatch parameternames.
Descriptivevariablenamesshould be used throughout a program without
regard to matching parameter names in a method declaration.

Createa SpanishNumbersapplication that displays numbers 1 through 10in Spanish.A method with an :-nt
parameter should display the Spanish word for the number passed.A loop structure in the main0 method
should be used to call the method ten times. The Spanishword equivalents for numbers 1 through 10 are:
1 uno 6 seis
2 dos 7 siete
3 tres B ocho
4 cuatro 9 nueve
5 cinco I0 diez

Chapter7 Methods
Createa DisplayBox application that prompts the user for a height and width and then displays a box of that
size. The DisplayBox application should include a method named drawBox0 that has two parametersand
makescalls to the drawBarOmethod.

The method declarationis used by the compiler to determine which


method to execute.Therefore,method names do not have to be unique
as long as the parametersare different for methodswith the samename.
Methodoaerloading is when more than one method of the samename is
included in a class.For example,the following applicationcontainstwo
drawBar0 methods:
public class MethodOverloadingExample {

public static void drawBar(int length) {

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


S y s t e m .o u t . p r i n t ("*" );
]
System. out. println () ;
]
public static void drawBar(int length, String mark) {

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


System. out. print (mark) ;
]
S.'oro- ^, r -r ,f . n?i nf I1 \ J;
f------n

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

drawBar(10);
drawBar(5,"@");
]
]
The MethodOverloadingapplicationproducesthe output:
*xx}{*xxxxx
BGEECI

Note that the first call in main0 executesthe drawBar0 method containing
only one parameter.The secondcall executesthe drawBar0 method that
containstwo parameters.The compilerusesthe types,order,and number
of parametersto determinewhich method to execute.

Chapter7 Methods
Modify the DrawBox application to ask the user if a specific character should be used for the display. For
example/the prompt could be "Do you want to entera characterto use to display the box?(entery for yes):"
If the user types v, then prompt the user for the character.Otherwise, the default character should be used.
The modified application should contain overloadeddrawBoxQ and drawBarQ methods.

A method can return a value.For example,the cubeOfQmethod returns


the cube of its parameter:
public static double cube0f(double x) {
TIP rhe returntypes of ilouble xCubecl;
m e t h o d sc a n n o tb e u s e dt o
d i s t i n g u i sohn e m e t h o df r o m xCubed=x*x*x;
anotherfor overloading. return (xCubecl);
]
The return statementis used to send a value back to the calling statement.
A rerurn statementcan return only one value,
A method that returns a value must include the return type in the
method declaration,For example,the cubeOf0 method declaration
declaresa return type double.Return types can be primitive types, such
as inr/ double,and boolean,or abstracttypes, such as the String class.The
return type void is used when there will be no return value. A method
declaredds void doesnot contain a rerurn statement.
A method that returns a value is called from a statement that will
make use of the returned value,such as an expressionor an assignment
statement.For example,the following application calls cubeOfQ from an
assignmentstatement:
public class CubeCalculator {

public static double cubeOf(double x) {


double xCubecl;

xCubed=x*x*x;
ret.urn (xCubed) ;

]
public static void main(String[J args) {
double nun = 2.0:
double cube;

cube = cubeOf(nurn);
System. out. println (cube ) ;
]
]
The CubeCalculatorapplication produces the following output:

8.0

Chapter7 Methods
Createan Exponentiation application that prompts the user for two numbers and then displays the first num-
ber raised to the power of the secondnumber. The application should include a method named powerOf0
that returns its first parameterraised to the power of its secondparameter.

Methods should be carefully commentedso that a readerof the program


understands what task the method is performing and what data, if any,
will be returned by the method. Method documentationis in the form of
documentationcomments(7** */) that appearjust abovethe method
declaration.For example,the drawBar0 method with documentation:
/**
* Print a bar of asterisks across the screen.
* pre: length > 0
* post: Bar drawn of length characters, insertion
* point rnoved to next 1ine.

public static void drawBar(int length) {

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


S y s t e m .o u t . p r i n t ( " * " ) ;
]
System. out. println ();
]
The assumptions,or initial requirements,of a method are statedin the
precondition documentationin a sectioncalled the precondition, or just pre. Note that
the pre for drawBar0 statesthat lensth must be greaterthan O but not that
lensrh must be ofl inr. Information that the compiler will verify, such as
data types,should not be statedin method documentation.
postcondition Thepostconditionsectionof the documentation,or posr,stateswhat must
be true after the method has been executed.However, the post should not
statehow the method accomplishedits task.
A method may not have a precondition, but every method must
have a postcondition.For example/below is the cubeOf0 method with
documentation:

* Calculates the cube of a number.


* pre: none
* nost' x errhed retrrrned

public static double cubeOf(double x) {


double xCubeil;

xCubed=x*x*x;
?af ,,Tr f *C"L..1 ) '

Chapter7 Methods
To summarize, the guidelines for writing pre and post conditions are:
. The precondition stateswhat must be true at the beginning of a
method for the method to work properly.
. The postcondition stateswhat must be true after the method has
executedif the method has worked properly.
o Preconditions and postconditions should not state facts that the
compiler will verify. They should also not refer to variables or
information outside the method.
o The postcondition should not statehow the method accomplished
its task.

Modify each of the Reviews in this chapter so that the methods are properly documented.

This casestudy will focus on top-down developmentand procedural


abstraction.Testing and debugging methods in isolation will also be
demonstrated.
An applicationfor generatinga letter gradebasedon a numeric grade
will be created.The GradeConverterapplication allows the user to enter
a numeric grade and then a letter grade is displayed. The user may then
chooseto enteranothergradeor quit.

GradeConverterSpecification
The GradeConverterapplication prompts the user for a numeric grade in
the range 0 to L00or a -1 to end the application. When a valid numeric
gradeis entered,the correspondingletter gradeis then displayed.Grades
from 90 to 100are an A, gradesfrom 80 to 89 are a B, grades from7} to79
are a C, gradesfrom 60 to 69 are a D and gradesbelow 60 are an F. After
displaying the corresponding letter grade, the user is prompted to enter
anotherletter gradeor can chooseto quit the application.
The GradeConverterinterface should include a prompt asking for the
numeric grade. The prompt should give the option of quitting the appli-
cation. After displaying the letter grade, the user should be prompted to
enter another numeric grade or quit the application.
The GradeConverteroutput sketch:

EnIer a numericqrade(-1Io quit):BB


TheqradeBB ie a(n) D.
EnNera numericqrade(-1to quiN):90
Theqrade90 io a(n) A.
EnIer a numeric6rade(-1to quil):-1

Chapter7 Methods
The GradeConverteralgorithm:
1. Prompt the user for a number'
2. Determine the letter grade that correspondsto the entered
numeric grade and display the result'
3. Repeatsteps 1 and 2 until the user choosesto quit'

The GradeConverterflowchart:

Delermineand
dioVlayletNer6rade

GradeConverterCode Design
further
Using the top-down development approach, the algorithm is
refined:
Step1 of the algorithm can be broken down further:
1a. Display a prompt that givesthe user the option to quit'
Checkthatthenumberenteredisvalid.Itshouldcorrespondto
eitherasentinelvaluethatindicatestheuserwantstoquitora
number in the range 0 through 100'

Step 2 of the algorithm can be broken down further:


70
2a, Determine if the numeric grade is between 90 to ].00,80 to 89,
to79,50to 69,or 0 to 59.
Assign the letter A to a grade from 90 to 100 a letter B to a grade
fromg0toSg,theletterCtoagradefromT0toTg,theletterDto
a grade from 50 to 69,and the letter F to a grade from 0 to 59'

Chapter7 Methods
Using the flowcharf algorithm, and procedural abstraction, the pseudo-
code for the GradeConverter application can be created. The code will
include a loop structure to get the user's input and two additional methods.
One method will determine if the input is valid and another determines
which letter corresponds to the numeric grade:
main ( )
Promnt t-he rrser for a number
while (number != -l-) {
if (isvalidNumber(number)) {
g e t L e t t e r G r a d e (n u m b e r )
Display message with letter grade
]
Pronpt the user for a number
l

isValidNumber(userNum, maxNum. ninNum)


if (minNum <= userNum <= maxNum) {
return (true);
] -1 .. {
return(false);
]
g e t L e t t e r G r a d e (n u m e r i c G r a d e )
if (numericGrade < 60) {
return ("F");
] else if (numericGrade < 70) {
return {"D");
] else if (numericGrade < B0) {
return ("C");
] else if (nunericGrade < 90) i
return ("B");
] else {
return ( " A ") ;
]

GradeConverterImplementation

Testingmethods in isolation is important to ensure that the program


as a whole will run without error. When testing a method, statementsin
main$ should call the method using testdata.The main0 method should
not call any other method or Perform any other task excepttest the current
method.
Rather than writing codefor the entire aPPlicationat once/one method
at a time will be addedand then tested.When testingthe methodsis com-
plete,the mainQ method willbe rewritten to imPlementthe CradeConverter
Dseudocode,

Chapter7 Methods 3
The isValidNumber0 method is the first method written and tested:
public class GracleConverter {

* Determines if a numeric entry is valiil.


* pre: none
* post: true return if rninNum <= userNum <= maxNum:
* false returneil otherwise

public static boolean isValiclNumber(int userNum, int minNum, int maxNum) {


if (minNum <= userNum && userNum <= naxNum) {
return (true);
] else {
return (false ) ;
]
]
public static voiil main(string[] args) {
final intrninValue = 0:
final int maxValue = 100;
int numeri-cGraile;

numericGraile = 0;
if (isValidNunber(numericGrade, minValue, maxValue)) {
System.out.println(numericGracle + " is valid.");
] else {
System.out.println(nurnericGraile + " is NOT va1iil.,');
]

numericGrade = L00;
if (isvalidNumber(numericGrade, minValue, maxValue)) {
System.out.println(numericGrade + " is valicl.,,);
] else {
Systern.out.println(numericGracle + " is NOT vaIicl.,,);
]

numericGrad.e = -1;
if (isvalidNumber(nurnericGrade, minValue, maxValue)) {
System.out.println(numericGracle + " is valid.");
) else {
System.out.println(numericGraiie + " is NOT valicl.,');
]

numericGrade = 101;
if (isValiilNumber(numericGrade, minValue, maxValue)) {
System.out.prj-nt1n(numericGrade + " is va1id.,,);
] else {
Systern.out.println(numericGratle + " is NOT valicl.");
]
1

The statementsin mainQ test the isValidNumber0 method with data


boundary value that includesboundary values.Aboundaryaalueis data that is just inside
or just outsidethe range of valid values.For example,the value 100lies just
inside the high end of the range of valid grades.Testing the method with
this data verifies that the <=operator was used rather than the < operator.
The GradeConverterapplication produces the following output:

0 is uatid.
100 is ualid.
- l i s N O Tu a l i d .
t 0 l i s N O Tu a l i d .

Chapter7 Methods
Next, the getletterGradeQ method is added and the main0 statements
are changed to test that method:
public class GradeConverter {

* Determines if a numeric entrv is valicl.


x pre: noD.e
* post: true has been returnecl if minNum <= userNum <= maxNum;
* false has been returned otherwise

public static boolean isValiclNumber(int userNum, int minNurn, iat naxNurn) {


if (minNum <= userNum && userNum <= maxNum) {
return (true);
] else {
return(fa1se);
]
)

* Determines the letter gracle that corresponils to the numeric gracle.


* pre: 0 <= numGraile <= 100
* nosf: Tle ]et-t-er orade A. B. C D or F has been returneil.

public static String getletterGracle(int numGracle) {


if (numGracle < 60) {
return ( "F" );
] else if (numGracle < 70) {
return("D");
i else if (nurnGrade < 80) {
return ( "C");
] else if (numGraile < 90) {
return ( "B" );
] else {
returu ( "A");
i
]
public static voicl rnain(String[] args) {
int numericGracle;

numericGracle = 90;
System.out.println(numericGrade + " is " + getletterGrade(numericGrade));
numericGrade = 89;
Systern.out.println(numericGracle+"is"+getletterGracle(numericGracle));
numericGracle = 80;
System.out.println(numericGratle+"is"+getletterGracle(numericGracle));
numericGracle = 79;
System.out.println(numericGraile+"is"+getletterGraile(numericGrade));
numericGrade = 70;
System.out.println(nunericGraile+"is"+getletterGraile(numericGracle));
nurnericGracle = 69;
System.out.println(numerj-cGracle+"is"+getletterGratle(numericGracle));
numericGracls = 60;
System.out.println(nurnericGraile+"is"+getletterGracle(numericGraile));
numericGracle = 59:
Syst.em.out.println(nunerj-cGrade+"is"+getletterGraile(numericGrade));
]

7 Methods re
chapter
Boundaryvaluesfor getletterGrade0are testedwith statements
in
main0.RunningCradeConverter displaystheoutput:
90isA
89isB
80isB
79isC
70isC
69is0
60isD
59isF

After verifying that the methodsare working as expected,the final


GradeConverter application can be completed:

* G-^,1-C^--.rf6? E r . J iqr v\ rd:

q^-,
imnnrts i-,,- ,,f i l - - *iner;

* Display the letter grade that corresponds to the nurneric


* nradc crt-crci h- the user,

public class GradeConverter {

* Determines if a nrrmeric enfTv is valid.


* pre: none
* post: true has been returned if ninNum <= userNum <= maxNum;
* false has been returned. otherwise

public static boolean isValidNunber(int userNum, int ninNun, int maxNum) {


if (minNun <= userNum && userNum <= maxNum) {
return (true ) ;
] else {
return (false ) ;
]
l
* Determines the letter grade that corresponds to the numeric grade.
* pre: 0 <= nuncrade <= 100
* nosl-: The let-l-cr arade A P C D or F has been returned.

public static String getletterGrade(int numGrade) {


if (numGrade < 60) {
return ("F" );
] e l s e if (numGrade < 70){
r e t u r n ( " D ' ') ;
] else if (numGrade < 80) t
return("C");
] else lf (numGrade < 90) {
return ("B");
] else {
r e t u r n ( " A ") ;
]
]

T Chapter7 Methods
public static void main(String[] args) {
fi-na1 FLAG = -1;
int
final minValue = 0;
int
final i-nt naxVa]ue = 100;
i-nE nunericGrade;
St-i.^ 1 attarGrai-

Scanner input = new Scanner(Systen.in);

System.out.print("Enter a numeric gracle (-1 to quit): ");


numericcrade = input.nextlnt0;
while (numericGrade != FLAG) i
if (isValidNumber(numericGracle, minValue, rnaxValue)) {
LetterGrade = getletterGracle (numericGracle);
System.out.println("The graale " + numericGraile + " is a(n)
letterGracle + "."):
] else {
System.out.println("Grade entered. is not valid.");
]
System.out.print("Enter a numeric grade (-1- to quj-t): ");
numericGrade = input.nextfnt0 ;
]
1
J

The GradeConverterapplicationproducesoutput similar to:

E n t e r a n u m e r i ca r a d e ( - l t o Q u i t ) : 88
The grade 88 is a(n) B.
Enter a numeric arade (-l t o q u i t ) : 90
The grade 90 is a(n) A.
E n t e r a n u m e r i ca r a d e ( - l to {uit): -l

GradeConverterTesting and Debugging


Testingdone at this point should test the logic in main0 becausethe
other methodshave alreadybeen verified. The logic in main0 is simple.
Therefore,testing need only include verifying that the loop control vari-
ableis working as expected,the user is able to enter gradesas expected,
and that letter gradesare returned for valuesenteredby the user in the
range 0 though 100.

Modify the GradeConverterCaseStudy to display 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 59.

This chapter introduced a new level of software development that


included writing methods to perform tasks.In the software development
process/top-down developmentis a problem-solvingapproachthat breaksa
task down into smaller subtasksand then further into units, Implementing
thesetaskswith methodsis calledproceduralabstraction.

Chapter7 Methods
Methods are executed in a statement by including the method name
followed by parentheses. A statement that executes a method is said to
call the method. When a method requires data to perform its tasks, the
data is included inside the parentheses in the method call. A method that
returns 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 accesslevel, return type if any, method name, and param-
eters for receiving data, if necessary. The access level of a method can
be declared public, which means that the method can be called from a
statement in any other method. The keyword public is called an access
modifier. A method declaration that includes the keyword static is a class
method, which can be called from the class itself.

The return type of a method declares what type of value will be given
back to the calling statement. The return type void indicates that the
method will not return a value at all. Return types can be primitive types,
such as inr ?nd clouble,or abstract data types, such as String. Methods that
return a value must include a rerurn 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. Methods with the same name, but with different parameters are
said to be overloaded. The compiler determines which method to call by
the types, order, and number of parameters in overloaded methods.

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

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.

Careful documentation is important for the reader of a program to


understand a method. Method documentation is enclosedby /** */ and
includes a brief description of the method, a precondition, and a postcon-
dition. Every method must have a postcondition, but not every method
requires a precondition.

Code conventions introduced in this chapter are:

. Method names should indicate an action and begin with a lower-


case letter and then an uppercase letter should begin each word
within the name.
o Method documentation should be enclosed in /** */ comment
blocks.
. Method documentation should include a brief description of the
task the method performs, a precondition, and a postcondition.

Chapter7 Methods
r

Access level The part of a method declaration that Method overloading Writingmorethanonemethod
determines if the method can be called by other of the samename in a class.
classes.
Method parameters The part of a method declara-
Accessmodifier A keyword in the declaration tion that acceptsvalues from the method call.
of a method that determines the accesslevel of a
method. Pass Giving data to a method by enclosingthe data
in parenthesesin the method call.
Argument The value or variable passed to a
method. Passby value Passingthe value of an argument to a
method.Thetype of datapasseddependson whether
Call A statementthat contains a method name the argument is a primitive or an object.
followed by parentheses.
Precondition Thepart of a method'sdocumentation
Boundary value A value that liesjust inside or just that statesthe assumptions,or initial requirements,
outside the range of valid values. of the method. Also calledpre.
Class method A method that can be called from Proceduralabstraction Breakinga task down into
the classitself. methods.
Local Variables,constants,and objectsthat are Postcondition The part of a method'sdocumenta-
declaredwithin a method and thereforehavea scope tion that stateswhat must be true after the method
limited to that method. has been executed.Also called posf.
Method body The statementsthat implement a Top-down development A problem-solving
method. approachwhere a task is broken down into subtasks
and then the subtasksare reduced to yet simpler
Method declaration The first line of a method,
tasks.
which containsthe method name,accesslevel,return
type, and parameters,if any. Visibilitv The accesslevel of a method.

/** */ Used to enclose documentation comments


for a method.

public An accessmodifier used in the declaration


of a method to indicate that the method is visible
to any other class.

static Akeywordusedinthedeclarationof amethod


to indicate that the method is a class method.

void A keyword used in the declaration of a method to


indicate that the method will not return a value.

rerurn Statement used to send a value from a method


back to the calling statement.

Chapter7 Methods
1
I. Use top-down developmentand procedural 8. a) What is the return statementused for?
abstractionto write pseudocodefor the follow- b) How many values Cono rerurn statement
ing specification: send back to the calling statement?
The Pizza application allows the user to c) How is the declaration of a method return-
chooseto display the instructions for mak- ing a value different from the declaration of
ing apizza in either English or Spanish. a method that doesnot return a value?

2. Explain the differencebetweenmethod declara- 9, Find and explain the error in the codebelow:
tion and method body. public class MethoclCallExarnple {
a public static void main(Stringll args)
What type of keyword is used to change the {
int num;
accesslevel of a method? rlnSnmotlli nn l l'

num = dosomethingu;
/l
What is another word used for describingthe ]
accesslevel of a method?
n"h'l i . qf af i ^ i nr rlaSnnat,]. i hd l\ I

5. Explain the scopeof eachof the variablesin the return(5);


codebelow: ]
]
public class ScopeExample {

public static void main(String[] args) {


10. a) What type of commentsshould be used for
int varl; describinga method?
for (int vax2 = 0; var2 < 5; var2++) { b) What three things should the comments for
methodl () ; a method describe?
]
]
True/False
public static void methodl0 {
1,1.Determine if eachof the following are true or
int var3;
for (j-nt var4 = 0; var4 < 2; var4++) false,If false,explain why.
{
var3 += L; a) Breakinga task down into methodsis called
] proceduralabstraction.
] b) A method call consistsof the method decla-
] ration in an assignment statement.
c) A void method must return a value.
6. Write a method declaration for each of the fol- d) An accessmodifier declaresthe return type
lowing descriptions: of a method.
a) A classmethod named getVowelsthat canbe e) The keyword sraric declaresa method is a
calledby any other method, requiresa String classmethod.
parameter,and returns an integervalue. f) Method parametersare enclosedby braces
b) A classmethod named extractDigitthat can ({}).
be called by any other method, requires an g) Local variablescan be used by any method
integer parameter,and returns an integer in a class.
value. h) The value of an argumentpassedto a method
c) A classmethod named insertStringthat can can be changedin an assignmentstatement
be called by any other method, requires a in the method.
String parameterand an integerparameter, i) Method overloading means that an applica-
and returns a String parameter. tion containsmore than 10methods.
j) The return statementis used to senda value
a) How does the compiler distinguish one back to the calling statement.
method from another? k) The precondition of a method statesthe data
b) Can two methodsin the sameclasshavethe types of the method'sparameters.
samename?Explain. l) The postcondition of a method describesthe
way the method accomplishesits task.

Chapter7 Methods
Exercise 1 House
Createa House application that calls methods addRoof0, addBase0,and addWalk0 to display the
following:

/\
r'\
I I
I I
I I
t l
l l
I I
I I
l -I

Exercise 2 MetricConversion
The following formulas can be used to convertEnglish units of measurementsto metric units:
inches* 254 = centimeters
feet*30=centimeters
yards*0.91=meters
miles*1.6=kilometers
Create a MetricConversion application that displays a menu of conversionchoicesand then prompts
the user to choosea conversion.Conversion choicesshould include inches to centimeters,feet to cen-
timeters,yards to meters,miles to kilometers,and vice versa.The applicationshould include separate
methodsfor doing eachof the conversions.Application output should look similar to:

Enter a nunber: lE
Conuert:
1. Inches to Centineters 5. Centineters to Inches
2. Feet to Centineters 6. Centineters to Feet
3. tards to lleters ?. l.leters to tards
4. I'liles to Hilometers 8. l{ilonetere to l'lites
Enter your choice: 1
1O inches equals 25.4 centineters.

Exercise 3 r,, PrimeNumber


Modify the PrimeNumber application createdin Chapter 6 ExerciseL to include a method named
isPrime0. The isPrimeQmethod should require one parameterand return a Booleanvalue.

Chapter7 Methods
Exercise 4 IsoTriangle
Create an IsoTriangle application that prompts the user for the size of an isoscelestriangle and then
displaysthe triangle with that many lines.The IsoTriangleapplicationcodeshould include:
. the drawBar0 method from the chapter.
. An addSpaces0method which "prints" spaces.
Application output should look similar to:

Enter the size: 4


:*
i*r*
:***:**

Exercise 5 AddCoins
Createan AddCoins application that prompts the user for the number of pennies, nickels, dimes,
and quarters, and then displays their total dollar amount. The AddCoins application should include
a getDollarAmount0 method that has four int parameterscorrespondingto the number of pennies,
nickels,dimes, and quarters,and returns a String that correspondsto the dollar value of the coins.
Note that the String returned should include the currency sign ($). Application output should look
similar to:

Enter your total coins:

Quanters: 3
Dimes: 2
Hickels:1
Pennies: I

Total:51.88

Exercise 6 PythagoreanTriple
Create a PythagoreanTripleapplication that displays all pythagorean triples with values of A and B
lessthan 100.A pythagoreantriple is a set of three integersthat make the equationa2+ b2= c2true.
The application should include a PerfectSquare0method that usesthe solution from the PerfectSquare
review in Chapter6. (Hint: You will needto generateall possiblecombinationsof A and B and display
lust those that work.)

Chapter7 Methods
Exercise 7 Perfectlntegers
Create a Perfectlntegersapplication that displays all perfect integers up to 100.A perfect integer is a
number which is equal to the sum of all its factors except itself. For example, 6 is a perfect number
because7 +2+ 3 = 6. The applicationshouldincludeabooleanmethodisPerfectO.

Exercise 8 HiLo
a) In the Hi-Lo game,the player begins with a scoreof 1000.The player is prompted for the
number of points to risk and a secondprompt asksthe player to chooseeither High or
Low. The player'schoiceof either High or Low is comparedto 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 "high". The number 7 is neither high
nor low, and the player losesthe points at risk. If the player had guessedcorrectly,
the points at risk are doubled and added to the total points. For a wrong choice,the
player loses the points at risk. Create a HiLo application based on this specification.
Application output should look similar to:

High Lor+ Ganre


RULES
Hunbers 1 through 6 are lou
Humhers I through 13 are high
Hunber ? is neither high or lor,r
You haue 1OEE points-
Enter points to risk: SEE
Predict (1=HiSh, 6=Lou): B
Hunber is 4
Iou r+in.
F1a9 again? 9
You haue 2668 points.

b) Modify the applicationto allow the player to continueuntil there are 0 points left. At
the end of the game,display the number of guessesthe user took before running out
of points.

Chapter7 Methods
Exercise 9 Nim
The game of Nim starts with a random number of stonesbetween 15 and 30. TWoplayers
alternate
turns and on eachturn may take either 1,2, or 3 stonesfrom the pile. The player forcedto take
the last
stoneloses'Createa Nim applicationthat allows the user to play againstthe computer.In this
version
of the game,the applicationgeneratesthe number of stonesto begin with, the number of
stonesthe
computertakes,and the user goesfirst. The Nim applicationcodeshould:
o prevent the user and the computer from taking an illegal
number of stones.For
example,neither should be allowed to take three stoneswhen there are only 1 or 2
Ieft.
. include an isValidEntryQmethod to checkuser input.
' include a drawStones0 method that generatesa random
number from 1 to 3 for the
number of stonesthe computer draws.
' include separatemethodsto handle the user'sturn
and the computer,sturn.
Application output should look similar to that shown on the next page:

There anr.e22 stones. Igr many ruould you like? l


There are 19 stones. The conrfiuiir taf;; Z-uionJ*.
There are 1? stones. !g" rarr! *uoutay;; ti*.?"5-
There are 14 stones. The confu[ir tailes Z-*[oni*-
T h e r e a r e 1 2 s t o n e s . _ t l o " n a n ! r + o u t Ay ; ; -*l';;*;.
fit.T'-5-
There are 9 stones. The compiltio tat*6i--f
There ane 6 stones. lgr man! r,routd t;u ii[ri":-'
There are 3 stones. The confiuirr tatiJ 5-*[on*".
The player beats the computir!

Exercise 10 .*5 GuessingGame


The GuessingGame application modified in Chapter 6 Exercise 8 should include a
separate method for
displaying a hint to the user. Modify the GuessingGame application as follows:

a) Modify the algorithm to include a call to a method named giveHintg, which


displays
a hint, but does not return a value.

b) Modify the flowchart based on the argorithm modifications.

c) Modify the GuessingGame code. Application output should look similar to:

Enter a nunher hetlreen 1 and 2E: 1 5


Hint: trg a higher number

Enter a nunher hetr+een 1 and 2E: 1?


Hint: trg a lotrer nunher

Enter a number hetlreen 1 and 26: L6


You r,ron!

Chapter7 Methods

You might also like