Chapter 07
Chapter 07
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.
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
public static
voicl fahrenheitToCelsius 0 {
double fTernp, cTenp;
Scanner input = new Scanner(System.in);
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:
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.
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, "$");
$$$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.
]
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.
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.
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.
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:
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'
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
GradeConverterImplementation
Chapter7 Methods 3
The isValidNumber0 method is the first method written and tested:
public class GracleConverter {
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
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 {
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
q^-,
imnnrts i-,,- ,,f i l - - *iner;
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-
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
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.
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.
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.
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.
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.
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
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.
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:
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:
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:
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:
c) Modify the GuessingGame code. Application output should look similar to:
Chapter7 Methods