Tải bản đầy đủ - 0 (trang)
Chapter 4. Control Statements: Part I

Chapter 4. Control Statements: Part I

Tải bản đầy đủ - 0trang

Chapter4.ControlStatements:PartI

Let'sallmoveoneplaceon.

LewisCarroll

Thewheeliscomefullcircle.

WilliamShakespeare

HowmanyapplesfellonNewton'sheadbeforehe

tookthehint!

RobertFrost

Alltheevolutionweknowofproceedsfromthe

vaguetothedefinite.

CharlesSandersPeirce

OBJECTIVES

Inthischapteryouwilllearn:

Tousebasicproblem-solvingtechniques.

Todevelopalgorithmsthroughtheprocessoftop-down,

stepwiserefinement.

Tousetheifandif...elseselectionstatementstochoose

amongalternativeactions.

Tousethewhilerepetitionstatementtoexecutestatements

inaprogramrepeatedly.



Tousecounter-controlledrepetitionandsentinel-controlled

repetition.

Tousetheassignment,incrementanddecrementoperators.



[Page124]

Outline

4.1Introduction

4.2Algorithms

4.3Pseudocode

4.4ControlStructures

4.5ifSingle-SelectionStatement

4.6if...elseDouble-SelectionStatement

4.7whileRepetitionStatement

4.8FormulatingAlgorithms:Counter-ControlledRepetition

4.9FormulatingAlgorithms:Sentinel-ControlledRepetition

4.10FormulatingAlgorithms:NestedControlStatements

4.11CompoundAssignmentOperators

4.12IncrementandDecrementOperators

4.13PrimitiveTypes

4.14(Optional)GUIandGraphicsCaseStudy:CreatingSimple

Drawings



4.15(Optional)SoftwareEngineeringCaseStudy:Identifying

ClassAttributes

4.16Wrap-Up

Summary

Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises

Exercises







[Page124(continued)]



4.1.Introduction

Beforewritingaprogramtosolveaproblem,itisessentialto

haveathoroughunderstandingoftheproblemandacarefully

plannedapproachtosolvingit.Whenwritingaprogram,itis

alsoessentialtounderstandthetypesofbuildingblocksthat

areavailableandtoemployprovenprogram-construction

techniques.InthischapterandinChapter5,Control

Statements:Part2,wediscusstheseissuesinourpresentation

ofthetheoryandprinciplesofstructuredprogramming.The

conceptspresentedherearecrucialinbuildingclassesand

manipulatingobjects.

Inthischapter,weintroduceJava'sif,if...elseandwhile

statements,threeofthebuildingblocksthatallowprogrammers

tospecifythelogicrequiredformethodstoperformtheirtasks.

Wedevoteaportionofthischapter(andChapters5and7)to

furtherdevelopingtheGradeBookclassintroducedinChapter3.In

particular,weaddamethodtotheGradeBookclassthatuses

controlstatementstocalculatetheaverageofasetofstudent

grades.Anotherexampledemonstratesadditionalwaysto

combinecontrolstatementstosolveasimilarproblem.We

introduceJava'scompoundassignmentoperatorsandexplore

Java'sincrementanddecrementoperators.Theseadditional

operatorsabbreviateandsimplifymanyprogramstatements.

Finally,wepresentanoverviewoftheprimitivedatatypes

availabletoprogrammers.







[Page124(continued)]



4.2.Algorithms

Anycomputingproblemcanbesolvedbyexecutingaseriesof

actionsinaspecificorder.Aprocedureforsolvingaproblemin

termsof

1. theactionstoexecuteand

2. theorderinwhichtheseactionsexecute



[Page125]

iscalledanalgorithm.Thefollowingexampledemonstrates

thatcorrectlyspecifyingtheorderinwhichtheactionsexecute

isimportant.

Considerthe"rise-and-shinealgorithm"followedbyone

executiveforgettingoutofbedandgoingtowork:(1)Getout

ofbed;(2)takeoffpajamas;(3)takeashower;(4)get

dressed;(5)eatbreakfast;(6)carpooltowork.Thisroutine

getstheexecutivetoworkwellpreparedtomakecritical

decisions.Supposethatthesamestepsareperformedina

slightlydifferentorder:(1)Getoutofbed;(2)takeoff

pajamas;(3)getdressed;(4)takeashower;(5)eatbreakfast;

(6)carpooltowork.Inthiscase,ourexecutiveshowsupfor

worksoakingwet.

Specifyingtheorderinwhichstatements(actions)executeina

programiscalledprogramcontrol.Thischapterinvestigates

programcontrolusingJava'scontrolstatements.







[Page125(continued)]



4.3.Pseudocode

Pseudocodeisaninformallanguagethathelpsprogrammers

developalgorithmswithouthavingtoworryaboutthestrict

detailsofJavalanguagesyntax.Thepseudocodewepresentis

particularlyusefulfordevelopingalgorithmsthatwillbe

convertedtostructuredportionsofJavaprograms.Pseudocode

issimilartoeverydayEnglishitisconvenientanduserfriendly,

butitisnotanactualcomputerprogramminglanguage.

Pseudocodedoesnotexecuteoncomputers.Rather,ithelpsthe

programmer"thinkout"aprogrambeforeattemptingtowriteit

inaprogramminglanguage,suchasJava.Thischapterprovides

severalexamplesofhowtousepseudocodetodevelopJava

programs.

Thestyleofpseudocodewepresentconsistspurelyof

characters,soprogrammerscantypepseudocodeconveniently,

usinganytext-editorprogram.Acarefullypreparedpseudocode

programcaneasilybeconvertedtoacorrespondingJava

program.Inmanycases,thissimplyrequiresreplacing

pseudocodestatementswithJavaequivalents.

Pseudocodenormallydescribesonlystatementsrepresenting

theactionsthatoccurafteraprogrammerconvertsaprogram

frompseudocodetoJavaandtheprogramisrunonacomputer.

Suchactionsmightincludeinput,outputoracalculation.We

typicallydonotincludevariabledeclarationsinourpseudocode.

However,someprogrammerschoosetolistvariablesand

mentiontheirpurposesatthebeginningoftheirpseudocode.



[Page125(continued)]



4.4.ControlStructures

Normally,statementsinaprogramareexecutedoneafterthe

otherintheorderinwhichtheyarewritten.Thisprocessis

calledsequentialexecution.VariousJavastatements,which

wewillsoondiscuss,enabletheprogrammertospecifythatthe

nextstatementtoexecuteisnotnecessarilythenextonein

sequence.Thisiscalledtransferofcontrol.

Duringthe1960s,itbecameclearthattheindiscriminateuseof

transfersofcontrolwastherootofmuchdifficultyexperienced

bysoftwaredevelopmentgroups.Theblamewaspointedatthe

gotostatement(usedinmostprogramminglanguagesofthe

time),whichallowstheprogrammertospecifyatransferof

controltooneofaverywiderangeofpossibledestinationsina

program.Thenotionofso-calledstructuredprogramming

becamealmostsynonymouswith"gotoelimination."[Note:Java

doesnothaveagotostatement;however,thewordgotois

reservedbyJavaandshouldnotbeusedasanidentifierin

programs.]

TheresearchofBohmandJacopini[1]haddemonstratedthat

programscouldbewrittenwithoutanygotostatements.The

challengeoftheeraforprogrammerswastoshifttheirstylesto

"goto-lessprogramming."Notuntilthe1970sdidprogrammers

starttakingstructuredprogrammingseriously.Theresultswere

impressive.Softwaredevelopmentgroupsreportedshorter

developmenttimes,morefrequenton-timedeliveryofsystems

andmorefrequentwithin-budgetcompletionofsoftware

projects.Thekeytothesesuccesseswasthatstructured

programswereclearer,easiertodebugandmodify,andmore

likelytobebugfreeinthefirstplace.

[1]Bohm,C.,andG.Jacopini,"FlowDiagrams,TuringMachines,andLanguageswithOnlyTwoFormation

Rules,"CommunicationsoftheACM,Vol.9,No.5,May1966,pp.336371.



[Page126]

BohmandJacopini'sworkdemonstratedthatallprogramscould

bewrittenintermsofonlythreecontrolstructuresthe

sequencestructure,theselectionstructureandthe

repetitionstructure.Theterm"controlstructures"comes

fromthefieldofcomputerscience.WhenweintroduceJava's

implementationsofcontrolstructures,wewillrefertothemin

theterminologyoftheJavaLanguageSpecificationas"control

statements."



SequenceStructureinJava

ThesequencestructureisbuiltintoJava.Unlessdirected

otherwise,thecomputerexecutesJavastatementsoneafter

theotherintheorderinwhichtheyarewritten,thatis,in

sequence.TheactivitydiagraminFig.4.1illustratesatypical

sequencestructureinwhichtwocalculationsareperformedin

order.Javaletsushaveasmanyactionsaswewantina

sequencestructure.Aswewillsoonsee,anywhereasingle

actionmaybeplaced,wemayplaceseveralactionsin

sequence.



Figure4.1.Sequencestructureactivitydiagram.

(Thisitemisdisplayedonpage127intheprintversion)



[Viewfullsizeimage]



ActivitydiagramsarepartoftheUML.Anactivitydiagram

modelstheworkflow(alsocalledtheactivity)ofaportionof

asoftwaresystem.Suchworkflowsmayincludeaportionofan

algorithm,suchasthesequencestructureinFig.4.1.Activity

diagramsarecomposedofspecial-purposesymbols,suchas

action-statesymbols(rectangleswiththeirleftandright

sidesreplacedwitharcscurvingoutward),diamondsand

smallcircles.Thesesymbolsareconnectedbytransition

arrows,whichrepresenttheflowoftheactivity,thatis,the

orderinwhichtheactionsshouldoccur

Likepseudocode,activitydiagramshelpprogrammersdevelop

andrepresentalgorithms,althoughmanyprogrammersprefer

pseudocode.Activitydiagramsclearlyshowhowcontrol

structuresoperate.

ConsidertheactivitydiagramforthesequencestructureinFig.

4.1.Itcontainstwoactionstatesthatrepresentactionsto

perform.Eachactionstatecontainsanactionexpressionfor

example,"addgradetototal"or"add1tocounter"that

specifiesaparticularactiontoperform.Otheractionsmight

includecalculationsorinput/outputoperations.Thearrowsin

theactivitydiagramrepresenttransitions,whichindicatethe

orderinwhichtheactionsrepresentedbytheactionstates

occur.Theprogramthatimplementstheactivitiesillustratedby

thediagraminFig.4.1firstaddsgradetototal,thenadds1to

counter.



Thesolidcirclelocatedatthetopoftheactivitydiagram

representstheactivity'sinitialstatethebeginningofthe

workflowbeforetheprogramperformsthemodeledactions.

Thesolidcirclesurroundedbyahollowcirclethatappears

atthebottomofthediagramrepresentsthefinalstatetheend

oftheworkflowaftertheprogramperformsitsactions.

Figure4.1alsoincludesrectangleswiththeupper-rightcorners

foldedover.TheseareUMLnotes(likecommentsin

Java)explanatoryremarksthatdescribethepurposeofsymbols

inthediagram.Figure4.1usesUMLnotestoshowtheJava

codeassociatedwitheachactionstateintheactivitydiagram.A

dottedlineconnectseachnotewiththeelementthatthenote

describes.ActivitydiagramsnormallydonotshowtheJava

codethatimplementstheactivity.Weusenotesforthis

purposeheretoillustratehowthediagramrelatestoJavacode.

FormoreinformationontheUML,seeouroptionalcasestudy,

whichappearsintheSoftwareEngineeringCaseStudysections

attheendsofChapters18and10,orvisitwww.uml.org.



[Page127]



SelectionStatementsinJava

Javahasthreetypesofselectionstatements(discussedinthis

chapterandChapter5).Theifstatementeitherperforms

(selects)anactionifaconditionistrueorskipstheaction,if

theconditionisfalse.Theif...elsestatementperformsanaction

ifaconditionistrueandperformsadifferentactionifthe

conditionisfalse.Theswitchstatement(Chapter5)performs

oneofmanydifferentactions,dependingonthevalueofan

expression.

Theifstatementisasingle-selectionstatementbecauseit

selectsorignoresasingleaction(or,aswewillsoonsee,a



singlegroupofactions).Theif...elsestatementiscalleda

double-selectionstatementbecauseitselectsbetweentwo

differentactions(orgroupsofactions).Theswitchstatementis

calledamultiple-selectionstatementbecauseitselects

amongmanydifferentactions(orgroupsofactions).



RepetitionStatementsinJava

Javaprovidesthreerepetitionstatements(alsocalledlooping

statements)thatenableprogramstoperformstatements

repeatedlyaslongasacondition(calledtheloopcontinuationcondition)remainstrue.Therepetition

statementsarethewhile,do...whileandforstatements.(Chapter

5presentsthedo...whileandforstatements.)Thewhileandfor

statementsperformtheaction(orgroupofactions)intheir

bodieszeroormoretimesiftheloop-continuationconditionis

initiallyfalse,theaction(orgroupofactions)willnotexecute.

Thedo...whilestatementperformstheaction(orgroupof

actions)initsbodyoneormoretimes.

Thewordsif,else,switch,while,doandforareJavakeywords.

RecallthatkeywordsareusedtoimplementvariousJava

features,suchascontrolstatements.Keywordscannotbeused

asidentifiers,suchasvariablenames.AcompletelistofJava

keywordsappearsinAppendixC.



SummaryofControlStatementsinJava

Javahasonlythreekindsofcontrolstructures,whichfromthis

pointforwardwerefertoascontrolstatements:thesequence

statement,selectionstatements(threetypes)andrepetition

statements(threetypes).Everyprogramisformedby

combiningasmanysequence,selectionandrepetition

statementsasisappropriateforthealgorithmtheprogram



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 4. Control Statements: Part I

Tải bản đầy đủ ngay(0 tr)

×