0% found this document useful (0 votes)
164 views189 pages

Learn Java

Java

Uploaded by

coressu
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)
164 views189 pages

Learn Java

Java

Uploaded by

coressu
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

Learn Java

the
Hard Way
Graham Mitchell
Version20130720.004
[Link].
Version20130720.004
100908070605XYZABC04030201
Preface
Ihavebeenteachingbeginnershowtocodeforoverfifteenyears.Morethan2,000studentshavetaken
[Link]
littleandothersgainedincredibleskilloverthecourseofjustafewyears.
Ibelievethatnearlyanyonecanteachachildprodigyhowtocode.Itaughtmy9yearolddaughterto
code,andshemadeherfirstAndroidappsixweekslater!Ifyouarethechildprodigy,thisbookisnot
writtenforyou.
[Link]
[Link].

Thebestwaytolearnistodo.
[Link]
Contents
Preface:LearningbyDoing
Introduction:TheChallengeofJavaasaFirstLanguage
Exercise0:TheSetup
Exercise1:AnImportantMessage
Exercise2:MorePrinting
Exercise3:PrintingChoices
Exercise4:EscapeSequencesandComments
Exercise5:SavingInformationinVariables
Exercise6:MathematicalOperations
Exercise7:GettingInputfromaHuman
Exercise8:StoringtheHumansResponses
Exercise9:CalculationswithUserInput
Exercise10:VariablesOnlyHoldValues
Exercise11:VariableModificationShortcuts
Exercise12:BooleanExpressions(TrueorFalse)
Exercise13:ComparingStrings
Exercise14:CompoundBooleanExpressions(And,Or,Not)
Exercise15:MakingDecisionswithIfStatements
Exercise16:MoreIfStatements
Exercise17:Otherwise(IfStatementswithElse)
Exercise18:IfStatementswithStrings
Exercise19:MutualExclusionwithChainsofIfandElse
Exercise20:MoreChainsofIfsandElse
Exercise21:NestedIfStatements
Exercise22:MakingDecisionswithaBigSwitch
Exercise23:MoreStringComparisons
Exercise24:ChoosingNumbersRandomly
Exercise25:MoreComplexRandomNumbers
Exercise26:RepeatingYourselfusingaWhileLoop
Exercise27:ANumberGuessingGame
Exercise28:InfiniteLoops
Exercise29:UsingLoopsforErrorChecking
Exercise30:DoWhileLoops
Exercise31:AddingValuesOneataTime
Exercise32:AddingValuesforaDiceGame
Exercise33:TheDiceGameCalledPig
Exercise34:CallingaFunction
Exercise35:CallingFunctionstoDrawaFlag
Exercise36:DisplayingDicewithFunctions
Exercise37:ReturningaValuefromaFunction
Exercise38:AreasofShapes
Exercise39:ThirtyDaysRevisitedwithJavadoc
Exercise40:ImportingStandardLibraries
Exercise41:ProgramsthatWritetoFiles
Exercise42:GettingDatafromaFile
Exercise43:SavingaHighScore
Exercise44:CountingwithaForLoop
Exercise45:CaesarCipher(LoopingThroughaString)
Exercise46:NestedForLoops
Exercise47:GeneratingandFilteringValues
Exercise48:ArraysManyValuesinaSingleVariable
Exercise49:FindingThingsinanArray
Exercise50:SayingSomethingIsNOTinanArray
Exercise51:ArraysWithoutForeachLoops
Exercise52:LowestTemperature
Exercise53:MailingAddresses(Records)
Exercise54:RecordsfromaFile
Exercise55:AnArrayofRecords
Exercise56:ArrayofRecordsfromaFile(TemperaturesRevisited)
Exercise57:ADeckofPlayingCards
Exercise58:FinalProjectTextAdventureGame
Introduction:Java
[Link]
peoplewhoalreadyknowhowtocodeorwhoareprodigies.
IcanteachyouJava,[Link]
amgoingtohavetocheatabit.
[Link]
[Link],then1)yourewrong,and2)
[Link]
hastooffer,fasterthanyoucanhandleit.
Inparticular,Ihaveonehugeomission:IamgoingtoavoidthetopicofObjectOrientedProgramming
(OOP).Imprettysurethatuncomfortablebeginnerscantlearnhowtocodewellandalsolearn
[Link].
IplantowriteafollowupbookthatwillcoverObjectOrientedProgrammingandthemorecomplex
[Link]
manyyears,andIhaveneverhadastudentcomevisitmefromcollegeandsayIwishyouhadspent
lesstimeonthefundamentals.

WhatYouWillLearn
HowtoinstalltheJavacompilerandatexteditortowriteprogramswith.
Howtocreate,compileandrunyourfirstJavaprogram.
Variablesandgettinginputfromtheuserandfromfiles.
Makingdecisionswithifstatements
Loops
Arrays
Records

Inthefinalchapteryoullwriteanotsosimpletextbasedadventuregamewithlevelsloadedfromtext
[Link].

WhatYouWillNotLearn
Graphics
Objectorientedprogramming
HowtomakeanAndroidapp

Ilikegraphics,andtheyrenothardinJavacomparedto,say,C++,butIcantcovereverythingand
teachthebasicswell,sosomethinghadtogo.
Objectorientedprogramminghasnoplaceinanintroductorybook,inmyopinion.
Androidappsareprettycomplex,andifyoureabeginner,[Link]
inthisbookwillhurtyourchancesofmakinganapp,though,andthekinder,gentlerpacemaykeepyou
goingwhenotherbookswouldfrustrateyouintoquitting.
Also,[Link]
[Link],assuming
youhavefinishedworkingthroughthefirsttwobooks.

HowtoReadThisBook
AlthoughIhaveprovidedazipfilecontainingthesourcecodeforalltheexercisesinthebook,you
shouldtypethemin.
Foreachexercise,[Link],[Link]?Noneof
myformerstudentseverbecamegreatatprogrammingbymerelyreadingotherscode.
Workthestudydrills,[Link],[Link]
willbeabletocode,atleastalittle.

License
Somechaptersofthisbookaremadeavailablefreetoreadonlinebutyouarenotallowedtomake
[Link],allcontentiscopyright2013GrahamMitchell.
Exercise0:TheSetup
[Link]
installtheJavaDevelopmentKit(JDK).Ifyoudonotdobothofthesethings,youwillnotbeabletodo
[Link].
Warning!
Thisexerciserequiresyoutodothingsinaterminalwindow(alsocalleda
shell,[Link]
terminalwindow,thenyoumightneedtogolearnthatfirst.
ZedShawsexcellentCommandLineCrashCourseisat
[Link]
PowerShellonWindowsortheTerminalonOSXorbashonLinux.

MacOSX
Tocompletethisexercise,completethefollowingtasks:
1. Goto[Link]
TextWranglertexteditorandinstallit.
2. PutTextWranglerinyourdocksoyoucanreachiteasily.
3. FindaprogramcalledTerminal.(Searchforitifyouhaveto.)
4. PutyourTerminalinyourdockaswell.
5. LaunchtheTerminal.
6. IntheTerminalprogram,[Link]
responselikejavac1.7.0_04.Itisokayifthenumberafterjavacisnotexactlythesame
[Link],however,youmayneedtoinstallthe
JDK.
7. Afterthis,youshouldbebackataprompt.
8. Learnhowtocreateafolder(makeadirectory)[Link]
canputallyourcodefromthisbookinit.
9. [Link].
10. Useyourtexteditor(TextWrangler)[Link]
directoryyoujustcreated.
11. GobacktotheTerminalusingonlythekeyboardtoswitchwindows.
12. BackinTerminal,seeifyoucanlistthecontentsofthedirectorytoseeyournewlycreatedfile.

OSX:WhatYouShouldSee
IdontcurrentlyhaveaccesstoaMac,sohereisZedfollowingthestepsaboveonhiscomputerin
[Link],soseeifyoucanfigureoutallthedifferencesbetween
whathedidandwhatyoushoulddo.
Lastlogin:FriJul1900:56:54onttys001
~$javacversion
javac1.6.22
~$mkdirjavacode
~$cdjavacode
javacode$ls
#...[Link]....
javacode$ls
[Link]
javacode$
Windows
1. Goto[Link]
[Link].
2. MakesureyoucangettoNotepad++easilybyputtingitonyourdesktopand/orinQuick
[Link].
3. [Link].
4. MakeashortcuttoPowerShellonyourdesktopand/orQuickLaunchforyourconvenience.
5. Goto[Link]
A) ClickthebigJavabuttonontheleftnearthetoptodownloadtheJavaPlatform(JDK)
[Link].
B) OnthispageyouwillhavetoacceptthelicenseagreementandthenchoosetheWindows
[Link].
C) Oncedownloaded,[Link]
Next>theveryfirsttimeyouwillseeascreenthatsaysInstallto:C:\Program
Files(x86)\Java\jdk1.7.0_25\[Link]
location;youwillneeditsoon.
6. OncetheJDKisinstalledyouwillneedtofindouttheexactnameofthefolderwhereitwas
[Link]:driveinsidetheProgramFilesfolderortheC:\Program
Files(x86)[Link]
afoldercalledjdk1.7.0_25thathasafoldercalledbininsideit.Thefoldernamemusthave
jdk1.7init;[Link].
7. Onceyouareinthisfolder,youcanleftclickupinthefolderlocationanditwillchangeto
somethingthatlookslikeC:\ProgramFiles(x86)\Java\jdk1.7.0_25\[Link]
canwritethisdownorhighlightandrightclicktocopyittotheclipboard.
8. OncetheJDKisinstalledandyouknowthislocationopenupyourterminalwindow
(PowerShell).InPowerShell,typethis:

[Environment]::SetEnvironmentVariable("Path",
"$env:Path;C:\Program Files (x86)\Java\jdk1.7.0_25\bin", "User")

Putitallononeline,though.
Ifyoucopiedthefolderlocationtotheclipboard,thenyoucantypeeverythinguptothe$env:Path;
[Link]
canjustfinishthelinebytyping","User")[Link],youtyped
[Link]
fixyourmistake,thenpressENTERagain.
1. OncethesetEnvironmentVariablecommandcompleteswithoutgivingyouanerror,
[Link]
justmadewonttakeeffect.
2. LaunchPowerShellagain.
3. Typejavacversionattheprompt.Youshouldseearesponselikejavac1.7.0_25.
Congratulations!Ifyougotthattowork,therestofthisbookoughttoberelativelyeasy.
4. Afterthis,youshouldbebackatablinkingPowerShellprompt.
5. Learnhowtocreateafolder(makeadirectory)fromtheterminalwindow(PowerShell).Makea
directorysothatyoucanputallyourcodefromthisbookinit.
6. [Link].
7. Useyourtexteditor(Notepad++)[Link]
youjustcreated.
8. Gobacktotheterminalusingonlythekeyboardtoswitchwindows.
9. Backintheterminal,seeifyoucanlistthecontentsofthedirectorytoseeyournewlycreated
file.

Windows:WhatYouShouldSee
WindowsPowerShell
Copyright(C)[Link].

PSC:\Users\Graham_Mitchell>javacversion
javac1.7.0_25
PSC:\Users\Graham_Mitchell>mkdirjavacode

Directory:C:\Users\Graham_Mitchell\javacode

ModeLastWriteTimeLengthName

d7/19/20137:39PMjavacode

PSC:\Users\Graham_Mitchell>cdjavacode
PSC:\Users\Graham_Mitchell\javacode>ls
PSC:\Users\Graham_Mitchell\javacode>
...HereyouwoulduseNotepad++[Link]...
PSC:\Users\Graham_Mitchell\javacode>ls

Directory:C:\Users\Graham_Mitchell\javacode

ModeLastWriteTimeLengthName

a7/19/20137:[Link]

PSC:\Users\Graham_Mitchell\javacode>
Youwillprobablyseeadifferentpromptandotherslightdifferencesbutyoushouldntgetanyerrors
andthisisthegeneralidea.
Linux
TherearealotofdifferentversionsofLinuxoutthere,soIamgoingtogiveinstructionsforthelatest
[Link],youprobablyknowwhatyouaredoingwell
enoughtofigureouthowtomodifythedirectionsforyoursetup.
1. UseyourLinuxpackagemanagertoinstallthegedittexteditor(Whichmightjustbecalled
TextEditor.)
2. MakesureyoucangettogediteasilybyputtingitintheLauncher.
3. Rungeditsowecanchangesomeofthedefaultstobebetterforprogrammers:
A) OpenPreferencesandselecttheEditortab.
B) ChangeTabwidth:to4.
C) PutacheckmarknexttoAutomaticindentation
D) OpentheViewtabandturnonDisplaylinenumbers.
4. [Link],Konsole,orxterm.
5. PutyourTerminalintheLauncheraswell.
6. UseyourLinuxpackagemanagertoinstalltheJavaJDK.Iuseopenjdk7jdk,butifyou
prefertheOracleonethatwillwork,too.
7. LaunchyourTerminalifyouhaventalready.
8. Typejavacversionattheprompt.Youshouldseearesponselikejavac1.7.0_25.If
not,makesuretheJDKisinstalledandthatthebinfoldercontainingtheexecutablejavacis
inyourPATH.
9. Learnhowtocreateafolder(makeadirectory)[Link]
canputallyourcodefromthisbookinit.
10. [Link].
11. Useyourtexteditor(gedit)[Link]
justcreated.
12. [Link]
knowhow.
13. Backintheterminal,seeifyoucanlistthecontentsofthedirectorytoseeyournewlycreated
file.

Linux:WhatYouShouldSee
mitchell@grahamdesktop:~$javacversion
javac1.7.0_25
mitchell@grahamdesktop:~$mkdirjavacode
mitchell@grahamdesktop:~$cdjavacode/
mitchell@grahamdesktop:~/javacode$ls
mitchell@grahamdesktop:~/javacode$
...HereyouwoulduseNotepad++[Link]...
mitchell@grahamdesktop:~/javacode$ls
[Link]
mitchell@grahamdesktop:~/javacode$
Youwillprobablyseeadifferentpromptandotherslightdifferencesbutyoushouldntgetanyerrors
andthisisthegeneralidea.
WarningsforBeginners
[Link]
[Link]'tfinishit,gobackandtakethetime
[Link].
IfaprogrammertellsyoutousevimoremacsorEclipse,[Link]
[Link]
gedit,TextWrangler,orNotepad++(fromnowoncalledthetexteditororatexteditor)becauseitis
[Link]
enoughforyoustartingout.
[Link]
typography,[Link],theyll
[Link],[Link]
aneditor,aTerminal,andJava.
Finally,thepurposeofthissetupissoyoucandothreethingsveryreliablywhileyouworkonthe
exercises:
Writeexercisesusingyourtexteditor(geditonLinux,TextWrangleronOSX,orNotepad++on
Windows).
Runtheexercisesyouwrote.
Fixthemwhentheyarebroken.
Repeat.
Anythingelsewillonlyconfuseyou,sosticktotheplan.

FrequentlyAskedQuestions
DoIhavetousethislametexteditor?IwanttouseEclipse!
[Link]
twoways:
1. Itmakesyoudothingsthatyoudontneedtoworryaboutrightnow.
2. Itdoesthingsforyouthatyouneedtolearnhowtodoforyourselffirst.
[Link]
learnedhowtocodeyoucanuseothertoolsifyouwant,butnotnow.
CanIworkthroughthisbookonmytablet?OrmyChromebook?
[Link](JDK)oneitherofthosemachines.
Youmusthavesomesortoftraditionalcomputer.
Exercise1:AnImportantMessage
InthisexerciseyouwillwriteaworkingprograminJavatodisplayanimportantmessageonthescreen.
Ifyouarenotusedtotypingdetailedinstructionsforacomputerthenthiscouldbeoneoftheharder
[Link],thecomputer
[Link],thenthereisa
goodchancethatyouwillbeabletohandleeveryexerciseinthebookaslongasyouworkonitevery
dayanddontquit.
OpenthetexteditoryouinstalledinExercise0andtypethefollowingtextintoasinglefilenamed
[Link],includingspacing,punctuation,
andcapitalization.
1publicclassFirstProg
2{
3publicstaticvoidmain(String[]args)
4{
[Link]("Iamdeterminedtolearnhowtocode.");
[Link]("Today'sdateis");
7}
8}
Ihaveputlinenumbersinfrontofeachline,[Link]
[Link],dependingonwhetherornotyouhavesavedthefileyet,thedifferent
[Link],[Link]
differencesarefine.
Imgoingtowalkthroughthislinebyline,justtomakesureyoutypedeverythingcorrectly.
Thefirstlinestartswiththewordpublicfollowedbyasinglespacethenthewordclassfollowed
[Link],thePinProgis
[Link].
Thesecondlineisjustasinglecharacter:[Link]
thenpressingthe[keywhichisusuallytotherightoftheletterP.
BeforeIgoontothethirdlineoftheprogram,Ishouldtellyouwhatprogrammersusuallycalleach
funnysymbolthatappearsinthisprogram.
(and)arecalledparentheses(thatsplural).Justoneofthemiscalleda
parenthesis,butsomepeoplejustcallthemparens(puhRENZ).Thisone(()is
sometimescalledaleftparenandtheother())iscalledarightparenbecause
[Link]
parenthesis(()isalsooftencalledanopenparenandtherightoneiscalleda
closeparenforsimilarreasons.
Theresanopenparenonline3andacloseparen,too,andnootherparenthesesinthe
wholefile.
[and]arecalledbrackets,butmanyprogrammerscallthemsquarebracketsto
[Link],parenthesesandsquarebracketsarenot
[Link]
bracketandrightbracketorclosebracket.
Theresanopenandclosesquarebracketrightnexttoeachotheronline3.
{and}arecalledbraces,[Link]
alsoalwayscomeinpairsofleftandrightcurlybraces/openandclosebraces.
"iscalledaquotationmark,[Link],thesealways
[Link]
[Link]
firstquoteservestobeginsomethingandthesecondoneendsthatthing.
'istechnicallyanapostrophe,butalmostallprogrammerscallthemsingle
[Link]
programminglanguages,singlequotesanddoublequotesareinterchangeable,butnot
[Link],buttheyregoingtobeprettyrarein
thisbook.
.istechnicallyaperiod,[Link]
lotinprogramminglanguages,andtheyareusuallyusedasseparatorsinsteadof
enders,sowedontcallthemperiods.
Therearefourdotsinthisprogramandoneperiod.
;[Link].
Javausesalotofsemicolonsalthoughthereareonlytwooftheminthisprogram:one
ontheendofline5andanotherattheendofline6.
:[Link]
usecolons,buttheyreveryrare.
Finally,<isalessthansignand>isagreaterthansign,butsometimestheyare
[Link],theyreusually
[Link],butyouwontseethemusedinthis
book.
Okay,[Link].
[Link]
(probably4or8).Thentypethewordpublicagain,onespace,thewordstatic,onespace,the
wordvoid,onespace,thewordmainfollowedbyanopenparen(nospacebetweenthewordmain
andtheparen).Aftertheparentheresonespace,thewordStringwithacapitalS,anopenand
closesquarebracketrightnexttoeachother,onespace,thewordargs,onespaceandfinallyaclose
parenthesis.
Solinethreestartswithatab,hasatotalofsixspaces,[Link].
Onthefourthline,yourtexteditormayhavealreadystartedyourcursordirectlyunderneaththepin
[Link],[Link]
anotheropencurlybraceandthatsit.
[Link],thenadot
(period),thenthewordout,anotherdot,thewordprintln(pronouncedPrintLineeventhough
theresnoioreattheend),anopenparen,aspace,aquotationmark(openquote),thesentenceI
amdeterminedtolearnhowtocode.(thesentenceendswithaperiod),thenaclose
quote,aspace,acloseparenandasemicolon.
Soline5hastwotabs,ninespaces,twodots(andaperiod),anopenandclosequote,anopenandclose
paren,andonlytwocapitalletters.
Line6isnearlyidenticaltoline5exceptthatthesentencesaysToday'sdateisinsteadofthe
determinationsentence.
[Link],youshouldbeabletoget
[Link].
Finally,line8hasnotabsandonemoreclosecurlybrace.YoucanpressENTERafterline8ornot:
Javadoesntcare.
[Link]
[Link]
[Link].
Alsonoticethateverytimewedidanopencurlybrace,theline(s)belowithadmoretabsatthe
beginning,andthelinesbelowclosecurlybraceshadfewertabs.
Okay,nowsavethis(ifyouhaventalready)[Link]
youcreatedinExercise0.
Makesurethefilenamematchesmineexactly:theFinFirstiscapitalized,thePinProgis
capitalized,[Link]
[Link]
[Link].

CompilingYourFirstProgram
Nowthattheprogramhasbeenwrittenandhopefullycontainsnomistakes(wellseesoonenough),
launchyourTerminal(orPowerShell)andchangeintothedirectorywherethecodeissaved.
[Link],itlookslikethis:
mitchell@grahamdesktop:~$cdjavacode/
mitchell@grahamdesktop:~/javacode$ls
[Link]
mitchell@grahamdesktop:~/javacode$
Inthefuture,sinceyourterminalprobablydoesntlooklikemine,Iamgoingtoabbreviatetheprompt
likethis:
$ls
[Link]
$
Thatwayitwillbelessconfusing,sincethereislesswrongstufftoignoreandyouonlyhavetolook
atwhatyoushouldtypeandwhatyoushouldsee.
Now,[Link]
[Link],whichisa
programthatwilltranslateourinstructionsintosomethingmorelikeonesandzerosthatthecomputer
[Link]
compilerprogramtocompileourJavasourcecodeintoabytecodefilethatwewillbeabletoexecute.
TheJavacompilerisnamedjavac(thecisforcompiler),andwerunitlikeso:
$[Link]
$
IfyouhaveextraordinaryattentiontodetailanddideverythingthatItoldyou,thiscommandwilltakea
secondtorun,[Link]
mistake,youwillseeanerrorlikethis:
$[Link]
[Link]:error:reachedendoffilewhileparsing
}
^
1error
$
[Link],thecompilertriesto
[Link],theguessesaredesignedforexpert
programmers,soitusuallydoesntguesswellforbeginnertypemistakes.
Hereisanexampleofadifferenterrormessageyoumightget:
$[Link]
[Link]:error:';'expected
[Link]("Iamdeterminedtolearnhowtocode."):
^
1error
$
Inthiscase,thecompilerisactuallyright:theerrorisonline5andthespecificerroristhatasemicolon
wasexpected(';'expected).(Thelineendswithacolon(:)butitoughttobeasemicolon(;).
Heresonemore:
$[Link]
[Link]:error:classFirstprogispublic,shouldbedeclaredinafile
[Link]
publicclassFirstprog
^
1error
$
[Link](notethelowercase
p)[Link],capitalizationandall,
thecompilergetsconfusedandbailsout.
Soifyouhaveanyerrormessages,fixthem,thensaveyourcode,gobacktotheterminalandcompile
again.
Warning!
Ifyoumakeachangetothecodeinyourtexteditor,youmustsavethefile
[Link],youwillstillbe
compilingtheoldversionofthecodethatwassavedpreviously,evenifthecode
inyourtexteditoriscorrect.
[Link]
directorylistingandyoushouldseethebytecodefilehasappearedinthefolder:
$[Link]
$ls
[Link]
$
Nowthatwehaveavalidbytecodefilewecanrunit(orexecuteit)byrunningitthroughtheJava
VirtualMachine(JVM)programcalledjava:
WhatYouShouldSee
$javaFirstProg
Iamdeterminedtolearnhowtocode.
Today'sdateis
$
NotethatthecommandyoutypeisjavaFirstProg,[Link]
[Link].
Areyoustoked?YoujustwroteyourfirstJavaprogramandranit!Ifyoumadeitthisfar,thenyou
almostcertainlyhavewhatittakestofinishthebookaslongasyouworkoniteverydayanddontquit.

StudyDrills
Aftermostoftheexercises,Iwilllistsomeadditionaltasksyoushouldtryaftertypingupthecodeand
[Link],
butyoushouldalwaysgivethemashot.
1. [Link]
madeyourchanges,compilethefileandrunitagain.
2. Changewhatisinsidethequotesonline5tohavethecomputerdisplayyourname.

WhatYouShouldSeeAfterCompletingtheStudyDrills
$javaFirstProg
I,GrahamMitchell,amdeterminedtolearnhowtocode.
Today'sdateisFriday,July19,2013.
$
Exercise2:MorePrinting
Okay,nowthatwevegottenthatfirst,hardassignmentoutoftheway,[Link]
isthatinthisone,westillhavealotofthesetupcode(whichwillbenearlythesameeverytime),but
theratioofsetuptousefulcodeismuchbetter.
[Link]
whatIhavewrittenexactly,includingspacing,punctuation,andcapitalization.
1publicclassLetterToYourself
2{
3publicstaticvoidmain(String[]args)
4{
[Link]("++");
[Link]("|####|");
[Link]("|####|");
[Link]("|####|");
[Link]("||");
[Link]("||");
[Link]("|BillGates|");
[Link]("|1MicrosoftWay|");
[Link]("|Redmond,WA98104|");
[Link]("||");
[Link]("++");
16}
17}

Noticethatthefirstlineisthesameasthepreviousassignment,exceptthatthenameoftheclassisnow
[Link]
[Link].
InJava,eachfilecancontainonlyonepublicclass,andthenameofthepublicclassmustmatchthefile
name(capitalizationandall)[Link]
not.
So,whatdoespublicclassmeaninJava?[Link],tryingtogointo
[Link]
[Link].(Unfortunately,theresgoingtobealotofthat.)
Youwillprobablynoticethatthesecond,thirdandfourthlinesofthisprogramareexactlythesameas
[Link].
Then,afterthesecondopenbrace,[Link]
[Link](|)iscalledthepipecharacter,andyou
cantypeitusingShift+backslash(\).AssumingyouareusinganormalUSkeyboard,thebackslash
keyislocatedbetweentheBackspaceandEnterkeys.
[Link],youcancompileandrunitthe
[Link],changethedirectoryinto
theonewhereyouaresavingyourcodeandtypethistocompileit:
$[Link]
Ifyouareextremelygoodwithannoyingdetailsandfortunate,youwillhavenoerrorsandthejavac
[Link],[Link],goback
[Link](s).
Fixthem,savethefileagain,andtrycompilingagain.
Onceitcompileswithnoerrors,youcanrunitlikebefore:
$[Link]
$javaLetterToYourself
++
|####|
|####|
|####|
||
||
|BillGates|
|1MicrosoftWay|
|Redmond,WA98104|
||
++
[Link]!Whatyouhaveaccomplishedsofarisnoteasy,andanyonethatthinksitis
[Link]!
Workalittleeverydayandthiswillgeteasier.

StudyDrills
1. [Link]!Goback
toyourtexteditorandchangethenameandaddressfromBillGatesaddressatMicrosoftto
[Link],compileitandrunitagain.

CommonStudentQuestions
DoIhavetousemyrealaddress?
[Link].
WhydoesntmyletterlineupwhenIruntheprogram?!?Everythinglooksperfectinthecode!
Youprobablyusedamixtureoftabsandspacesbetweenthequotesinyourprintln()statements.
[Link]
runs,anytabsembeddedinsidethequoteswilltakeup8spaces,[Link]
betweenthequotesandreplacethemwithspaces,thingsshouldlookthesameinyourcodeand
whenyouruntheprogram.
Exercise3:PrintingChoices
[Link]
println(),butprint()issometimesused,[Link].
[Link],couldyouguessthatthefilemustbe
[Link]?Infutureassignments,ImaynottellyouwhattonametheJava
file.
1publicclassPrintingChoices
2{
3publicstaticvoidmain(String[]args)
4{
[Link]("Alpha");
[Link]("Bravo");
7
[Link]("Charlie");
[Link]("Delta");
[Link]();
11
[Link]("Echo");
[Link]("Foxtrot");
14
[Link]("Golf");
[Link]("Hotel");
[Link]();
[Link]("India");
19
[Link]();
[Link]("This"+""+"is"+""+"a"+"test.");
22
23}
24}
Whenyourunit,thisiswhatyoushouldsee.
Alpha
Bravo
Charlie
Delta

EchoFoxtrotGolf
Hotel
India

Thisisatest.
Canyoufigureoutthedifference?
Bothprint()andprintln()[Link]
println()movestoanewlineafterfinishingprinting,andprint()doesnot:itdisplaysandthen
leavesthecursorrightattheendofthelinesothatthefollowingprintingstatementpicksupfromthat
samepositionontheline.
Youwillalsonotice(online10)thatwecanhaveaprintln()statementwithnothingbetweenthe
[Link],and
thenmovethecursortothebeginningofthenextline.
Youmayalsonoticethatthisprogramhassomelineswithnothingonthem(lines7,11,14,19and22).
Ontheveryfirstexercise,whenIwrotethatyoumustmatchwhatIhavewrittenexactly,including
spacing,punctuation,andcapitalization,[Link]
[Link],andtheprogramwillworkexactly
thesame.
[Link]
studentsarejustlearningsomethingashardasprogramming,tellingthemthetruthwillconfusethem
[Link],evenwhenthatmakesittechnicallyinaccurate.
Ifyoualreadyknowhowtoprogram,andmyliesoffendyou,thenthisbookwillbedifficulttoread.
Butforthosethatarejustlearning,[Link]
Illrevealthetrutheventually.
Anyway,online21,[Link]
[Link],aslongasyoucombinethose
thingsbeforeprinting.
Soonline21,IhavesixStrings1inquotationmarks:thewordthis,aspace,thewordis,aspace,
theworda,[Link](+)
betweeneachofthosesixStrings,[Link]
signbetweenStrings,Javaadds2themtogethertomakeonelongthinginquotationmarks,andthen
displaysthatallatonce.
Ifyouhaveanerrorinyourcode,[Link]
correctlyandgettingallthosedetailsrightistricky.
[Link],Illmakeupforitonthenextone.

1 WhatisaString?Abunchofcharacters(letters,numbers,symbols)[Link]
morelater.
2 Technicallycombiningsmallerwordstomakealargeroneiscalledconcatenation,[Link]
Stringstogether.
Exercise4:EscapeSequencesandComments
Haveyouthoughtaboutwhatmighthappenifwewantedtodisplayaquotationmarkonthescreen?
Sinceeverythingwewanttodisplayiscontainedbetweenquotationmarksintheprintln()
statement,puttingaquoteinsidethequoteswouldbeaproblem.
Mostprogramminglanguagesallowforescapesequences,whereyousignalwithsomesortofescape
characterthatthenextcharacteryouseeshouldntbehandledinthenormalway.
Thefollowing(evil)[Link]
[Link].
1publicclassEscapeSequences
2{
3publicstaticvoidmain(String[]args)
4{
5//InitialversioncreatedusingFIGlet,font"BigMoney",orientedsouthwest
6
[Link]("\t_____\n\t/|\n\tJJJJJ|");
[Link]("________________");
[Link]("\tJJ|/\\/\\/|/\\");
[Link]("\t__JJ|aaaaaa|\"\"\\/\"\"/aaaaaa|");
[Link]("\t/|JJ|/aa|\"\"/\"\"//aa|");
[Link]("\tJJ\\__JJ|/aaaaaaa|\"\"\"\"//aaaaaaa|");
[Link]("\tJJJJ/aaaa|\"\"\"/aaaa|");
[Link]("\tJJJJJJ/aaaaaaa/\"/aaaaaaa/");
15}
16}

Whenyourunit,thisiswhatyoushouldsee.
_____
/|
JJJJJ|________________
JJ|/\/\/|/\
__JJ|aaaaaa|""\/""/aaaaaa|
/|JJ|/aa|""/""//aa|
JJ\__JJ|/aaaaaaa|""""//aaaaaaa|
JJJJ/aaaa|"""/aaaa|
JJJJJJ/aaaaaaa/"/aaaaaaa/
Javasescapecharacterisabackslash(\),whichisthesamekeyyoupresstomakeapipe(|)show
[Link].
\"representsaquotationmark.
\tisatab;[Link]
complicatednowbecauseyouveneverseenitbefore,butwhenyourereadingsomeoneelsescodea
\tinsidethequotesislessambiguousthanabunchofblankspacesthatmightbespacesormightbea
tab.
\[Link]
beforecontinuingprinting.
\\ishowyoudisplayabackslash.
Online5youwillnoticethatthelinebeginswithtwoslashes(orforwardslashes,ifyouinsist).This
marksthelineasacomment,[Link]
aretotallyignoredbythecomputer.
Infact,thetwoslashestomarkacommentdonthavetobeatthebeginningoftheline;wecouldwrite
somethinglikethis:
[Link]("A");//printsan'A'onthescreen
[Link]
compiler.
(Thatsnotaverygoodcomment,though;anyprogrammerwhoknowsJavaalreadyknowswhat
[Link],not
[Link]
general.)
Anyway,thisonewasatoughone,[Link]
somethingnewandreturntonormaldifficulty.
Exercise5:SavingInformationinVariables
[Link]
wouldlikeourprogramstobeinteractive.
Unfortunately,interactivityrequiresseveraldifferentconceptsworkingtogether,andexplainingthemall
[Link].
Firstup:variables!IfyouhaveevertakenanAlgebraclass,youarefamiliarwiththeconceptof
[Link],too,andthebasicconceptisthe
same:
Avariableisanamethatreferstoalocationthatholdsavalue.
VariablesinJavahavefourmajordifferencesfrommathvariables:
1. Variablenamescanbemorethanoneletterlong.
2. Variablescanholdmorethanjustnumbers;theycanholdwords.
3. Youhavetochoosewhattypeofvaluesthevariablewillholdwhenthevariableisfirstcreated.
4. Thevalueofavariable(butnotitstype)[Link]
scoremightstartoutwithavalueof0,butbytheendoftheprogram,scoremightholdthe
value413500instead.
Okay,[Link]!Imnotgoingtotellyouwhatthenameofthefileis
[Link].
1publicclassCreatingVariables
2{
3publicstaticvoidmain(String[]args)
4{
5intx,y,age;
6doubleseconds,e,checking;
7StringfirstName,last_name,title;
8
9x=10;
10y=400;
11age=39;
12
13seconds=4.71;
14e=2.71828182845904523536;
15checking=1.89;
16
17firstName="Graham";
18last_name="Mitchell";
19title="Mr.";
20
[Link]("Thevariablexcontains"+x);
[Link]("Thevalue"+y+"isstoredinthevariabley.");
[Link]("Theexperimentcompletedin"+seconds+"seconds.");
[Link]("MyfavoriteirrationalnumberisEuler'sconstant:"+e);
[Link]("Hopefullyyourbalanceismorethan$"+checking+"!");
[Link]("Myfullnameis"+title+""+firstName+last_name);
27}
28}

WhatYouShouldSee
Thevariablexcontains10
Thevalue400isstoredinthevariabley.
Theexperimentcompletedin4.71seconds.
MyfavoriteirrationalnumberisEuler'sconstant:2.718281828459045
Hopefullyyourbalanceismorethan$1.89!
[Link]
[Link],y,[Link]
thesevariablesareintegers,whichisthetypeofvariablethatcanholdavaluebetweentwobillion.
[Link]
[Link]
integervariablecouldnotholdthevalue10000000000becausetenbillionistoobig.
Online6wedeclarevariablesnamedseconds,e,[Link],
whichisthetypeofvariablethatcanholdanumberthatmighthaveafractionalpart.
Avariablewhichisadoublecouldholdthevalue4.71.Itcouldholdthevalue8192.(Itmayhavea
fractionalpartbutdoesnthaveto.)Itcanprettymuchholdanyvaluebetween1.7976910308and
4.9406510324.
However,doubleshavelimitedprecision.Noticethatonline14Istorethevalue
2.71828182845904523536intothevariablenamede,butwhenIprintoutthatvalueonline24,
[Link]
[Link],butcanonlyhold
wholenumbersandcantholdhugehugevalues.
ThelasttypeofvariablewearegoingtolookatinthisexerciseistheString.Online7wedeclare
threeStringvariables:firstName,last_nameandtitle.Stringvariablescanholdwordsandphrases;the
nameisshortforstringofcharacters.
[Link]
point,thevariablexexists,butitsvalueisundefined.400isstoredintoyand39isstoredintothe
variableage.
Lines13through15giveinitialvaluestothethreedoublevariables,andlines17through19initialize
thethreeStringvariables.Thenlines21through26displaythevaluesofthosevariablesonthescreen.
Noticethatthevariablenamesarenotsurroundedbyquotes.
Iknowthatitdoesntmakesensetousevariablesforaprogramlikethis,butsooneverythingwill
becomeclear.

3 declaretotelltheprogramthename(oridentifier)andtypeofavariable.
4 initializetogiveavariableitsfirst(orinitial)value.
Exercise6:MathematicalOperations
NowthatweknowhowtodeclareandinitializevariablesinJava,wecandosomemathematicswith
thosevariables.
1publicclassMathOperations
2{
3publicstaticvoidmain(String[]args)
4{
5inta,b,c,d,e,f,g;
6doublex,y,z;
7Stringone,two,both;
8
9a=10;
10b=27;
[Link]("ais"+a+",bis"+b);
12
13c=a+b;
[Link]("a+bis"+c);
15d=ab;
[Link]("abis"+d);
17e=a+b*3;
[Link]("a+b*3is"+e);
19f=b/2;
[Link]("b/2is"+f);
21g=b%10;
[Link]("b%10is"+g);
23
24x=1.1;
[Link]("\nxis"+x);
26y=x*x;
[Link]("x*xis"+y);
28z=b/2;
[Link]("b/2is"+z);
[Link]();
31
32one="dog";
33two="house";
34both=one+two;
[Link](both);
36}
37}

WhatYouShouldSee
ais10,bis27
a+bis37
abis17
a+b*3is91
b/2is13
b%10is7

xis1.1
x*xis1.2100000000000002
b/2is13.0

doghouse
Theplussign(+)willaddtwointegersortwodoublestogether,oroneintegerandonedouble(ineither
order).WithtwoStrings(likeonline34)itwillconcatenate5thetwoStringstogether.

5 concatenatetojoincharacterStringsendtoend.
Theminussign()[Link],itworkswithtwointegers,
twodoubles,oroneintegerandonedouble(ineitherorder).
Anasterisk(*)isusedtorepresentmultiplication.Youcanalsoseeonline17thatJavaknowsaboutthe
correctorderofoperations.bismultipliedby3giving81andthenaisadded.
Aslash(/)[Link](likeonline
19)theresultisalsoanintegerandnotadouble.
Thepercentsign(%)isusedtomeanmodulus,whichisessentiallytheremainderleftoverafter
dividing.Online21,bisdividedby10andtheremainder(7)isstoredintothevariableg.

CommonStudentQuestions
Whyis1.1times1.1equalto1.2100000000000002insteadofjust1.21?
Whyis0.333333+0.666666equalto0.999999insteadof1.0?Sometimes
withmathwegetrepeatingdecimals,andmostcomputersconvertnumbers
intobinarybeforeworkingwiththem.Itturnsoutthat1.1isarepeating
decimalinbinary.
RememberwhatIsaidinthelastexercise:theproblemwithdoublesislimited
[Link],butIwould
likeyoutokeepinthebackofyourmindthatdoublevariablessometimesgive
youvaluesthatareslightlydifferentthanyoudexpect.
Exercise7:GettingInputfromaHuman
Nowthatwehavepracticedcreatingvariablesforabit,wearegoingtolookattheotherpartof
interactiveprograms:lettingthehumanwhoisrunningourprogramhaveachancetotypesomething.
Goaheadandtypethisup,butnoticethatthefirstlineintheprogramisnotthepublicclassline.
Thistimewestartwithanimportstatement.
Noteveryprogramneedstogetinteractiveinputfromahumanusingthekeyboard,sothisisnotpartof
thecoreoftheJavalanguage.JustlikeaFormula1racecardoesnotincludeanairconditioner,
programminglanguagesusuallyhaveasmallcoreandthenlotsofoptionallibraries6thatcanbe
includedifdesired.
[Link];
2
3publicclassForgetfulMachine
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
[Link]("WhatcityisthecapitalofFrance?");
[Link]();
11
[Link]("Whatis6multipliedby7?");
[Link]();
14
[Link]("Whatisyourfavoritenumberbetween0.0and1.0?");
[Link]();
17
[Link]("Isthereanythingelseyouwouldliketotellme?");
[Link]();
20}
21}

Whenyoufirstrunthisprogram,itwillonlyprintthefirstline:
WhatcityisthecapitalofFrance?
andthenitwillblinkthecursoratyou,[Link],I
typedthewordParis,buttheprogramwillworkthesameevenifyoutypeadifferentword.
ThenafteryoutypeawordandpressEnter,theprogramwillcontinue,printing:
Whatis6multipliedby7?
[Link],itwillenduplookinglikethis:

WhatYouShouldSee
WhatcityisthecapitalofFrance?
Paris
Whatis6multipliedby7?
42
Whatisyourfavoritenumberbetween0.0and1.0?
2.3
Isthereanythingelseyouwouldliketotellme?
No,thereisnot.

6 libraryormoduleachunkofcodethataddsextrafunctionalitytoaprogramandwhichmayormaynotbeincluded.
[Link]
[Link](javadotutildotScanner).Thislibrarycontains
functionalitythatallowsustoreadininformationfromthekeyboardorotherplaceslikefilesorthe
Internet.
Lines2through7arehopefullyboring.Online8weseesomethingelsenew:wecreateaScanner
objectnamedkeyboard.(Itdoesnthavetobenamedkeyboard;youcoulduseadifferentword
thereaslongasyouuseiteverywhereinyourcode.)ThisScannerobjectnamedkeyboardcontains
[Link]
useone.
[Link],run
yournext()[Link]
[Link],theScannerobjectwillpackageitintoa
Stringandallowyourcodetocontinue.
Online13weasktheScannerobjecttoexecuteitsnextInt()[Link],
waitsforthehumantotypesomethingandpressEnter,thenpackagesitintoanintegervalue(if
possible)andcontinues.
Whatifthehumandoesnttypeanintegerhere?Tryrunningtheprogramagainandtype41.9asthe
answertothesecondquestion.
Theprogramblowsupanddoesntrunanyotherstatementsbecause41.9cannotbepackagedintoan
integervalue:[Link]
likethis,butinthemeantime,ifthehumantypesinsomethingincorrectlywhichblowsupourprogram,
wewillblamethehumanfornotfollowingdirectionsandnotworryaboutit.
Line16letsthehumantypeinsomethingwhichtheScannerobjectwillattempttoconvertintoadouble
value,andline19letsthehumantypeinaString.(AnythingcanbepackagedasaString,including
numbers,sothisisntlikelytofail.)
Tryrunningtheprogramseveralmoretimes,noticingwhenitblowsupandwhenitdoesnt.
Exercise8:StoringtheHumansResponses
Inthelastexercise,youlearnedhowtopausetheprogramandallowthehumantotypeinsomething.
Butwhathappenedtowhatwastyped?WhenyoutypedintheanswerParisforthefirstquestion,
wheredidthatanswergo?Well,itwasthrownawayrightafteritwastypedbecausewedidntputany
[Link].
[Link];
2
3publicclassRudeQuestions
4{
5publicstaticvoidmain(String[]args)
6{
7Stringname;
8intage;
9doubleweight,income;
10
11Scannerkeyboard=newScanner([Link]);
12
[Link]("[Link]?");
14name=[Link]();
15
[Link]("Hi,"+name+"!Howoldareyou?");
17age=[Link]();
18
[Link]("Soyou're"+age+",eh?That'snotoldatall.");
[Link]("Howmuchdoyouweigh,"+name+"?");
21weight=[Link]();
22
[Link](weight+"![Link],what'syourincome,"+
name+"?");
24income=[Link]();
25
[Link]("Hopefullythatis"+income+"perhourandnotperyear!");
[Link]("Well,thanksforansweringmyrudequestions,"+name+".");
28}
29}

([Link]'twanttomakethefonttinyjustonaccountofthatoneline.
Justtypeitallononelinelikeusual.)
Justlikethelastexercise,whenyoufirstrunthisyourprogramwillonlydisplaythefirstquestionand
thenpause,waitingforaresponse:
[Link]?
Noticethatbecausethatfirstprintingstatementonline13isprint()ratherthanprintln(),the
[Link](),thecursor
wouldblinkonthebeginningofthenextlineinstead.

WhatYouShouldSee
[Link]?Brick
Hi,Brick!Howoldareyou?25
Soyou're25,eh?That'snotoldatall.
Howmuchdoyouweigh,Brick?192
192.0![Link],what'syourincome,Brick?8.75
Hopefullythatis8.75perhourandnotperyear!
Well,thanksforansweringmyrudequestions,Brick.
Atthetopoftheprogramwedeclaredfourvariables:oneStringvariablenamedname,oneinteger
variablenamedage,andtwodoublevariablesnamedweightandincome.
[Link]()thatweknowfromthepreviousexercisewillpausethe
[Link]
Stringtheytypego?Inthiscase,[Link]
[Link].
So,assumingyoutypeBrickforyourname,theStringvalue"Brick"getsstoredintothevariable
nameonline14.Thismeansthatonline16,wecandisplaythatvalueonthescreen!Thatsprettycool,
ifyouaskme.
Online17weasktheScannerobjecttoletthehumantypeinsomethingwhichitwilltrytoformatasan
integer,[Link]
thescreenonline19.
Line21readsinadoublevalueandstoresitintoweight,andline24readsinanotherdoublevalueand
storesitintoincome.
[Link],wecannow
letthehumantypeininformation,andwecanrememberitinavariabletouselaterintheprogram!
BeforeIwrapup,noticeforexamplethatthevariableincomeisdeclaredallthewayuponline9(we
chooseitsnameandtype),butitisundefined(itdoesnthaveavalue)untilline24.Online24incomeis
finallyinitialized(givenitsfirstvalueoftheprogram).Ifyouhadattemptedtoprintthevalueofincome
onthescreenpriortoline24,theprogramwouldnothavecompiled.
Anyway,playwithtypingindifferentanswerstothequestionsandseeifyoucangettheprogramto
blowupaftereachquestion.
Exercise9:CalculationswithUserInput
Nowthatweknowhowtogetinputfromtheuserandstoreitintovariablesandsinceweknowhowto
dosomebasicmath,wecannowwriteourfirstusefulprogram!
[Link];
2
3publicclassBMICalculator
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8doublem,kg,bmi;
9
[Link]("Yourheightinm:");
11m=[Link]();
12
[Link]("Yourweightinkg:");
14kg=[Link]();
15
16bmi=kg/(m*m);
17
[Link]("YourBMIis"+bmi);
19}
20}

WhatYouShouldSee
Yourheightinm:1.75
Yourweightinkg:73
YourBMIis23.836734693877553
Thisexerciseis(hopefully)[Link](alldoubles):m(meters),kg
(kilograms)andbmi(bodymassindex).Wereadinvaluesformandkg,butbmisvaluecomesnotfrom
thehumanbutastheresultofacalculation.Online16wecomputethemassdividedbythesquareof
[Link].
Thebodymassindex(BMI)iscommonlyusedbyhealthandnutritionprofessionalstoestimatehuman
[Link]
wecandowithit.
EventuallywewilllearnhowtodisplayadifferentmessageonthescreendependingonwhattheBMI
equals,butfornowthiswillhavetodo.
Aprettyeasyassignmentfortoday,butIhavesomechallengesforyouintheStudyDrillsthatshould
makethingsabittougher.

StudyDrills
1. Addsomevariablesandchangetheprogramsothatthehumancaninputtheirweightandheight
usingpoundsandinches,andthenconvertthosevaluestokilogramsandmeterstofigurethe
BMI.
Yourheightininches:69
Yourweightinpounds:160
YourBMIis23.625289

[Link].
Yourheight(feetonly):5
Yourheight(inches):9
Yourweightinpounds:160
YourBMIis23.625289
Exercise10:VariablesOnlyHoldValues
Okay,nowthatwecangetinputfromthehumananddocalculationswithit,Iwanttocallattentionto
[Link],butit
probablywillnotworkthewayyouexpect.
[Link](thepartofthe
codethecompilercaresabout),anditisnotaruntimeerrorlikeyougetwhenthehumantypesadouble
[Link]
theflowofinstructions,sothattheoutputisnotwhatIwastryingtoaccomplish.
[Link];
2
3publicclassSequencing
4{
5publicstaticvoidmain(String[]args)
6{
7//BROKEN
8
9Scannerkeyboard=newScanner([Link]);
10doubleprice=0,salesTax,total;
11
12salesTax=price*0.0825;
13total=price+salesTax;
14
[Link]("Howmuchisthepurchaseprice?");
16price=[Link]();
17
[Link]("Itemprice:\t"+price);
[Link]("Salestax:\t"+salesTax);
[Link]("Totalcost:\t"+total);
21}
22}

WhatYouShouldSee
Howmuchisthepurchaseprice?7.99
Itemprice:7.99
Salestax:0.0
Totalcost:0.0
Areyousurprisedbytheoutput?Didyouexpectthesalestaxon$7.99toshowsomethinglike$0.66
insteadofabigfatzero?Andthetotalcostshouldhavebeensomethinglike$8.65,right?What
happened?
WhathappenedisthatinJava(andmostprogramminglanguages),variablescannotholdformulas.
Variablescanonlyholdvalues.
[Link]*0.0825intothe
[Link]
online19whenweprintoutsalesTaxthatthecomputerthenrunstheformulasomehow.
[Link],[Link]
[Link]
sneakyonline10.
Normallywehavebeendeclaringvariablesupatthetopofourprogramsandtheninitializingthem
[Link]
avariableatthesametime,[Link]
line10,justdeclared.
Sothenonline16thevaluethehumantypesindoesntinitializeprice;pricealreadyhasaninitialvalue
(0).Butthevaluethehumantypesin(7.99orwhatever)doesgetstoredintothevariablepricehere.
The0isreplacedwith7.99.
Fromline10until15thevariablepricecontainsthevalue0.Whenline16beginsexecutingandwhile
wearewaitingforthehumantotypesomething,pricestillcontains0.Butbythetimeline16has
completed,whateverthehumantypedhasbeenstoredintoprice,replacingthezero.Thenfromline17
untiltheendoftheprogram,thevariablepricecontainsthevalue7.99(orwhatever).
Sowiththisinmind,wecanfigureoutwhatreallyhappensonline12.Line12doesnotstoreaformula
[Link]?Ittakesthevalueofthevariablepriceatthispoint
inthecode(whichis0),multipliesitby0.0825(whichisstillzero),andthenstoresthatzerointo
salesTax.
Asline12isbeginning,thevalueofsalesTaxisundefined.(salesTaxisdeclaredbutnotdefined.)By
theendofline12,[Link](thereisno
lineofcodethatbeginswithsalesTax=),sothatvalueneverchangesandsalesTaxisstillzerowhen
itisdisplayedonline19.
[Link](zero)andaddsittothevalueofsalesTaxright
then(alsozero)andstoresthesum(zero)[Link],and
totaldoesnotsomehowrememberthatitsvaluecamefromaformulainvolvingsomevariables.
[Link],[Link],they
areasequenceofinstructionsthatthecomputerexecutesinorder,andthingslaterinyourcodedepend
onwhathappenedbefore.

StudyDrills
1. Removethe=0online10,sothatpricenolongergetsdefinedonline10,onlydeclared.
Whathappenswhenyoutrytocompilethecode?Doestheerrormessagemakesense?(Nowput
the=0backsothattheprogramcompilesagain.)
2. MovethetwolinesofcodethatgivevaluestosalesTaxandtotalsotheyoccurafterpricehas
[Link].
3. Nowthattheselinesoccurafterthevariablepricehasbeenproperlygivenarealvalue,try
removingthe=[Link]?Areyousurprised?
Exercise11:VariableModificationShortcuts
Thevalueofavariablecanchangeovertimeasyourprogramruns.(Itwontchangeunlessyouwrite
codetochangeit,butitcanchangeiswhatImsaying.)
Infact,[Link].
Forexample,letssaythevariablexcontainsthevalue10.Wewanttoadd2toitsothatxnow
contains12.
Wecandothis:
intx=10,temp_x;
temp_x=x+2;
x=temp_x;
Thiswillwork,[Link],wecantakeadvantageofthefactthatavariablecanhave
[Link]
writesomethinglikethis:
intx=10;
x=2+x;
[Link](10),add2toit,andstorethesum
(12)intothevariablex.Sowhenthesecondlineofcodebeginsexecutingxis10,andwhenitisdone
executing,[Link],sowecanevendosomethinglikethis:
intx=10;
x=x+2;
[Link],nowtothecode!
1publicclassVariableChangeShortcuts
2{
3publicstaticvoidmain(String[]args)
4{
5inti,j,k;
6
7i=5;
8j=5;
9k=5;
10
[Link]("i:"+i+"\tj:"+j+"\tk:"+k);
12i=i+3;
13j=j3;
14k=k*3;
[Link]("i:"+i+"\tj:"+j+"\tk:"+k);
16
17i=5;
18j=5;
19k=5;
20
[Link]("\ni:"+i+"\tj:"+j+"\tk:"+k);
22i+=3;
23j=3;
24k*=3;
[Link]("i:"+i+"\tj:"+j+"\tk:"+k);
26
27i=j=k=5;
28
[Link]("\ni:"+i+"\tj:"+j+"\tk:"+k);
30i+=1;
31j=2;
32k*=3;
[Link]("i:"+i+"\tj:"+j+"\tk:"+k);
34
35i=j=k=5;
36
[Link]("\ni:"+i+"\tj:"+j+"\tk:"+k);
38i=+1;
39j=2;
[Link]("i:"+i+"\tj:"+j+"\tk:"+k);
41
42i=j=k=5;
43
[Link]("\ni:"+i+"\tj:"+j+"\tk:"+k);
45i++;
46j;
[Link]("i:"+i+"\tj:"+j+"\tk:"+k);
48
49}
50}

WhatYouShouldSee
i:5j:5k:5
i:8j:2k:15

i:5j:5k:5
i:8j:2k:15

i:5j:5k:5
i:6j:3k:15

i:5j:5k:5
i:1j:2k:5

i:5j:5k:5
i:6j:4k:5
[Link],givethemvalues,displaythem,
changetheirvaluesandprintthemagain.Thenstartingonline17wegivethevariablesthesamevalues
theystartedwithandprintthem.
Online22weseesomethingnew:[Link]+=3
meansthesameasi=i+3:takethecurrentvalueofi,add3toit,andstoretheresultasthenew
[Link],wewouldsayiplusequals3.
Online23wesee=(minusequals),whichsubtracts3fromk,andline24demonstrates*=,which
[Link]/=,whichdivideswhatevervariableisonthelefthandsidebywhatevervalue
therighthandsideendsupequaling.(Modulusequals(%=)alsoexists,whichsetsthevariableonthe
lefthandsideequaltowhatevertheremainderiswhenitspreviousvalueisdividedbywhateverison
[Link].)
[Link],jandkallto5,I
doitinoneline.(Somepeopledontapproveofthistrick,butIthinkitsfineincaseslikethis.)Line27
[Link](5)andstore
[Link],
allthreevariableshavebeenchangedtoequal5.
Lines30through32arebasicallythesameaslines22through24exceptthatwearenolongerusing3
asthenumbertoadd,subtractormultiply.
Line38mightlooklikeatypo,[Link]
insteadof+=Iwrote=+.Thiswillcompile,[Link]
seesi=+1;,thatis,[Link]
watchforthat.
Online45weseeonemoreshortcut:thepostincrementoperator.i++justmeansadd1towhatever
[Link]=i+1ori+=1.Adding1toavariableissupercommon.
(Youllsee.)Thatswhytheresaspecialshortcutforit.
Online46weseethepostdecrementoperator:j.Itsubtracts1fromthevalueinj.
[Link]
[Link],
soifyoueverreadotherpeoplescodeyouwillseetheseprettyoften.
Exercise12:BooleanExpressions
Sofarwehaveonlyseenthreetypesofvariables:
int
integers,holdnumbers(positiveornegative)withnofractionalparts
double
doubleprecisionfloatingpointnumbers(positiveornegative)thatcouldhaveafractionalpart
String
astringacharacters,holdwords,phrases,symbols,sentences,whatever
ButinthewordsofYoda:[Link](namedafterthemathematician
GeorgeBoole)[Link]:trueorfalse.
[Link]!
[Link];
2
3publicclassBooleanExpressions
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9booleana,b,c,d,e,f;
10doublex,y;
11
[Link]("[Link]:");
13x=[Link]();
[Link]("Second:");
15y=[Link]();
16
17a=(x<y);
18b=(x<=y);
19c=(x==y);
20d=(x!=y);
21e=(x>y);
22f=(x>=y);
23
[Link](x+"isLESSTHAN"+y+":"+a);
[Link](x+"isLESSTHANorEQUALTO"+y+":"+b);
[Link](x+"isEQUALTO"+y+":"+c);
[Link](x+"isNOTEQUALTO"+y+":"+d);
[Link](x+"isGREATERTHAN"+y+":"+e);
[Link](x+"isGREATERTHANorEQUALTO"+y+":"+f
);
[Link]();
31
[Link](!(x<y)+""+(x>=y));
[Link](!(x<=y)+""+(x>y));
[Link](!(x==y)+""+(x!=y));
[Link](!(x!=y)+""+(x==y));
[Link](!(x>y)+""+(x<=y));
[Link](!(x>=y)+""+(x<y));
38
39}
40}
WhatYouShouldSee
[Link]
Second:4
3.0isLESSTHAN4.0:true
3.0isLESSTHANorEQUALTO4.0:true
3.0isEQUALTO4.0:false
3.0isNOTEQUALTO4.0:true
3.0isGREATERTHAN4.0:false
3.0isGREATERTHANorEQUALTO4.0:false

falsefalse
falsefalse
truetrue
falsefalse
truetrue
truetrue
Online17theBooleanvariableaissetequaltosomethingstrange:[Link]
[Link],thenthe
[Link],thenthe
comparisonisfalseandthebooleanvaluefalseisstoredintoa.(Ithinkthatiseasiertounderstand
thanitistowrite.)
Line18issimilar,exceptthatthecomparisonislessthanorequalto,andtheBooleanresultisstored
intob.
Line19isequalto:[Link]
line20isnotequalto.Lines21and22aregreaterthanandgreaterthanorequalto,respectively.
Onlines24through29,wedisplaythevaluesofallthoseBooleanvariablesonthescreen.
Line32throughline37introducethenotoperator,whichisanexclamationpoint(!).Ittakesthe
logicalopposite.Soonline32wedisplaythelogicalnegationofxislessthany?,andwealsoprint
outthetruthvalueofxisgreaterthanorequaltoy?,whichareequivalent.(Theoppositeofless
thanisgreaterthanorequalto.)Lines33through37showtheoppositesoftheremainingrelational
operators.
Exercise13:ComparingStrings
InthisexercisewewillseesomethingthatcausestroubleforbeginnerstryingtolearnJava:theregular
relationaloperatorsdonotworkwithStrings,onlynumbers.
booleana,b;
a=("cat"<"dog");
b=("horse"=="horse");
Thesecondlinedoesntevencompile!Youcantuse<toseeifawordcomesbeforeanotherwordin
[Link],bdoesgetsettothevaluetruehere,butnotifyoureadthevalueintoa
variablelikeso:
Stringanimal;
animal=[Link]();//theusertypesin"horse"
b=(animal=="horse");
bwillalwaysgetsettothevaluefalse,nomatterifthehumantypes"horse"ornot!
[Link]
weirdbehavior,butitsnotfriendlyforbeginnersandexplainingitwouldprobablyonlyconfuseyou
moreatthispointinyourlearning.
DoyourememberwhenIwarnedyouthatJavaisnotalanguageforbeginners?
SothereisawaytocompareStringsforequality,soletslookatit.
[Link];
2
3publicclassWeaselOrNot
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9Stringword;
10booleanyep,nope;
11
[Link]("Typetheword\"weasel\",please.");
13word=[Link]();
14
15yep=[Link]("weasel");
16nope=![Link]("weasel");
17
[Link]("Youtypedwhatwasrequested:"+yep);
[Link]("Youignoredpoliteinstructions:"+nope);
20}
21}

WhatYouShouldSee
Typetheword"weasel",please.
no
Youtypedwhatwasrequested:false
Youignoredpoliteinstructions:true
[Link]()(dotequals)thatcomparesitselftoanother
String,[Link]
mustusethenotoperator(!)[Link]()methodtofindoutiftwoStringsare
different.
StudyDrills
1. Trychangingaroundthecomparisononline15sothat"weasel"isinfrontofthedotandthe
[Link]"weasel"isstillsurroundedbyquotes
[Link]?
Exercise14:CompoundBooleanExpressions
[Link]
grandmotherwhowillonlyapproveyoudatinghergrandchildifyouareolderthan25andyoungerthan
[Link]
applicantstoanswerhonestly,herprogrammightlookabitlikethis:
[Link];
2
3publicclassShallowGrandmother
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9intage;
10doubleincome,attractiveness;
11booleanallowed;
12
[Link]("Enteryourage:");
14age=[Link]();
15
[Link]("Enteryouryearlyincome:");
17income=[Link]();
18
[Link]("Howattractiveareyou,onascalefrom0.0to10.0?");
20attractiveness=[Link]();
21
22allowed=(age>25&&age<40&&(income>50000||attractiveness>=8.5));
23
[Link]("Youareallowedtodatemygrandchild:"+allowed);
25}
26}

WhatYouShouldSee
Enteryourage:39
Enteryouryearlyincome:49000
Howattractiveareyou,onascalefrom0.0to10.0?7.5
Youareallowedtodatemygrandchild:false
SowecanseethatforcomplicatedBooleanexpressionsyoucanuseparenthesestogroupthings,and
youusethesymbols&&tomeanANDandthesymbols||tomeanOR.
Iknowwhatyouarethinking:using&(anampersandorandsign)tomeanANDmakesalittle
sense,butwhytwoofthem?Andwhoseideawasittouse||(pipepipe)tomeanOR?!?
Well,KenThompsonsidea,[Link]++ssyntax,
whichwasbasicallycopiedfromCssyntax,andthatwasmodifiedfromBssyntax,
whichwasinventedbyDennisRitchieandKenThompson.
TheprogramminglanguageBused&tomeanANDand|forOR,buttheywere
bitwise:theyonlyworkedontwointegersandtheywouldwalkonebitatatime
downtheintegersdoingabitwiseANDorORoneachpairofbits,puttinga1or0in
theoutputforeachcomparison.(|wasprobablyusedbecauseitwas
mathematicallookingandwasakeyonthekeyboardsofthePDP7computerthatB
wasoriginallydevelopedfor.)
WhenKenandDennisstarteddevelopingtheprogramminglanguageCtoreplaceB,
theydecidedtherewasaneedforalogicalANDandOR,andthe
onesymbollongthingswerealreadytaken,sotheyusedtwoampersandstorepresent
[Link].
Fortunatelyforyou,[Link]
getitright.
Thisnextlittlebitisgoingtobealittlebitweird,becauseImgoingtoshowyouthetruthtablesfor
ANDandOR,andyoullhavetothinkofANDasanoperationthatisbeingperformedontwovalues
insteadofaconjunction.
HereisthetruthtableforAND:
Inputs Output(s)
A B A&&B
true true true
true false false
false true false
false false false

Youreadthetablesthisway:letspretendthatourshallowgrandmotherhasdecidedthatshewillonly
[Link]
[Link]
possiblecruiseline.
[Link]#1?Yes!
Cruiseischeapistrueandalcoholisincludedistrue,sograndmotherwillgo(A&&B)isalso
true.
Cruise#2ischeap,butthealcoholisnotincluded(statementBisfalse).Sograndmotherisnt
interested:(A&&B)isfalsewhenAistrueandBisfalse.
Clear?NowhereisthetruthtableforOR:
Inputs Output(s)
A B A||B
true true true
true false true
false true true
false false false

LetssaythatgrandmotherwillbuyacertainusedcarifitisreallycoollookingORifitgetsgreatgas
[Link],Bisgoodmilespergallonandtheresult,AORB,
determinesifitisacargrandmotherwouldwant.
Car#[Link]?
Heck,yes!WecansaythatthevaluetrueORedwiththevaluetruegivesaresultoftrue.
Infact,[Link]
falseifBOTHofitscomponentsarefalse.
StudyDrills
1. DidyouknowthatJavahasbitwiseoperators,too?Investigatehownumbersarerepresentedin
binaryandseeifyoucanfigureoutwhythefollowingcodesetsxtothevalue7andsetsytothe
value1.
intx=3|5;
inty=3&5;
Exercise15:MakingDecisionswithIfStatements
Hey![Link],soitstimetolearn
somethingthatisusefulandnotsuperdifficult.
Wearegoingtolearnhowtowritecodethathasdecisionsinit,sothattheoutputisntalwaysthesame.
Thecodethatgetsexecutedchangesdependingonwhatthehumanenters.
[Link];
2
3publicclassAgeMessages
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9intage;
10
[Link]("Howoldareyou?");
12age=[Link]();
13
14if(age<13)
15{
[Link]("YouaretooyoungtocreateaFacebook
account.");
17}
18if(age<16)
19{
[Link]("Youaretooyoungtogetadriver'slicense."
);
21}
22if(age<18)
23{
[Link]("Youaretooyoungtogetatattoo.");
25}
26if(age<21)
27{
[Link]("Youaretooyoungtodrinkalcohol.");
29}
30if(age<35)
31{
[Link]("YouaretooyoungtorunforPresidentofthe
UnitedStates.");
[Link]("Howsad!");
34}
35}
36}

WhatYouShouldSee
Howoldareyou?17
Youaretooyoungtogetatattoo.
Youaretooyoungtodrinkalcohol.
YouaretooyoungtorunforPresidentoftheUnitedStates.
Howsad!
Okay,[Link],followedbya
[Link]
[Link],andthestuffinsidethecurly
[Link].
Whentheconditionoftheifstatementistrue,allthecodeinthebodyoftheifstatementisexecuted.
Whentheconditionoftheifstatementisfalse,[Link]
manylinesofcodeasyouwantinsidethebodyofanifstatement;theywillallbeexecutedorskipped
asagroup.
NoticethatwhenIranthecode,Iputin17formyage.Because17isnotlessthan13,theconditionon
line14isfalse,andsothecodeinthebodyofthefirstifstatement(lines15through17)wasskipped.
Thesecondifstatementwasalsofalsebecause17isnotlessthan16,sothecodeinitsbody(lines19
through21)wasskipped,too.
Theconditionofthethirdifstatementwastrue:17islessthan18,sothebodyofthethirdifstatement
wasnotskipped;itwasexecutedandthephraseYouaretooyoungtogetatattoowasprintedonthe
[Link].
Thefinalifstatementcontainstwolinesofcodeinitsbody,justtoshowyouwhatitwouldlooklike.

StudyDrills
1. Ifyoutypeinanagegreaterthan35whatgetsprinted?Why?
2. Addonemoreifstatementcomparingtheirageto65.Iftheirageisgreaterthanorequalto65,
sayYouareoldenoughtoretire!.
3. Foreachifstatement,[Link],iftheirageis
greaterthanorequalto13,[Link]
aredone,yourprogramshouldshowsixmessageseverytimenomatterwhatageyouenter.
Exercise16:MoreIfStatements
[Link],becausetheyre
[Link].
[Link];
2
3publicclassComparingNumbers
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8doublefirst,second;
9
[Link]("[Link]:");
11first=[Link]();
[Link]("Second:");
13second=[Link]();
14
15if(first<second)
16{
[Link](first+"isLESSTHAN"+second);
18}
19if(first<=second)
20{
[Link](first+"isLESSTHANorEQUALTO"+second);
22}
23if(first==second)
24{
[Link](first+"isEQUALTO"+second);
26}
27if(first>=second)
28{
[Link](first+"isGREATERTHANorEQUALTO"+second);
30}
31if(first>second)
32{
[Link](first+"isGREATERTHAN"+second);
34}
35
36if(first!=second)
[Link](first+"isNOTEQUALTO"+second);
38
39}
40}

WhatYouShouldSee
[Link]
Second:4
3.0isLESSTHAN4.0
3.0isLESSTHANorEQUALTO4.0
3.0isNOTEQUALTO4.0
Online37youwillseethatIdidsomethingquestionable:thebodyofthelastifstatementdoesnothave
[Link]?
Actually,[Link],thenonlythefirstlineof
[Link],sincealltheifstatementsinthiswholeexercise
haveonlyonelineofcodeintheirbodies,alltheifstatementcurlybracesinthisexerciseareoptional.
[Link],though,
andsomeprogrammersalwaysputcurlybracesnomatterwhat.
StudyDrills
1. [Link]("Hey.");.
Indentitsothatitlinesupwiththeprintln()statementaboveit,likeso:
if(first!=second)
[Link](first+"isNOTEQUALTO"+second);
[Link]("Hey.");
Runtheprogram,[Link]?Thatis,whentheif
statementisskipped,istheHeyskipped,too,ordoesitrunnomatterwhat?Whatdoyouthink?
1. AddcurlybracesaroundthebodyofthefinalifstatementsothattheHeylineispartofthe
[Link]
[Link].
Exercise17:Otherwise(IfStatementswithElse)
So,[Link],andyouusethem
[Link],ifstatementsalonearefunctionalenoughthatyoucoulddoalotjustusingif
statements.
Butsometimes,[Link]:
quick!Whatisthelogicaloppositeofthefollowingexpression?
if(onGuestList||age>=21||([Link]("F")&&attractiveness>=8))
Eh?Gotityet?Well,ifyousaid
if(!(onGuestList||age>=21||([Link]("F")&&attractiveness>=8)))

[Link]
[Link]
if(!onGuestList&&age<21&&(![Link]("F")||attractiveness<8))

[Link]
logicaloppositeofthis:
if(expensiveDatabaseThatTakes45SecondsToLookup(userName,password)==true)
Dowereallywanttowrite
if(expensiveDatabaseThatTakes45SecondsToLookup(userName,password)==false)
[Link]
fortunately,programminglanguagesgiveussomethingelse.(Yeah,[Link].)
[Link];
2
3publicclassClubBouncer
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9intage=22;
10booleanonGuestList=false;
11doubleattractiveness=7.5;
12Stringgender="F";
13
14if(onGuestList||age>=21||([Link]("F")&&
attractiveness>=8))
15{
[Link]("Youareallowedtoentertheclub.");
17}
18else
19{
[Link]("Youarenotallowedtoentertheclub.");
21}
22}
23}

WhatYouShouldSee
Youareallowedtoentertheclub.
Sowhatthekeywordelsemeansisthis:[Link]
ifstatementtrue?Ifso,[Link],however,thenthebodyofthe
[Link],[Link](else),
runthisdifferentblockofcodeinstead.
Elseissuperconvenientbecausethenwedonthavetofigureoutthelogicaloppositeofsomecomplex
[Link].
Anelseisonlylegalimmediatelyafteranifstatementends.(Technicallyitisonlyallowedafterthe
closingoftheblockofcodethatisthebodyofanifstatement.)

StudyDrills
1. Betweenline17and18,addaprintln()statementtoprintsomethingonthescreen(it
doesntmatterwhat,butIput"CCCCOMBOBREAKER"becauseImweird.)Tryto
[Link]?Whynot?
Exercise18:IfStatementswithStrings
[Link]
reviewwithanexampleyoucanactuallytestout.
[Link];
2
3publicclassSecretWord
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9Stringsecret="please",guess;
10
[Link]("What'sthesecretword?");
12guess=[Link]();
13
14if(guess==secret)
15{
[Link]("Impossible.(Thiswillneverbeprinted.)");
17}
18
19if([Link](secret))
20{
[Link]("That'scorrect!");
22}
23else
24{
[Link]("Nope,thesecretwordisnot\""+guess+
"\".");
26}
27
28}
29}

WhatYouShouldSee
What'sthesecretword?abracadabra
Nope,thesecretwordisnot"abracadabra".
NoticethatasusualImsneakingsomethingin.Online9insteadofjustdeclaringsecretIalsogaveita
[Link],Idefinedit(declaredandinitializedallatonce).
Anyway,[Link],itwill
neverbethecasethatguess==secret.
(Icantreallyexplainwhywithoutgoingintowaytoomuchdetail,butithastodo
withthefactthat==onlycomparestheshallowvaluesofthevariables,andthe
shallowvaluesoftwoStringsareonlyequalwhentheyrefertothesamememory
location.)
[Link]()method(whichcomparesthedeepvaluesofthevariables
insteadoftheirshallowvalues).Thiswillbetrueiftheytypethecorrectsecretword.
Exercise19:MutualExclusionwithChainsofIfandElse
Inthepreviousexercise,wesawhowusingelsecanmakeiteasiertoincludeachunkofalternative
codethatyouwanttorunwhenanifstatementdidnothappen.
Butwhatifthealternativecodeisanotherifstatement?
[Link];
2
3publicclassBMICategories
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9doublebmi;
10
[Link]("EnteryourBMI:");
12bmi=[Link]();
13
[Link]("BMIcategory:");
15if(bmi<15.0)
16{
[Link]("veryseverelyunderweight");
18}
19elseif(bmi<=16.0)
20{
[Link]("severelyunderweight");
22}
23elseif(bmi<18.5)
24{
[Link]("underweight");
26}
27elseif(bmi<25.0)
28{
[Link]("normalweight");
30}
31elseif(bmi<30.0)
32{
[Link]("overweight");
34}
35elseif(bmi<35.0)
36{
[Link]("moderatelyobese");
38}
39elseif(bmi<40.0)
40{
[Link]("severelyobese");
42}
43else
44{
[Link]("veryseverely/\"morbidly\"obese");
46}
47}
48}

WhatYouShouldSee
EnteryourBMI:22.5
BMIcategory:normalweight
(Note:AlthoughBMIisaverygoodestimateofhumanbodyfat,theformuladoesntworkwellfor
athleteswithalotofmuscle,[Link]
yourBMI,checkwithyourdoctor.)
Noticethateventhoughseveraloftheifstatementsmighthaveallbeentrue,onlythefirsttrueif
[Link]:[Link]
ofusingelsewithif.
Online15thereisanifstatementthatchecksifyourBMIislessthan15.0,andifso,displaysthe
propercategoryforthatbodymassindex.
[Link]
[Link]
of22.5,[Link]
failed,theelsewillautomaticallyexecuteitsbodyofcode.
However,thatbodyofcodestartsrightafterthewordelsewithanewifstatement!Thismeansthat
thestatementif(bmi<=16.0)willonlybeconsideredwhenthepreviousifstatementwas
false.
Whenevermystudentsareconfusedaboutthis,IhaveananalogyIgivethem.(Itsalittlecrude,butit
seemstohelp.)
Imaginethatyouaresingle(romantically,Imean)andthatyouandsomeofyourfriendsareoutinabar
[Link],youseeareallyattractivesinglepersonandunderyourbreath
youtelltheothers:Okay,[Link].
[Link]
seemtobemakingprogress,[Link],youget
rejectedthenoneofyourothercompanionsfeelsclearedtotryandmakeaplay.
[Link](anifstatementwith
anelseinfrontoftheif)[Link]
meansthattheifstatementwillonlychecktoseeifitistrueorfalseassumingtheprecedingif
statement(andonlytheimmediatelyprecedingone)wasfalse.
Theelseonline23makesthatifstatementdefertotheifstatementthatstartsonline19:ifits
true,theline23ifstatementwillskipevenifitwouldhavebeentrueonitsown.Theelseonline27
makesitsifstatementdefertothepreviousifstatement,[Link]
line43islikethesmallestdoginapack:itonlygetsashotifallthepreviousifstatementsinthechain
werefalse.
Welltalkalittlebitmoreaboutthisinthenextexercise,sothatsenoughfornow.

StudyDrills
1. [Link],andenter
15.5fortheBMI.Doyouseehowthatmakestheifstatementonline27breakrankandno
longercareabouttheifstatementsbeforeit?
2. InsteadofmakingthehumanentertheirBMIdirectly,allowthemtotypeintheirheightand
weightandcomputetheBMIforthem.
Exercise20:MoreChainsofIfsandElse
Okay,letslookalittlemoreatmakingchainsofconditionsusingelseandif.
Aconfession:[Link]
relyontheoutputofthisprogramwhendecidingwhetherornottoapplytoabackupschool.
[Link];
[Link].*;
3
4publicclassCollegeAdmission
5{
6publicstaticvoidmain(String[]args)
7{
8Scannerkeyboard=newScanner([Link]);
9intmath;
10
[Link]("WelcometotheUTAustinCollegeAdmissions
Interface!");
[Link]("PleaseenteryourSATmathscore(200800):");
13math=[Link]();
14
[Link]("Admittancestatus:");
16
17if(math>=790)
[Link]("CERTAIN");
19elseif(math>=710)
[Link]("SAFE");
21elseif(math>=580)
[Link]("PROBABLE");
23elseif(math>=500)
[Link]("UNCERTAIN");
25elseif(math>=390)
[Link]("UNLIKELY");
27else//below390
[Link]("DENIED");
29
[Link]();
31}
32}

WhatYouShouldSee
WelcometotheUTAustinCollegeAdmissionsInterface!
PleaseenteryourSATmathscore(200800):730
Admittancestatus:SAFE
Now,beforeIgointothenewthingforthisexercise,IshouldexplainashortcutItookinthisprogram.
Didyounoticetherewasasecondimportstatementatthetop?Ifnot,thenyourcodedidntcompile
[Link]
everywhere.
Well,Idontwanttotalkmuchaboutobjectorientedcodeinthisbook,sincethatsseverelynot
beginnerfriendly,[Link]
[Link]()
andonecalledprintln().
[Link]
printlninsidetheobjectnamedoutwhichisinsidetheobjectnamedSystem(whichisitselfpart
[Link]).
Becauseofthis,Icancreateavariablenamedout,anditwontbeaproblem:
Stringout;
Eventhoughtheresanobjectnamedoutinexistencesomewhere,itsinsidetheSystemobjectsothe
namesdontconflict.
IfIamlazyanddonthaveanydesiretohavemyownvariablenamedout,thenIcanaskthecomputer
[Link]
namespace:
[Link].*;
[Link]!
InthisexerciseIalsoomittedallthecurlybracesthatdelimittheblocksofcodethatareinthebodiesof
[Link]
statement,[Link]
curlybracesback.
Anyway,inthepreviousexerciseIwroteabouthowputtingelseinfrontofanifstatementmakesit
[Link],the
currentoneskipsautomatically(andalltherestoftheelseifstatementsinthechainwillskip,too).
Thishastheeffectofmakingitsothatonlythefirsttruevaluetriggerstheifstatementandalltherest
[Link]:exactlyoneofthemwill
[Link],nevermorethanone.
[Link]
onlyworksproperlybecauseIputtheifstatementsinthecorrectorder.
Sincethefirstonethatistruewillgoandtheotherswillnot,youneedtomakesurethattheveryfirst
[Link],andsoon,with
[Link],andyou
willseehowthiscanmessthingsup.
Also,technically,elsestatementsshouldhavecurlybraces,justlikeifstatementsdo,andbyputting
[Link]
[Link]
[Link]
elseinfrontofanif;[Link].
[Link];
[Link].*;
3
4publicclassCollegeAdmissionExpanded
5{
6publicstaticvoidmain(String[]args)
7{
8Scannerkeyboard=newScanner([Link]);
9intmath;
10
[Link]("WelcometotheUTAustinCollegeAdmissions
Interface!");
[Link]("PleaseenteryourSATmathscore(200800):");
13math=[Link]();
14
[Link]("Admittancestatus:");
16
17if(math>=790)
18{
[Link]("CERTAIN");
20}
21else
22{
23if(math>=710)
24{
[Link]("SAFE");
26}
27else
28{
29if(math>=580)
30{
[Link]("PROBABLE");
32}
33else
34{
35if(math>=500)
36{
[Link]("UNCERTAIN");
38}
39else
40{
41if(math>=390)
42{
[Link]("UNLIKELY");
44}
45else//below390
46{
[Link]("DENIED");
48}
49}
50}
51}
52}
[Link]();
54}
55}
[Link].

StudyDrills
1. Intheoriginalcodefile([Link]),removealltheelsesexceptforthe
[Link].
2. [Link]
howtheprogramalmostalwaysjustsays"UNLIKELY"becausemostSATscoresaremorethan
390andtheifstatementissohighinthelistthatitstealstheshowmostofthetime.
3. Ifyouwant,[Link]
worksthesameasthenonexpandedversion.
Exercise21:NestedIfStatements
Yousawaglimpseofthisinthepreviousexercise,butyoucanputjustaboutanythingyoulikeinside
[Link],andanif
statementwhichisinsideanotheriscalledanestedif.
Heresanexampleofusingthattodosomethinguseful.
[Link];
2
3publicclassGenderTitles
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9Stringtitle;
10
[Link]("Firstname:");
12Stringfirst=[Link]();
[Link]("Lastname:");
14Stringlast=[Link]();
[Link]("Gender(M/F):");
16Stringgender=[Link]();
[Link]("Age:");
18intage=[Link]();
19
20if(age<20)
21{
22title=first;
23}
24else
25{
26if([Link]("F"))
27{
[Link]("Areyoumarried,"+first+"?(Y/N):");
29Stringmarried=[Link]();
30if([Link]("Y"))
31{
32title="Mrs.";
33}
34else
35{
36title="Ms.";
37}
38}
39else
40{
41title="Mr.";
42}
43}
44
[Link]("\n"+title+""+last);
46
47}
48}

WhatYouShouldSee
Firstname:Graham
Lastname:Mitchell
Gender(M/F):M
Age:39

[Link]

[Link]
noticewhatIdiddifferentlythistime?
NormallyIdeclareallmyvariablesatthetopoftheprogramandgivethemvalues(orinitializethem)
[Link],I
declaredallmyvariables(excepttitle)onthesamelineIputavalueintothemforthefirsttime.
WhydidntIdeclaretitleonline22,then?[Link]
[Link]
[Link]
thevariablegoesoutofscopeandcantbeusedanymore.
Letuslookatanexample:online29Idefined(declaredandinitialized)aStringvariablecalled
[Link]
[Link]
marriedisnotinscopeanywhereelseintheprogram;referringtoitonlines1through28oronlines39
through48wouldgiveacompilererror.
ThisiswhyIhadtodeclaretitletowardsthebeginningoftheprogram.IfIhaddeclareditonline22,
thenthevariablewouldhavegoneoutofscopeonelinelater,whentheclosecurlybraceofthe
youngerthan20blockoccurred.BecauseIneedtitletobevisibleallthewaydownthroughline45,I
needtomakesureIdeclareitinsidetheblockofcodethatendsonline47.
Icouldhavewaiteduntilline19todeclareit,though.
Anyway,theresnotmuchelseinterestingtosayaboutthisexerciseexceptthatitdemonstratesnesting
[Link],though.

StudyDrills
1. Changetheelseonline39toasuitableifstatementinstead,like:
if([Link]("M"))
[Link]?
Itisbecausethevariabletitleisdeclaredonline9butisnotgivenavaluerightaway.Thenonline45,
[Link],orwewillbe
tryingtodisplaythevalueofavariablethatisundefined:[Link]
this.

Whenline39wasanelse,thecompilercouldguaranteethatnomatterwhatpaththroughthenested
ifstatementswastaken,[Link],
thereisnowawaythehumancouldtypesomethingtogetittosneakthroughallthenestedif
[Link]?
(Theycouldtypeanage20orgreaterandaletterdifferentthan"M"or"F"whenpromptedforgender.
Thenneithergenderifstatementwouldbetrue.)
Wecanfixthisbychangingtheifstatementbacktoelse(probablyagoodidea)orbyinitializing
titlerightwhenwedeclareit(probablyagoodideaanyway):
Stringtitle="error";
[Link],andthecompilerishappy.
Exercise22:MakingDecisionswithaBigSwitch
[Link]
[Link],butyoushouldbefamiliarwiththemanywayincaseyou
readsomeoneelsescodethatusesone.
[Link];
2
3publicclassThirtyDays
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9intmonth,days;
10StringmonthName;
11
[Link]("Whichmonth?(112)");
13month=[Link]();
14
15switch(month)
16{
17case1:monthName="January";
18break;
19case2:monthName="February";
20break;
21case3:monthName="March";
22break;
23case4:monthName="April";
24break;
25case5:monthName="May";
26break;
27case6:monthName="June";
28break;
29case7:monthName="July";
30break;
31case8:monthName="August";
32break;
33case9:monthName="September";
34break;
35case10:monthName="October";
36break;
37case11:monthName="November";
38break;
39case12:monthName="December";
40break;
41default:monthName="error";
42}
43
44/*ThirtydayshathSeptember
45April,JuneandNovember
46Alltheresthavethirtyone
47Exceptthesecondmonthalone....
48*/
49
50switch(month)
51{
52case9:
53case4:
54case6:
55case11:days=30;
56break;
57case2:days=28;
58break;
59default:days=31;
60}
61
[Link](days+"dayshath"+monthName);
63
64}
65}

WhatYouShouldSee
Whichmonth?(112)4
30dayshathApril
[Link]
parenthesesisasinglevariable(oranexpressionthatsimplifiestoasinglevalue).Thentheresanopen
curlybrace.
Insidethebodyoftheswitchstatementareseveralcasestatementsthatbeginwiththekeyword
[Link](:).You
dontseecolonsveryofteninJava.
Afterthecase,[Link]
[Link]
[Link].
Whenaswitchstatementruns,thecomputerfiguresoutthecurrentvalueofthevariableinsidethe
[Link],oneatatime,[Link]
matchitmovesfromtheleftsidewherethecasesaretotherightsideandstartsrunningcodeuntilitis
stoppedbyabreak.
Ifnoneofthecasesmatchandthereisadefaultcase(itsoptional),thenthecodeinthedefault
casewillberuninstead.
Thesecondexamplestartsonline50anddemonstratesthatoncetheswitchstatementfindsacasethat
matches,[Link]
fromonecasetoanother.
Wecantakeadvantageofthisfallthroughbehaviortodocleverthingssometimes,likethecodeto
[Link],April,JuneandNovemberallhave30days,
wecanjustputalltheircasesinarowandletitfallthroughforanyofthosetorunthesamething.
Anyway,IwontuseswitchstatementsagaininthisbookbecauseIjustvirtuallyneverfindagood
useforthem,butitdoesexistandatleastIcansaythatyousawit.

StudyDrills
1. Removesomeofthebreakstatementsinthefirstswitchandaddsomeprintln()
statementstoconfirmthatitwillsetmonthNametoonevaluethenanotherthenanotheruntilit
finallygetsstoppedbyabreak.
Exercise23:MoreStringComparisons
Well,youhavelearnedthatyoucantcompareStringswith==;[Link]()
[Link].
[Link];
2
3publicclassDictionaryOrder
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9Stringname;
10
[Link]("Givemethenameofamadeupprogramminglanguage:
");
12name=[Link]();
13
14if([Link]("c++")<0)
[Link](name+"comesBEFOREc++");
16if([Link]("c++")==0)
[Link]("c++isn'tamadeuplanguage!");
18if([Link]("c++")>0)
[Link](name+"comesAFTERc++");
20
21if([Link]("go")<0)
[Link](name+"comesBEFOREgo");
23if([Link]("go")==0)
[Link]("goisn'tamadeuplanguage!");
25if([Link]("go")>0)
[Link](name+"comesAFTERgo");
27
28if([Link]("java")<0)
[Link](name+"comesBEFOREjava");
30if([Link]("java")==0)
[Link]("javaisn'tamadeuplanguage!");
32if([Link]("java")>0)
[Link](name+"comesAFTERjava");
34
35if([Link]("lisp")<0)
[Link](name+"comesBEFORElisp");
37if([Link]("lisp")==0)
[Link]("lispisn'tamadeuplanguage!");
39if([Link]("lisp")>0)
[Link](name+"comesAFTERlisp");
41
42if([Link]("python")<0)
[Link](name+"comesBEFOREpython");
44if([Link]("python")==0)
[Link]("pythonisn'tamadeuplanguage!");
46if([Link]("python")>0)
[Link](name+"comesAFTERpython");
48
49if([Link]("ruby")<0)
[Link](name+"comesBEFOREruby");
51if([Link]("ruby")==0)
[Link]("rubyisn'tamadeuplanguage!");
53if([Link]("ruby")>0)
[Link](name+"comesAFTERruby");
55
56if([Link]("visualbasic")<0)
[Link](name+"comesBEFOREvisualbasic");
58if([Link]("visualbasic")==0)
[Link]("visualbasicisn'tamadeuplanguage!");
60if([Link]("visualbasic")>0)
[Link](name+"comesAFTERvisualbasic");
62}
63}

WhatYouShouldSee
Givemethenameofamadeupprogramminglanguage:juniper
junipercomesAFTERc++
junipercomesAFTERgo
junipercomesAFTERjava
junipercomesBEFORElisp
junipercomesBEFOREpython
junipercomesBEFOREruby
junipercomesBEFOREvisualbasic
(OfcourseIcouldntresistslippinginsomething.Online12insteadofusingtheScannerobjects
.next()methodtoreadinaString,[Link]()methodtoreadina
[Link]()willstopreadingifyoutypeaspace,soifyoutyped"visual
basic"itwouldonlyreadin"visual"[Link]()it
readsineverythingyoutypeincludingspacesandtabsupuntilyoupressEnterandputsitallinto
onelongStringandstoresitintothevariablename.)
[Link]()[Link]
.compareTo()methoddoesntworkthewayyouprobablyexpect,butthereisgeniusinhowit
works.
[Link]().The
[Link]!Ifwecallthe
firstoneselfandthesecondoneotheritwouldlooklikethis:
intn=[Link](other);
[Link](thesamelengthandeverycharacterthe
same),[Link],thennwouldbesettoa
negativenumber(anumberlessthan0).Andifselfcomesafterotheralphabetically,thennwouldbeset
toapositivenumber(anumbergreaterthan0).
Thegeniuspartisthis:[Link]()givesusanintegerinsteadofjustaBooleantrueor
false,weonlyneedthisonemethodtodoallthecomparisons:lessthan,greaterthan,lessthanorequal
to,whatever.
Sinceifselfisequaltootherwewouldgetzeroandsinceifselfislessthanotherwewouldgeta
numberlessthanzero,wecanwrite:
if([Link](other)<=0)
Iftheresultislessthanzerotheifstatementwouldbetrueandiftheresultisequaltozerotheif
[Link]
if(self<=other)
[Link]()[Link],
ifyouaskme.
if([Link](other)<0)//truewhenself<other
if([Link](other)<=0)//truewhenself<=other
if([Link](other)>0)//truewhenself>other
if([Link](other)>=0)//truewhenself>=other
if([Link](other)==0)//truewhenself==other
if([Link](other)!=0)//truewhenself!=other
[Link],andslightlyhardertousebutnotbadatallonceyou
getusedtoit.
Theotherdifficultyhere([Link]()thing,ithappenseverywhereincode
unlessyouwritecodetofixit)isthatcapitalizationmatters."Bob"isnotthesamevalueas"bob".
AndwhatsworseisthatbecauseoftheUnicodevalues7oftheletters,"Bob"comesbefore"bob"
[Link],therearealotofways,butIlikeoneofthesetwo:
if([Link]().compareTo([Link]())<0)//or
if([Link](other)<0)
Oryoucanletthehumantypeinwhatevertheywantandconvertittolowercaserightawayandthen
onlycompareittolowercasethingsinyourcode.

StudyDrills
1. Usingthemethodofyourchoice,makethisprogramworkcorrectlyevenifthehumantypesin
wordswiththewrongcapitalization.

7 [Link],butthereisabiggianttablethatmapsevery
characterineverylanguageevertooneof1,112,063numbersthatuniquelyidentifiesthatcharacter.TheUTF8Unicode
valueoftheletter"B"is66;thevalueoftheletter"b"is98.
Exercise24:ChoosingNumbersRandomly
Weregoingtospendafewexercisesonsomethingyoudontalwaysseeinprogrammingbooks:howto
[Link]
[Link],havingrandom
numberswillletusmakesomesimpleinteractivegames,andthatiseasilyworththepainofthisslightly
weirdconcept.
1publicclassRandomNumbers
2{
3publicstaticvoidmain(String[]args)
4{
5inta,b,c;
6doublex,y,z;
7
8x=[Link]();
9y=[Link]();
10z=[Link]();
11
[Link]("xis"+x);
[Link]("yis"+y);
[Link]("zis"+z);
15
16x=[Link]()*100;
17y=[Link]()*100;
18z=[Link]()*100;
19
[Link]("\nxis"+x);
[Link]("yis"+y);
[Link]("zis"+z);
23
24a=(int)x;
25b=(int)y;
26c=(int)z;
27
[Link]("\nais"+a);
[Link]("bis"+b);
[Link]("cis"+c);
31
32x=0.9999999999999999;
33a=(int)(x*100);
34
[Link]("\nxis"+x);
[Link]("ais"+a);
37
38x=[Link]();
39a=0+(int)(x*10);
40b=1+(int)(x*10);
41c=5+(int)(x*10);
42
[Link]("\nais"+a);
[Link]("bis"+b);
[Link]("cis"+c);
46}
47}

WhatYouShouldSee
xis0.5371428668784091
yis0.4716636154720313
zis0.9791002546275134
xis57.33269918363617
yis44.731436970719386
zis75.79286027183542

ais57
bis44
cis75

xis0.9999999999999999
ais99

ais6
bis7
cis11
Note:[Link],remember?
[Link]().Everytimeyoucallthefunction,itwillproducea
newrandomdoubleintherange[0,1)(thatis,itmightbeexactly0butwillneverbeexactly1and
[Link]:
doublex=[Link]();
thenxcouldhaveavalueof0,or0.123544,or0.3,or0.999999999butnever1.0andnever
[Link]()iscalledthreetimes,andthe
[Link].
Unfortunately,Idontoftenwantadoublefrom[0,1).Imagineanumberguessinggamewhereyousay
Iamthinkingofanumberwithdecimalsbetweenzeroandone:trytoguessit![Link]
[Link]()givesus,sowehavetomushitintoarange
ourselves.
Onlines16through18wepickanewrandomnumber,butwemultiplyitby100beforestoringitintoa
variable.(Thishastheeffectofmovingthedecimaltwoplacevaluestotheright.)Sowecantellthatthe
originalrandomnumberprintedoutonline20was0.5733269918363617becauseitis
57.33269918363617afterbeingmultipliedby100.
[Link]
[Link]
somethinglike12.3544,or30.0,or99.9999999butnever100.0andneveranythinggreater
than100.
[Link]
double:[Link]:itcanholdwholenumbersonly.
[Link]
[Link]
[Link]?Itisokayifyouhavetothrow
[Link].
Soonline24thecomputermakesacopyofthevaluefromxbuteverythingafterthedecimalpointis
choppedoffandthrownaway(truncated)andthatnewintegervalueisstoredintothevariablea.(The
valueofxisunchanged.)Thevalueisnotrounded;itstruncated.
Theoreticallywhatdoesthisgiveus?Ifxwasoriginally0or12.3544or30.0,or99.9999999,
[Link],bandcwillalways
haveintegervaluesfrom0to99.
Onlines32and33Ihaveattemptedtoshowthatcastingfromadoubletoanintegerdoesnotround;the
numbersafterthedecimalpointaretruncated.
Finally,onlines38through41asinglerandomnumberischosen.Inallthreecasesitismultipliedby10
andthencasttoaninteger.Thismeansthatafterthecastwealwayshaveanumberfrom0to9.
Butonline39thatrandomnumberfrom0to9gets0addedtoitbeforestoringitintoa.(Adding0
doesntchangethenumber.)Soawillalwayshaveavaluefrom09.
[Link]
whateveritisbiggerby1.Ifithadbeena0,itwillnowbea1.Ifithadbeena6,[Link]
hadbeena9(themaximum),itwillnowbea10.Sobwillalwayshaveavaluefrom110.
[Link]
avaluefrom5to14.(Thisisstilltenvalues.)
Okay,thatsenoughfortoday.

StudyDrills
1. [Link]?
(Thenputitback.)
[Link],bandcasprintedoutonlines28through30
alwayshavevaluesfrom0to99.
1. UseyourfingerstocountandconfirmthatifIhaveanumberfrom0to9,therearetenpossible
[Link]
possibleresults(09).Multiplyingarandomnumberbyfiveandtruncatinggivesyoufive
possibleresults(04).
2. Runtheprogramseveraltimesandconfirmthataasprintedoutonline43alwayshasavalue
from09,thatbalwayshasavaluefrom110,andcalwayshasavaluefrom514.
Exercise25:MoreComplexRandomNumbers
Thepreviousexercisehadsometoughthinkinginit,soinsteadofteachingsomethingnew,thisexercise
willjustspendmoretimewiththesameconcepts.
1publicclassRandomNumbers2
2{
3publicstaticvoidmain(String[]args)
4{
5inta,b,c,d,e,low,high;
6
7a=1+(int)([Link]()*10);
8b=1+(int)([Link]()*10);
9c=1+(int)([Link]()*10);
10d=1+(int)([Link]()*10);
11e=1+(int)([Link]()*10);
12
[Link](a+"\t"+b+"\t"+c+"\t"+d+"\t"+e);
14
15a=1+(int)([Link]()*100);
16b=1+(int)([Link]()*100);
17c=1+(int)([Link]()*100);
18d=1+(int)([Link]()*100);
19e=1+(int)([Link]()*100);
20
[Link](a+"\t"+b+"\t"+c+"\t"+d+"\t"+e);
22
23a=70+(int)([Link]()*31);//31is10070+1
24b=70+(int)([Link]()*31);
25c=70+(int)([Link]()*31);
26d=70+(int)([Link]()*31);
27e=70+(int)([Link]()*31);
28
[Link](a+"\t"+b+"\t"+c+"\t"+d+"\t"+e);
30
31low=70;
32high=100;
33
34a=low+(int)([Link]()*(highlow+1));
35b=low+(int)([Link]()*(highlow+1));
36c=low+(int)([Link]()*(highlow+1));
37d=low+(int)([Link]()*(highlow+1));
38e=low+(int)([Link]()*(highlow+1));
39
[Link](a+"\t"+b+"\t"+c+"\t"+d+"\t"+e);
41}
42}

WhatYouShouldSee
79333
1053781775
7696998586
9991969983
(Again,[Link].)
[Link]
integertotruncateit(soeachrandomnumberisoneoftennumbers:0through9).Then1isaddedto
each,sothevariablesathrougheeachgetarandomnumberfrom1to10.
[Link]
hundredandcasttoanintegertotruncateit(soeachrandomnumberisoneof100numbers:0through
99).Then1isaddedtoeach,sothevariablesathrougheeachgetarandomnumberfrom1to100.
Onlines23through27wechoosefivemorerandomnumbers.Eachnumberismultipliedby31andcast
toanintegertotruncateit(soeachrandomnumberisoneof31numbers:0through30).Then70is
addedtoeach.0plus70gives70.1plus70gives71.23plus70gives93.30(themaximum)plus70
gives100.Sothevariablesathrougheeachgetarandomnumberfrom70to100.
Sothegeneralformulaisthis:
inta=low+(int)([Link]()*range);

[Link]
[Link]
numbersthatis,theformulais:
intrange=highlow+1;
IfthelowestrandomnumberIwantis1andthehighestrandomnumberis5,thentherangeisfive.5
minus1is4,thenaddonetoaccountforthefactthatsubtractinggivesyouthedistancebetweentwo
numbers,notthecountofstoppingpointsalongtheway.8
Youcouldevenwritetheformulalikethis:
inta=low+(int)([Link]()*(highlow+1));
[Link]
lines34through38.

StudyDrills
1. [Link]
programmanytimestoconfirmthatyoualwaysgetrandomnumbersinthatrange.

8 Thereisacommonlogicalerrorinprogrammingthatcanoccurifyouaccidentallycountdistanceinsteadofstops;itis
[Link]:ifIneedtobuildafencefivemeters
longusingabunchofwoodenboardsthatareslightlylongerthanonemetereach,howmanyfencepostswillIneed?You
needfiveboardsbutsixfenceposts.
Exercise26:RepeatingYourselfwiththeWhileLoop
Thisisoneofmyfavoriteexercises,becauseyouaregoingtolearnhowtomakechunksofcoderepeat.
Andifyoucandothat,youwillbeabletowriteallsortsofinterestingthings.
[Link];
2
3publicclassEnterPIN
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8intpin,entry;
9
10pin=12345;
11
[Link]("WELCOMETOTHEBANKOFJAVA.");
[Link]("ENTERYOURPIN:");
14entry=[Link]();
15
16while(entry!=pin)
17{
[Link]("\[Link].");
[Link]("ENTERYOURPIN:");
20entry=[Link]();
21}
22
[Link]("\[Link]
ACCOUNT.");
24}
25}

WhatYouShouldSee
WELCOMETOTHEBANKOFJAVA.
ENTERYOURPIN:123

[Link].
ENTERYOURPIN:1234

[Link].
ENTERYOURPIN:12345

[Link].
[Link]
[Link],
[Link],
bothwhileloopsandifstatementwillexecuteallofthecodeinsidetheirbodyonetime.
Theonlydifferenceisthatifstatementsthataretruewillexecuteallofthecodeinthecurlybraces
[Link]
[Link],thecodeinthebodywillallbe
[Link].
Infact,youcouldsaythatthewhileloopexecutesallofthecodeinitsbodyoverandoveragainas
longasitsconditionistruewhenchecked.
Eventually,[Link]
[Link],
itdoesntgetcheckedagain.
Loopingissogreatbecausewecanfinallydosomethingmorethanoncewithouthavingtotypethecode
foritmorethanonce!Infact,programmerssometimessayKeepyourcodeD.R.Y:DontRepeat
[Link],you
willstarttogetsuspiciousifyoufindyourselftyping(orcopyingandpasting)theexactsamecode
morethanonceinaprogram.
Exercise27:ANumberGuessingGame
Nowthatyouknowhowtorepeatsomethingusingawhileloopwearegoingtowriteaprogramthat
anotherhumanmightactuallyenjoyrunning?AreyouasexcitedasIamaboutthis?
[Link];
2
3publicclassHighLow
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8intsecret,guess;
9
10secret=1+(int)([Link]()*100);
11
[Link]("I'[Link]
guessit.");
[Link](">");
14guess=[Link]();
15
16while(secret!=guess)
17{
18if(guess<secret)
19{
[Link]("Sorry,[Link]."
);
21}
22if(guess>secret)
23{
[Link]("Sorry,[Link]
again.");
25}
[Link](">");
27guess=[Link]();
28}
29
[Link]("Youguessedit!Whataretheodds?!?");
31}
32}

WhatYouShouldSee
I'[Link].
>50
Sorry,[Link].
>25
Sorry,[Link].
>13
Sorry,[Link].
>20
Sorry,[Link].
>16
Sorry,[Link].
>18
Sorry,[Link].
>14
Sorry,[Link].
>15
Youguessedit!Whataretheodds?!?
Soonline10thecomputerchoosesarandomnumberfrom1to100andstoresitintothevariablesecret.
Weletthehumanmakeaguess.
[Link]
valueofthevariableguessrunthefollowingchunkofcode.Lines17through28arethebodyofthe
[Link],alltwelveoftheselinesofcodegetexecuted.
[Link]
isdifferentfromthesecretnumberorwewouldntbeinsidethewhilelooptobeginwith!Butwe
dontknowiftheguessiswrongbecauseitistooloworbecauseitistoohigh,sotheseifstatements
figurethatoutanddisplaytheappropriateerrormessage.
Thenaftertheerrormessageisdisplayed,[Link]
(hopefully)typesinanumberwhichisthenstoredintothevariableguess,overwritingtheirprevious
guessinthatvariable.
[Link]
(theirguessisstillnotequaltothesecretnumber)[Link]
conditionisnowfalse(theyguessedit)thenthewholeloopbodywillbeskippedandtheprogramwill
skipdowntoline29.
Iftheloopisover,[Link];itis
safetoprintyouguessedit.
Exercise28:InfiniteLoops
Onethingwhichsometimessurprisesstudentsishoweasyitistomakealoopthatrepeatsforever.
Thesearecalledinfiniteloopsandwesometimesmakethemonpurpose9butusuallytheyarethe
[Link]:
[Link];
2
3publicclassKeepGuessing
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8intsecret,guess;
9
10secret=1+(int)([Link]()*10);
11
[Link]("[Link]
guessit.");
[Link]("Yourguess:");
14guess=[Link]();
15
16while(secret!=guess)
17{
[Link]("[Link].");
[Link]("Yourguess:");
20}
21
[Link]("That'sright!You'reagoodguesser.");
23}
24}

WhatYouShouldSee
[Link].
Yourguess:4
[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].

9 Forexample,[Link]
[Link]
[Link]
webserversoftwarewasintendedtostartautomaticallywhenthemachinebooted,runthewholetime,andonlyshut
downwhenthemachinedid.
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:[Link].
Yourguess:^C
Theprogramactuallydidntstoponitsown;IhadtostopitbypressingCTRLCwhiletheprogram
wasrepeatingandrepeating.
Thiscodehasaninfiniteloopinit.Line16checkstoseeifthevalueofthevariablesecretisdifferent
[Link],itexecutesthebodyoftheloopandifnotitskipsoverthe
loopbodydowntoline21.
Theproblemisthatoncesecretandguessaredifferenttheprogramcanneverreachanotherlineofcode
thatchangeseithervariable,sothelooprepeatslines16through20forever.
Sowhenyouarewritingtheconditionofawhileloop,trytokeepinthebackofyourmind:Ineedto
makesuretheresawayforthisconditiontoeventuallybecomefalse.

StudyDrills
1. Fixthecodesothatitnolongermakesaninfiniteloop.
Exercise29:UsingLoopsforErrorChecking
[Link]
followdirections,andiftheirlackofdirectionfollowingbreaksourprogram,wejustblametheuserand
dontworryaboutit.
[Link],whichiswhymostbigprograms
havebugsandittakesawholearmyofpeopleworkingreallyhardtomakesurethatsoftwarehasasfew
bugsaspossible.
Butyouarefinallytothepointwhereyoucancodealittlebitoferrorchecking.
[Link];
2
3publicclassSafeSquareRoot
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8doublex,y;
9
[Link]("Givemeanumber,andIshallfindthesquareroot
ofit.");
[Link]("(Nonegatives,please.)");
12x=[Link]();
13
14while(x<0)
15{
[Link]("Sorry,Iwon'ttakethesquarerootofa
negative.\nNewnumber:");
17x=[Link]();
18}
19
20y=[Link](x);
21
[Link]("Thesquarerootof"+x+"is"+y);
23}
24}

WhatYouShouldSee
Givemeanumber,andIshallfindthesquarerootofit.(Nonegatives,please.)
8
Sorry,Iwon'ttakethesquarerootofanegative.
Newnumber:7
Sorry,Iwon'ttakethesquarerootofanegative.
Newnumber:200
Sorry,Iwon'ttakethesquarerootofanegative.
Newnumber:5
Thesquarerootof5.0is2.23606797749979
Startingonline14isanexampleofwhatIcallaninputprotectionloop.Online20wearegoingto
takethesquarerootofwhatevervalueisinthevariablexandwewouldliketomakesureitcontainsa
positivenumberbeforewedothat.(Javadoesnothavebuiltinsupportforimaginarynumbers.)We
[Link](),butImtryingtodemonstrate
errorchecking,okay?
[Link]
number,buttheycantypewhatevertheylike.(TheycouldeventypeMisterMxyzptlk,butour
errorcheckingskillarentadvancedenoughtosurvivethat,yet.)
[Link](lessthanzero)we
[Link],aftertheyhavetypedtheirnewnumberwego
[Link]?Ifso,
displaytheerrormessageagainandgivethemanotherchance.
Computersdontgetimpatientorbored,[Link]
couldtypenegativenumberstwobilliontimesandeachtimethecomputerwouldpolitelycomplainand
makethemtypesomethingagain.
Eventually,[Link]
loopwillbefalse(finally)andthebodyoftheloopwillbeskipped(finally)andexecutionwillpickup
online20wherewecansafelytakethesquarerootofanumberthatweknowispositive.
[Link]
[Link]
mashingkeyswhileaprogramisrunning?Wewouldliketheprogramtonotcrash.
Oh,anddidyounotice?[Link]
printedsomethingonthescreen,Ihaveputablankspacebetweentheparenthesesandthequotation
marks,likeso:
[Link]("Thisisatest.");
IdidthatbecauseIwantedtomakeitclearthatthethinginsidethequotes(technicallyaStringliteral)
wasonething,[Link].
(RememberthatIamfulloflies.)Yourprogramwillstillcompileandworkexactlythesameifyou
leavethespacesout:
[Link]("Thisisatest.");
Youmighthavenoticedthatonline22IevenleftoutthespacesbetweentheStringliteralsandtheplus
[Link],althoughmanycompaniesandother
softwarewritinggroupshavestyleguidelinesthattellyouwhattheRightWaytoformatyourcodeis
ifyouwanttomakeothermembersofthegrouphappy.
[Link]
code,oralwaysputtheopenbraceofacodeblockattheendofthepreviousline:
if(age<16){
allowed=false;
}
[Link],youshouldgiveotherstylesatryanddowhatmakesyouhappy.
Andwhenyoureworkingwithothers,youshouldformatthecodeinawaythatmakesthemhappy.
Thereareeventoolsthatcanchangetheformatofyourcodeautomaticallytofitacertainstyle!(Search
forsourcecodebeautifierorJavaprettyprintertoseesomeexamples.)

StudyDrills
1. [Link]()tohandletakingthe
squarerootofnegativenumbers,[Link],takethesquarerootof
thepositiveversion,andprintalittle"i"nexttotheanswer.
Exercise30:DoWhileloops
[Link]
[Link],showingyoua
[Link]
alongtimebeforeIshowthemanewwaytodothesamething.
Soifyouthinkyouaregoingtobeconfused,[Link]
all,andyoucancomebacktoitwhenyourefeelingmoreconfident.
Anyway,[Link],thereisalsoa
[Link]
conditionistrue,[Link],thebodyoftheloopis
skipped(ortheloopingstops).
Sowhatsthedifference?Typeinthecodeandthenwelltalkaboutit.
[Link];
2
3publicclassCoinFlip
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9Stringcoin,again;
10intflip,streak=0;
11
12do
13{
14flip=1+(int)([Link]()*2);
15
16if(flip==1)
17coin="HEADS";
18else
19coin="TAILS";
20
[Link]("Youflipacoinanditis..."+coin);
22
23if(flip==1)
24{
25streak++;
[Link]("\tThat's"+streak+"inarow....");
[Link]("\tWouldyouliketoflipagain(y/n)?");
28again=[Link]();
29}
30else
31{
32streak=0;
33again="n";
34}
35}while([Link]("y"));
36
[Link]("Finalscore:"+streak);
38}
39}

WhatYouShouldSee
Youflipacoinanditis...HEADS
That's1inarow....
Wouldyouliketoflipagain(y/n)?y
Youflipacoinanditis...HEADS
That's2inarow....
Wouldyouliketoflipagain(y/n)?y
Youflipacoinanditis...HEADS
That's3inarow....
Wouldyouliketoflipagain(y/n)?n
Finalscore:3
Thereareonlytwodifferencesbetweenwhileloopsanddowhileloops.
1. Theconditionofawhileloopisbeforethebody,butdowhileloopsjusthavethekeyworddo
beforethebodyandtheconditionisattheend,justaftertheclosecurlybrace.(Andtheresa
semicolonafterthecloseparenoftheloopcondition,whichwhileloopsdonthave.)
2. whileloopschecktheirconditionbeforegoingintotheloopbody,butdowhileloopsrunthe
bodyofthelooponcenomatterwhatandonlychecktheconditionafterthefirsttimethrough.
Incomputersciencecircles,thewhileloopiscalledapretestloop(becauseitchecksthecondition
first)andthedowhileiscalledaposttestloop(becauseitcheckstheconditionafterward).
Iftheconditionofthewhileloopistruetheveryfirsttimeitischecked,thencodeusingawhile
[Link]
withawhileloopyoucoulddowithadowhileloop(andslightlydifferentcode)andviceversa.
SowhywouldthedevelopersofJavabothertomakeadowhileloop?Becausesometimeswhatyoure
checkingintheconditionissomethingyoudontreallyknowuntilyouhavegonethroughthebodyof
theloopatleastonce.
Inthiscase,weareflippingacoinbypickingarandomnumberbetween12andusinganifstatement.
[Link]
wanttoflipagain.
Ifwehaddonethiswithawhileloop,theconditionwouldlooklikethis:
while([Link]("y"))
{
Thisisfine,andwouldwork,[Link]
wouldntcompilebecauseagain(inthewordsoftheJavacompiler)mightnothavebeeninitialized.
Andsowewouldhavetogiveitavalueupbeforetheloopthatdoesntmeananythingandisonlythere
topleasethecompiler.
Thatisannoying,sothedowhileloopallowsustoleaveourconditionthesamebutwaituntiltheendto
[Link].

StudyDrills
1. [Link]
andworksthesame.
2. Changeitbacktoadowhileloop.(Youmightlookbackatthiscodelaterwhenyouforgethow
towriteadowhileloopandwedontwantyouronlyexampletohavebeenchangedtoawhile
loop.)
Exercise31:AddingValuesOneataTime
Thisexercisewilldemonstratesomethingthatyouhavetodoalot:dealingwithvaluesthatyouonlyget
oneatatime.
IfIaskedyoutoletthehumantypeinthreenumbersandaddthemup,andifIpromisedtheywould
onlyneedtotypeinexactlythreenumbers(nevermore,neverfewer),youwouldprobablywrite
somethinglikethis:
inta,b,c,total;
a=[Link]();
b=[Link]();
c=[Link]();
total=a+b+c;
IfItoldyouthehumanwasgoingtotypeinfivenumbers,yourcodemightlooklikethis:
doublenum1,num2,num3,num4,num5,total;
num1=[Link]();
num2=[Link]();
num3=[Link]();
num4=[Link]();
num5=[Link]();
total=num1+num2+num3+num4+num5;
ButwhatifItoldyoutheywantedtotypeinonehundrednumbers?Ortenthousand?Ormaybethree
andmaybefive,Imnotsure?[Link](thatshowwe
repeatthings,afterall).Andyouneedavariablethatwilladdthevaluesoneatatimeastheycome.A
variablethatstartswithnothinginitandaddsvaluesoneatatimeiscalledanaccumulatorvariable,
althoughthatsaprettyoldwordandsoyourfriendswhocodemayneverhavehearditiftheyreunder
theageofforty.
Anyway,thebasicidealookslikethis:
[Link];
2
3publicclassRunningTotal
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9intcurrent,total=0;
10
[Link]("TypeinabunchofvaluesandI'lladdthemup.");
[Link]("I'llstopwhenyoutypeazero.");
13
14do
15{
[Link]("Value:");
17current=[Link]();
18intnewtotal=current+total;
19total=newtotal;
[Link]("Thetotalsofaris:"+total);
21}while(current!=0);
22
[Link]("Thefinaltotalis:"+total);
24}
25}
WhatYouShouldSee
TypeinabunchofvaluesandI'lladdthemup.I'llstopwhenyoutypeazero.
Value:3
Thetotalsofaris:3
Value:4
Thetotalsofaris:7
Value:5
Thetotalsofaris:12
Value:6
Thetotalsofaris:18
Value:0
Thetotalsofaris:18
Thefinaltotalis:18
Weneedtwovariables:onetoholdthevaluetheyjusttypedin(current)andonetoholdtherunning
total(umtotal).Online9,[Link].
[Link],whichrunsat
leastoncenomatterwhat,sothiscodealwayshappens.Letspretendtheytype3atfirst.
[Link]
valueequaltothenumberthehumanjusttypedpluswhatevervalueisalreadyinthevariabletotal.
Theresazerointotalatfirst,sothislineofcodeaddszerotocurrentandstoresthatnumberinto
newtotal.
Thenonline19thesecondhalfofthemagichappens:wereplacethevalueintotal(thezero)withthe
[Link];[Link]
totalwas0,nowitis3.
[Link],thelooprepeatsback
upline14.
[Link]
current(4)plustotal(3),sonewtotalis7.Thenonline19wechangetotalsvalueto7.
Theconditionischeckedagain,andtheprocesscontinues.Eventuallythehumantypesa0,that0gets
addedtothetotal(whichdoesnthurtit)andtheconditionisfalsesothedowhileloopstopslooping.
Ishouldmentiontwothingsbeforetheexerciseends:
[Link](anddefined)online18,thescopeofthatvariableislimited
tothebodyofthedowhileloop.Thatmeansonline21,newtotalisnolongerinscope,soanyattempt
[Link]
[Link].
[Link]
valueoftherighthandsidebeforestoringitintothevariablenamedonthelefthandside,wecould
havecombinedlines18and19intoasingleline:
total=current+total;

Thisworkstotallyfine.(Infact,youhaveseenitbefore.)

StudyDrills
1. [Link]
[Link].
2. Changetheconditionofthedowhileloopsothattheloopstopswhennewtotalisexactly20.
Oh?Itdoesntcompilebecausenewtotalisoutofscope?Changewherenewtotalisdeclaredso
thatthisworks.
Exercise32:AddingValuesforaDiceGame
Pigisasimpledicegamefortwoormoreplayers.(YoucanreadtheWikipediaentryforPigifyou
wantalotmoreinformation.)[Link]
yourolla1,[Link]
turn,butyouonlykeepthosepointsifyoudecidetohold.Ifyourolla1beforeyouhold,allyour
pointsforthatturnarelost.
YouknowenoughtohandlethecodefortheentiregameofPig,butitisalotatoncecomparedtothe
smallerprogramsyouhavebeenseeing,[Link]
onlytheartificialintelligence(A.I.)[Link]
holdat20strategy,whichmeansthecomputerkeepsrollinguntiltheirscorefortheturnaddsupto20
ormore,[Link],anditiseasyenoughto
code.
[Link];
2
3publicclassPigDiceComputer
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9introll,total;
10
11total=0;
12
13do
14{
15roll=1+(int)([Link]()*6);
[Link]("Computerrolleda"+roll+".");
17if(roll==1)
18{
[Link]("\tThatendsitsturn.");
20total=0;
21}
22else
23{
24total+=roll;
[Link]("\tComputerhas"+total+"pointssofarthis
round.");
26if(total<20)
27{
[Link]("\tComputerchoosestorollagain.");
29}
30}
31}while(roll!=1&&total<20);
32
[Link]("Computerendstheroundwith"+total+"points.");
34
35}
36}

WhatYouShouldSee
Computerrolleda2.
Computerhas2pointssofarthisround.
Computerchoosestorollagain.
Computerrolleda3.
Computerhas5pointssofarthisround.
Computerchoosestorollagain.
Computerrolleda1.
Thatendsitsturn.
Computerendstheroundwith0points.
Basicallythewholeprogramisinthebodyonebigdowhileloopthattellsthecomputerwhentostop:
[Link]
20,theconditionwillbetrueandtheloopwillstartoverfromthebeginning(online13).Andwe
chooseadowhileloopbecausewewantthecomputertorollatleastoncenomatterwhat.
Therollismadeonline15:arandomnumberfrom16isagoodsubstituteforrollingadice.
[Link],[Link](else),weaddthisrolltothe
[Link],whichwehaveseenbefore.
Theifstatementonline26isjustsowecangetanicemessagethatthecomputerisgoingtorollagain.
Notterrible,right?Socomebacknextlessonforthefullgame!

StudyDrills
1. Findadice(technicallyitshouldbedie,sincediceispluralandyouonlyneedone)orfind
[Link].
[Link]
andtherightcolumntotal.Puta0inthetotalcolumnandleavetheothercolumnblankat
first.
[Link]
number(15)inparenthesesnexttotherollvalue,sincethedierolloccursonline15inthe
code.
[Link]
[Link],crossoutthecurrentvalueinthetotalcolumnandput0(20)
there,sincetotalwouldbecomezeroonline20ofthecode.
[Link]
forthesamplerunoftheprogramshownintheWhatYouShouldSeesection.
roll total
0(11)
2(15)
2(24)
3(15)
5(24)
1(15)
0(20)
Exercise33:TheDiceGameCalledPig
[Link].(Rememberthatyoucanread
theWikipediaentryforPigifyouwantalotmoreinformationaboutthisgame.)Inthislessonwewill
havethecodefortheentiregame,withonehumanplayerandonecomputerplayerthattaketurns.
[Link]
onlymajordifferenceisthatinsteadofasingletotalvariablewewillhaveaturnTotalvariabletohold
onlythepointsforoneturnandatotal2variablethatholdsthecomputersoverallpointsfromroundto
round.
[Link];
2
3publicclassPigDice
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9introll,total1,total2,turnTotal;
10Stringchoice="";
11
12total1=0;
13total2=0;
14
15do
16{
17turnTotal=0;
[Link]("Youhave"+total1+"points.");
19
20do
21{
22roll=1+(int)([Link]()*6);
[Link]("\tYourolleda"+roll+".");
24if(roll==1)
25{
[Link]("\tThatendsyourturn.");
27turnTotal=0;
28}
29else
30{
31turnTotal+=roll;
[Link]("\tYouhave"+turnTotal+"pointssofarthis
round.");
[Link]("\tWouldyouliketo\"roll\"againor\"hold\"?");
34choice=[Link]();
35}
36}while(roll!=1&&[Link]("roll"));
37
38total1+=turnTotal;
[Link]("\tYouendtheroundwith"+total1+"points.");
40
41if(total1<100)
42{
43turnTotal=0;
[Link]("Computerhas"+total2+"points.");
45
46do
47{
48roll=1+(int)([Link]()*6);
[Link]("\tComputerrolleda"+roll+".");
50if(roll==1)
51{
[Link]("\tThatendsitsturn.");
53turnTotal=0;
54}
55else
56{
57turnTotal+=roll;
[Link]("\tComputerhas"+turnTotal+"pointssofarthis
round.");
59if(turnTotal<20)
60{
[Link]("\tComputerchoosestorollagain.");
62}
63}
64}while(roll!=1&&turnTotal<20);
65
66total2+=turnTotal;
[Link]("\tComputerendstheroundwith"+total2+"points.");
68}
69
70}while(total1<100&&total2<100);
71
72if(total1>total2)
73{
[Link]("Humanitywins!");
75}
76else
77{
[Link]("Thecomputerwins.");
79}
80
81}
82}

WhatYouShouldSee
Youhave0points.
Yourolleda2.
Youhave2pointssofarthisround.
Wouldyouliketo"roll"againor"hold"?roll
Yourolleda1.
Thatendsyourturn.
Youendtheroundwith0points.
Computerhas0points.
Computerrolleda6.
Computerhas6pointssofarthisround.
Computerchoosestorollagain.
Computerrolleda6.
Computerhas12pointssofarthisround.
Computerchoosestorollagain.
Computerrolleda1.
Thatendsitsturn.
Computerendstheroundwith0points.
Youhave0points.
Yourolleda3.
Youhave3pointssofarthisround.
Wouldyouliketo"roll"againor"hold"?roll
Yourolleda5.
Youhave8pointssofarthisround.
Wouldyouliketo"roll"againor"hold"?roll
Yourolleda2.
Youhave10pointssofarthisround.
Wouldyouliketo"roll"againor"hold"?roll
Yourolleda2.
Youhave12pointssofarthisround.
Wouldyouliketo"roll"againor"hold"?hold
Youendtheroundwith12points.
Computerhas0points.
Computerrolleda5.
Computerhas5pointssofarthisround.
Computerchoosestorollagain.
Computerrolleda4.
Computerhas9pointssofarthisround.
Computerchoosestorollagain.
Computerrolleda4.
Computerhas13pointssofarthisround.
Computerchoosestorollagain.
Computerrolleda3.
Computerhas16pointssofarthisround.
Computerchoosestorollagain.
Computerrolleda5.
Computerhas21pointssofarthisround.
Computerendstheroundwith21points.
Youhave12points.
Yourolleda2.
Youhave2pointssofarthisround.
Wouldyouliketo"roll"againor"hold"?roll

...etc

Computerhas20pointssofarthisround.
Computerendstheroundwith102points.
Thecomputerwins.
Webegintheprogramwithtwovariables:total1holdsthehumanstotalandtotal2holdsthecomputers
total.Bothstartat0.
Thenonline15beginsareallyhugedowhileloopthatbasicallycontainsthewholegameanddoesnt
enduntilline70.Scrolldownandyoucanseethatthislooprepeatsaslongasbothtotal1andtotal2are
lessthan100.Wheneitherplayerreaches100ormore,theconditionisnolongertrueandthedowhile
wontrepeatbackupagain.
Thenafterthatdowhileloopends(startingonline72)thereisanifstatementandanelseto
determinethewinner.
Letusscrollbackupandlookatthehumansturn,[Link]
[Link],weshould
startitoutat0.
Line20isthebeginningofadowhileloopthatcontainsthehumansturn.Itendsonline36,andallthe
codebetweenlines20and36willrepeataslongasthehumandoesnotrolla1andaslongasthehuman
keepschoosingtorollagain.
Eachrollforthehumanbeginsjustlikethecomputerdid:bychoosingarandomnumberfrom1to6.
Weprintthisoutonline22.
Nowtwothingscouldhappen:eithertherollis1andthehumanlosesallpointsearnedthisroundor
[Link],andonlines
[Link]
line36theconditionofthedowhileloopwillcheckandrepeatbackuptoline20ifappropriate.
Oncetheplayersturnends,weaddtheturnTotal(whichmightbe0)totheplayersoveralltotaland
displaytheircurrentnumberofpoints.
[Link],thecomputerdoesntgetaturnifthehumanhas
alreadyreached100points:[Link]
mustwrapthewholecomputersturninabigifstatementsothatitisskippedifthehumanstotal
(total1)isgreaterthanorequalto100.Thisifstatementbeginshereonline41andendsonline68.
[Link],soI
[Link]
onitsturntotal.
Line70endsthedowhileloopcontainingthewholegame,andlines72through79determineand
displaythewinner.
[Link].
Iwouldalsopointouthowimportantitisforaprogramlikethisthateverytimeyouputanopenbrace,
[Link]
justscanyoureyesvisuallydownfromtheopencurlybraceonline47tothematchingclosecurlybrace
online64toseewhatisinsidethatdowhileloopandwhatisnt.
Exercise34:CallingaFunction
[Link]
tolearnhowtowriteafunction10inJavaandhowtomakeitexecutebycallingit.
1publicclassThereAndBackAgain
2{
3publicstaticvoidmain(String[]args)
4{
[Link]("Here.");
6erebor();
[Link]("Backfirsttime.");
8erebor();
[Link]("Backsecondtime.");
10}
11
12publicstaticvoiderebor()
13{
[Link]("There.");
15}
16}

WhatYouShouldSee
Here.
There.
Backfirsttime.
There.
Backsecondtime.
Solines5through9areprettyboring,exceptthatonlines6and8wearereferringtosomethingcalled
[Link]?Becauseitdoesnt
exist!
Skippingdowntolines12through15youwillnoticethatIaddedsomethingtoourprogramthatisnot
insidethebodyofmain().Normallytheclosecurlybraceofpublicstaticvoidmainis
almostattheendofthecode,andtheonlythingafteritistheclosecurlybraceofpublicclass
[Link]!
Lines12through15defineafunctionnamederebor().(Theworderebor()doesntmean
[Link]()orsmaug()oranythingwelike.)
Thisfunctionhasanopencurlybraceonline13justlikemain()[Link]
online15istheendofthefunctionsbody,[Link]
startsonline12andendsonline15.
Whatdoesthefunctiondo?ItprintstheString"There."onthescreen.

10 [Link],[Link]
thisisamethod,notafunction.
[Link],whatwehavewrittenherewould
[Link]
remotelyobjectoriented.
Soeventhoughitstechnicallyincorrect,Iamgoingtorefertothissortofthingasafunctionandonlyusethewordmethod
whenImakesomethingthatactuallybehaveslikeamethod.
MyintentionallywrongvocabularywillonlycauseproblemsifyouaretalkingtoapedanticJavaprogrammerbecausethey
[Link],showthemthisfootnoteandaskthemhowmanyyearstheyhavebeenteaching
[Link]
doingthisnowandtryingtodistinguishbetweenmethodsthatactlikefunctionsandmethodsthatbehavelikereal
methods.
Sonowletsgobackuptomain()andlookatthefunctioncallsinsidethebodyofmain().
Online5weprinttheString"Here."[Link]
lineofcodetellsthecomputertojumpdowntothefunctionerebor(),runthroughallthecodeinthe
bodyofthatfunction,andtoreturntoline6oncethathasbeenaccomplished.
Soyouseethatwhenwecalltheerebor()function,theString"There."getsprintedonthescreen
rightaftertheString"Here.".Whenthecomputerrunsline6,executionoftheprogrampausesin
main(),skipsoveralltherestofthecodeinmain(),jumpsdowntoline12,runsallthecodeinthe
bodyofthefunctionerebor()(all1lineofit)andthenonceexecutionhitstheclosecurlybraceon
line15,itreturnsbackuptotheendofline6andunpausestheexecutioninmain().Itrunsline7next.
Online7isdisplaysanothermessageonthescreen,[Link]
[Link]()online8,jumpsdownandrunsthroughthe
bodyoferebor(whichprintstheString"There."again),thenreturnsbackuptoline8where
executionofmain()resumes.
[Link]
main()[Link]()ends,theprogramends.
Thatsprettyimportant,soIwillsayitagain:whenmain()ends,[Link]
bunchofdifferentfunctionsinsidetheclass,programexecutionbeginswiththefirstlineofmain().
Andoncethelastlineofmain()hasbeenexecuted,theprogramstopsrunningevenifthereare
functionsthatnevergotcalled.(Wewillseeanexampleofthisinthenextexercise.)

StudyDrills
1. Removetheparenthesesattheendofthefirstfunctioncallonline6sothatitlookslikeso:
erebor;
Whathappenswhenyoucompile?(Thenputtheparenthesesback.)
1. Removethesecondfunctioncall(theoneonline8).Youcaneitherjustdeletethelineentirely
orputslashesinfrontofitsothecompilerthinksitsacommentlikeso:
//erebor();
Compileit,butbeforeyourunit,howdoyouthinktheoutputwillbedifferent?Runitandseeifyou
wereright.
Exercise35:CallingFunctionstoDrawaFlag
Nowthatyouunderstandtheabsolutebasicsabouthowtodefineafunctionandhowtocallthat
function,letusgetsomepracticebydefiningelevenfunctions!
Therearenozeros(0)[Link]
thatlines45and50featureprint()insteadofprintln().
[Link].*;
2
3publicclassOverlyComplexFlag
4{
5publicstaticvoidmain(String[]args)
6{
7printTopHalf();
8
9print48Colons();
10print48Ohs();
11print48Colons();
12print48Ohs();
13print48Colons();
14print48Ohs();
15}
16
17publicstaticvoidprint48Colons()
18{
[Link]("|::::::::::::::::::::::::::::::::::::::::::::::::|");
20}
21
22publicstaticvoidprint48Ohs()
23{
[Link]("|OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO|");
25}
26
27publicstaticvoidprint29Colons()
28{
[Link]("|:::::::::::::::::::::::::::::|");
30}
31
32publicstaticvoidprintPledge()
33{
[Link]("Ipledgeallegiancetotheflag.");
35}
36
37publicstaticvoidprint29Ohs()
38{
[Link]("|OOOOOOOOOOOOOOOOOOOOOOOOOOOOO|");
40}
41
42publicstaticvoidprint6Stars()
43{
[Link]("|******");
45}
46
47publicstaticvoidprint5Stars()
48{
[Link]("|*****");
50}
51
52publicstaticvoidprintSixStarLine()
53{
54print6Stars();
55print29Ohs();
56}
57
58publicstaticvoidprintFiveStarLine()
59{
60print5Stars();
61print29Colons();
62}
63
64publicstaticvoidprintTopHalf()
65{
[Link]("________________________________________________");//
1spacethen48underscores
67printSixStarLine();
68printFiveStarLine();
69printSixStarLine();
70printFiveStarLine();
71printSixStarLine();
72printFiveStarLine();
73printSixStarLine();
74}
75
76}

WhatYouShouldSee
________________________________________________
|******|OOOOOOOOOOOOOOOOOOOOOOOOOOOOO|
|*****|:::::::::::::::::::::::::::::|
|******|OOOOOOOOOOOOOOOOOOOOOOOOOOOOO|
|*****|:::::::::::::::::::::::::::::|
|******|OOOOOOOOOOOOOOOOOOOOOOOOOOOOO|
|*****|:::::::::::::::::::::::::::::|
|******|OOOOOOOOOOOOOOOOOOOOOOOOOOOOO|
|::::::::::::::::::::::::::::::::::::::::::::::::|
|OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO|
|::::::::::::::::::::::::::::::::::::::::::::::::|
|OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO|
|::::::::::::::::::::::::::::::::::::::::::::::::|
|OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO|
[Link]
[Link].
ButfunctionsareimportantandIprefertostartwithsillyexamplesthatyoucanactuallyunderstand
insteadofrealisticexamplesthataretoohardtofollow.
Sohowdoweeventracethroughtheexecutionofaprogramlikethis?Westartatthebeginning:the
firstlineofmain().Online7thefirstthingmaindoesiscallthefunctionprintTopHalf().So
maingetsputonpauseandexecutionjumpsdowntothefirstlineoftheprintTopHalf()function,
whichisonline66.
ThefirstthingthatprintTopHalfdoesisprintabunchofunderscoresonthescreen,whichwewillbethe
topofourflag.Afterthatexecutionmovesontoline67,whichisanotherfunctioncall!Somain()is
stillonpausefrombefore,waitingforprintTopHalf()tofinish,andnowprintTopHalf()
itselfisonpause,waitingforprintSixStarLine()tofinishandreturncontroltohere.
printSixStarLine()beginsonline54,whereitcallstheprint6Stars()[Link]
function(thankfully)onlydisplayssomethingonthescreensowhentheclosecurlybraceof
print6Stars()comesonline45,itreturnscontrolbacktothesecondline(line55)of
printSixStarLine(),[Link]
functionprint29Ohs()[Link]()ends,which
returnscontroltotheendofline67.
Atthispoint,Ithinkexplainingallthefunctioncallswillbemoreconfusingthanjustfollowingthe
executionpathonyourown,sohereIwilljustprintallthelinenumbersthatexecute,[Link]
functionwillincreasetheindentationlevelandreturningfromthatfunctionwillreducetheindentation
level.
5beginmain
6
7callprintTopHalf
64beginprintTopHalf
65
66
67callprintSixStarLine
52beginprintSixStarLine
53
54callprint6Stars
42beginprint6Stars
43
44
45endprint6Stars
54resumeprintSixStarLine
55callprint29Ohs
37beginprint29Ohs
38
39
40endprint29Ohs
55resumeprintSixStarLine
56endprintSixStarLine
67resumeprintTopHalf
68callprintFiveStarLine
58beginprintFiveStarLine
59
60callprint5Stars
47beginprint5Stars
48
49
50endprint5Stars
60resumeprintFiveStarLine
61callprint29Colons
27beginprint29Colons
28
29
30endprint29Colons
61resumeprintFiveStarLine
62endprintFiveStarLine
68resumeprintTopHalf
69callprintSixStarLine
52beginprintSixStarLine
53
54callprint6Stars
42beginprint6Stars
43
44
45endprint6Stars
54resumeprintSixStarLine
55callprint29Ohs
37beginprint29Ohs
38
39
40endprint29Ohs
55resumeprintSixStarLine
56endprintSixStarLine
69resumeprintTopHalf
70callprintFiveStarLine
58beginprintFiveStarLine
59
60callprint5Stars
47beginprint5Stars
48
49
50endprint5Stars
60resumeprintFiveStarLine
61callprint29Colons
27beginprint29Colons
28
29
30endprint29Colons
61resumeprintFiveStarLine
62endprintFiveStarLine
70resumeprintTopHalf
71callprintSixStarLine
52beginprintSixStarLine
53
54callprint6Stars
42beginprint6Stars
43
44
45endprint6Stars
54resumeprintSixStarLine
55callprint29Ohs
37beginprint29Ohs
38
39
40endprint29Ohs
55resumeprintSixStarLine
56endprintSixStarLine
71resumeprintTopHalf
72callprintFiveStarLine
58beginprintFiveStarLine
59
60callprint5Stars
47beginprint5Stars
48
49
50endprint5Stars
60resumeprintFiveStarLine
61callprint29Colons
27beginprint29Colons
28
29
30endprint29Colons
61resumeprintFiveStarLine
62endprintFiveStarLine
72resumeprintTopHalf
73callprintSixStarLine
52beginprintSixStarLine
53
54callprint6Stars
42beginprint6Stars
43
44
45endprint6Stars
54resumeprintSixStarLine
55callprint29Ohs
37beginprint29Ohs
38
39
40endprint29Ohs
55resumeprintSixStarLine
56endprintSixStarLine
73resumeprintTopHalf
74endprintTopHalf
7resumemain
8
9callprint48Colons
17beginprint48Colons
18
19
20endprint48Colons
9resumemain
10callprint48Ohs
22beginprint48Ohs
23
24
25endprint48Ohs
10resumemain
11callprint48Colons
17beginprint48Colons
18
19
20endprint48Colons
11resumemain
12callprint48Ohs
22beginprint48Ohs
23
24
25endprint48Ohs
12resumemain
13callprint48Colons
17beginprint48Colons
18
19
20endprint48Colons
13resumemain
14callprint48Ohs
22beginprint48Ohs
23
24
25endprint48Ohs
14resumemain
Holycow!Ifyoucansuccessfullytracethroughthat,thenyouarewellonyourwaytobecominga
competentprogrammer.

StudyDrills
1. Youdidntactuallytraceallthewaythroughtheprogram,didyou?Well,[Link]
bookisntcalledLearnJavatheHalfwayisit?Printoutthecode,grabapencil,anddrawlines
[Link]
youaredoneitshouldlookabitlikeaplateofgraphitespaghetti!
2. Onlines32through35youfindadefinitionforafunctionnamedprintPledge().Butyet
[Link]?Attheendofmain()addafunctioncall
torunthisfunctionsothatitshowsupunderneaththeflag.
(Despitetheevilnessofthisprogram,[Link]
dimensionsofeverythingyouwillfindthatmyflagisaboutascloseasIthinkyoucanmakeittothe
[Link]
everything.)
Exercise36:DisplayingDicewithFunctions
[Link]
arereadytolookatasituationwhereusingafunctionactuallymakestheprogrambetter.
[Link]
[Link],when
allfivediceshowthesamenumber.
Thisprogramdoesntdoanyotherscoring,itjustrollsfivediceuntiltheyareallthesame.(Computers
gofast,soevenifthistakesalotoftriesitdoesnttakeverylong.)
1publicclassYachtDice
2{
3publicstaticvoidmain(String[]args)
4{
5introll1,roll2,roll3,roll4,roll5;
6booleanallTheSame;
7
8do
9{
10roll1=1+(int)([Link]()*6);
11roll2=1+(int)([Link]()*6);
12roll3=1+(int)([Link]()*6);
13roll4=1+(int)([Link]()*6);
14roll5=1+(int)([Link]()*6);
[Link]("\nYourolled:"+roll1+""+roll2+""+
roll3+""+roll4+""+roll5);
16showDice(roll1);
17showDice(roll2);
18showDice(roll3);
19showDice(roll4);
20showDice(roll5);
21allTheSame=(roll1==roll2&&roll2==roll3&&roll3==roll4
&&roll4==roll5);
22
23}while(!allTheSame);
[Link]("TheYacht!!");
25}
26
27publicstaticvoidshowDice(introll)
28{
[Link]("++");
30if(roll==1)
31{
[Link]("||");
[Link]("|o|");
[Link]("||");
35}
36elseif(roll==2)
37{
[Link]("|o|");
[Link]("||");
[Link]("|o|");
41}
42elseif(roll==3)
43{
[Link]("|o|");
[Link]("|o|");
[Link]("|o|");
47}
48elseif(roll==4)
49{
[Link]("|oo|");
[Link]("||");
[Link]("|oo|");
53}
54elseif(roll==5)
55{
[Link]("|oo|");
[Link]("|o|");
[Link]("|oo|");
59}
60elseif(roll==6)
61{
[Link]("|oo|");
[Link]("|oo|");
[Link]("|oo|");
65}
[Link]("++");
67}
68}

WhatYouShouldSee
Yourolled:46556
++
|oo|
||
|oo|
++
++
|oo|
|oo|
|oo|
++
++
|oo|
|o|
|oo|
++
++
|oo|
|o|
|oo|
++
++
|oo|
|oo|
|oo|
++

Yourolled:22566
++
|o|
||
|o|
++
++
|o|
||
|o|
++
++
|oo|
|o|
|oo|
++
++
|oo|
|oo|
|oo|
++
++
|oo|
|oo|
|oo|
++

...etc

Yourolled:55555
++
|oo|
|o|
|oo|
++
++
|oo|
|o|
|oo|
++
++
|oo|
|o|
|oo|
++
++
|oo|
|o|
|oo|
++
++
|oo|
|o|
|oo|
++
TheYacht!!
OtherthanthefancyBooleanexpressiononline21,theinterestingthinginthisexerciseisasingle
functioncalledshowDice.
Onlines10through14wechoosefiverandomnumbers(eachfrom1to6)andstoretheresultsintothe
fiveintegervariablesroll1throughroll5.
Wewanttousesomeifstatementstodisplayapictureofthediesvalueonthescreen,butwedont
wanttohavetowritethesameifstatementsfivetimes(whichwewouldhavetodobecausethe
variablesaredifferent).Thesolutionistocreateafunctionthattakesaparameter.
[Link](or
identifier)showDicethereisasetofparenthesesandbetweenthemavariableisdeclared!This
[Link]
[Link].
ThismeansthatwheneveryouwriteafunctioncallforshowDiceyoucannotjustwritethenameof
thefunctionwithparentheseslikeshowDice().[Link]
intheparentheses(thisiscalledanargument),eitheravariableoranexpressionthatsimplifiestoan
integervalue.
Herearesomeexamples.
showDice;//NO(withoutparensthisreferstoavariablenotafunctioncall)
showDice();//NO(functioncallmusthaveoneargument,notzero)
showDice(1);//YES(oneargumentisjustright)
showDice(4);//YES
showDice(1+2);//YES
showDice(roll2);//YES
showDice(roll5);//YES
showDice((roll3+roll4)/2);//YES(strangebutlegal)
showDice(17);//YES(althoughitwon'tshowaproperdicepicture)
showDice(3,4);//NO(functioncallmusthaveoneargument,nottwo)
showDice(2.0);//NO(argumentmustbeaninteger,notadouble)
showDice("two");//NO(argumentmustbeaninteger,notaString)
showDice(false);//NO(argumentmustbeaninteger,notaBoolean)

Inallcases,[Link]
soshowDice(3);[Link]
line29theparametervariablerollhasalreadybeendeclaredandinitializedwiththevalue3.
IfwecallthefunctionusingavariablelikeshowDice(roll2);thenthefunctioniscalledanda
copyofwhatevervalueiscurrentlyinroll2willhavebeenstoredintotheparametervariablerollbefore
thebodyofthefunctionisexecuted.
Soonline16theshowDicefunctionisexecuted,androllwillhavebeensetequaltowhatevervalueis
inroll1.
Thenonline17showDiceiscalledagain,butthistimerollwillbesetequaltowhatevervalueisin
[Link].
Inthiswaywebasicallyrunthesamechunkofcodefivetimes,butsubstitutingadifferentvariablefor
[Link].
Forcomparison,Ialsowroteasimplifiedtwodiceversionofthisexercisewithoutusingfunctions.
NoticehowIhadtorepeattheexactsamesequenceofifstatementstwice:onceforeachvariable.
Alsonoticethatalthoughdefiningafunctionisalittlebitmoreworkthanjustcopyingandpastingthe
ifstatementsandchangingthevariable,thetwodiceversionislongerthanthefivediceversion.
1publicclassYachtDiceNoFunctions
2{
3publicstaticvoidmain(String[]args)
4{
5introll1,roll2;
6
7do
8{
9roll1=1+(int)([Link]()*6);
10roll2=1+(int)([Link]()*6);
11inttotal=roll1+roll2;
[Link]("\nYourolleda"+roll1+"anda"+roll2);
[Link]("++");
14if(roll1==1)
15{
[Link]("||");
[Link]("|o|");
[Link]("||");
19}
20elseif(roll1==2)
21{
[Link]("|o|");
[Link]("||");
[Link]("|o|");
25}
26elseif(roll1==3)
27{
[Link]("|o|");
[Link]("|o|");
[Link]("|o|");
31}
32elseif(roll1==4)
33{
[Link]("|oo|");
[Link]("||");
[Link]("|oo|");
37}
38elseif(roll1==5)
39{
[Link]("|oo|");
[Link]("|o|");
[Link]("|oo|");
43}
44elseif(roll1==6)
45{
[Link]("|oo|");
[Link]("|oo|");
[Link]("|oo|");
49}
[Link]("++");
51
52
[Link]("++");
54if(roll2==1)
55{
[Link]("||");
[Link]("|o|");
[Link]("||");
59}
60elseif(roll2==2)
61{
[Link]("|o|");
[Link]("||");
[Link]("|o|");
65}
66elseif(roll2==3)
67{
[Link]("|o|");
[Link]("|o|");
[Link]("|o|");
71}
72elseif(roll2==4)
73{
[Link]("|oo|");
[Link]("||");
[Link]("|oo|");
77}
78elseif(roll2==5)
79{
[Link]("|oo|");
[Link]("|o|");
[Link]("|oo|");
83}
84elseif(roll2==6)
85{
[Link]("|oo|");
[Link]("|oo|");
[Link]("|oo|");
89}
[Link]("++");
91
[Link]("Thetotalis"+total+"\n");
93}while(roll1!=roll2);
94
[Link]("Doubles!Nicejob.");
96}
97}

WhatYouShouldSee
Yourolleda5anda4
++
|oo|
|o|
|oo|
++
++
|oo|
||
|oo|
++
Thetotalis9

Yourolleda6anda2
++
|oo|
|oo|
|oo|
++
++
|o|
||
|o|
++
Thetotalis8

Yourolleda2anda2
++
|o|
||
|o|
++
++
|o|
||
|o|
++
Thetotalis4

Doubles!Nicejob.

StudyDrills
1. Addasixthdice.Noticehoweasyitistodisplayroll6byjustaddingasinglefunctioncall.
Exercise37:ReturningaValuefromaFunction
[Link]
[Link]:thereturnvalue.
Thisexercisegivesanexampleofafunctionthathasthreeparameters(thesidelengthsofatriangle)and
oneoutput:theareaofthattriangleusingHeronsFormula.
1publicclassHeronsFormula
2{
3publicstaticvoidmain(String[]args)
4{
5doublea;
6
7a=triangleArea(3,3,3);
[Link]("Atrianglewithsides3,3,3hasanareaof"+a);
9
10a=triangleArea(3,4,5);
[Link]("Atrianglewithsides3,4,5hasanareaof"+a);
12
13a=triangleArea(7,8,9);
[Link]("Atrianglewithsides7,8,9hasanareaof"+a);
15
[Link]("Atrianglewithsides5,12,13hasanareaof"+
triangleArea(5,12,13));
[Link]("Atrianglewithsides10,9,11hasanareaof"+
triangleArea(10,9,11));
[Link]("Atrianglewithsides8,15,17hasanareaof"+
triangleArea(8,15,17));
19}
20
21publicstaticdoubletriangleArea(inta,intb,intc)
22{
23//thecodeinthisfunctioncomputestheareaofatrianglewhosesideshave
lengthsa,b,andc
24doubles,A;
25
26s=(a+b+c)/2;
27A=[Link](s*(sa)*(sb)*(sc));
28
29returnA;
30//^aftercomputingthearea,"return"it
31}
32}

WhatYouShouldSee
Atrianglewithsides3,3,3hasanareaof2.0
Atrianglewithsides3,4,5hasanareaof6.0
Atrianglewithsides7,8,9hasanareaof26.832815729997478
Atrianglewithsides5,12,13hasanareaof30.0
Atrianglewithsides10,9,11hasanareaof42.42640687119285
Atrianglewithsides8,15,17hasanareaof60.0
[Link],andtheyare
nameda,[Link],thismeansthatwecannotcallthefunctionwithoutproviding
threeintegervaluesasarguments.
Inadditiontothis,thetriangleAreafunctionreturnsavalue.Noticethatonline21thatitdoesnt
[Link]
functionreturnsavalue,andthetypeofvalueitreturnsisadouble.
Ifinsteadithadthekeywordvoidinthisposition,[Link]
wewantedtriangleAreatoreturnadifferenttypeofvalue:
publicstaticinttriangleArea(inta,intb,intc)//thiswouldreturnan
int

publicstaticStringtriangleArea(inta,intb,intc)//thiswouldreturna
String

publicstaticbooleantriangleArea(inta,intb,intc)//thiswouldreturn
eithertrueorfalse

publicstaticvoidtriangleArea(inta,intb,intc)//thiscannotreturn
anyvalueofanytype
Sometimesmystudentsgetconfusedaboutfunctionsthatreturnvaluesversusfunctionsthatdonot
[Link].
[Link]
[Link]
ofmycarwet,soIsendyououtintotheparkinglot.
Student,pleasegooutintotheparkinglotandrollupthewindowsofmycar.
Yes,sir,yousay.
Ifyouneedinformationfrommeaboutwhatmycarlookslike,thenthoseare
[Link],youneednoparameters.
[Link]
returnavalue.
rollUpWindows();//ifyoudon'tneedparameters

rollUpWindows("Toyota","Corolla",2008,"blue");//ifyoudoneedparameters
Ineithercase,thefunctionisexecutedandgoesoffanddoesitsthing,[Link],
example#2:
[Link]
[Link],soIask
youtogototheparkinglotandgetitforme.
[Link]
[Link],Icopyit
[Link].
Stringplate;

plate=retrieveLicensePlate();//ifyoudon'tneedparameters

plate=retrieveLicensePlate("Toyota","Corolla",2008,"blue");//ifyoudo
needthem
IfIamrude,youcouldreturntomyclassroomandgivemethevalueandIcouldputmyfingersinmy
[Link]
thatreturnsavalue,youcanchoosetonotstorethereturnvalueintoavariableandjustallowthevalue
tovanish:
retrieveLicensePlate("Toyota","Corolla",2008,"blue");//returnsavaluewhich
islost

triangleArea(3,3,3);//returnstheareabutwerefusetostoreitintoa
variable
Thisisusuallyabadidea,butmaybeyouhaveyourreasons.
Inanycase,online10wecallthetriangleAreafunction.Wepassin3,4and5asthethree
arguments.The3getsstoredasthevalueofa(downonline21).The4isstoredintob,and5isputinto
[Link],the
variableAhasavaluestoredinit.
Online29wereturnthevaluethatisinthevariableA.11Thisvaluetravelsbackuptoline10,whereit
isstoredintothevariablea.
Andjusttomakesureyoucanseewhyfunctionsareworththetrouble,hereisanexampleofwriting
thissameprogramwithoutusingafunction.
1publicclassHeronsFormulaNoFunction
2{
3publicstaticvoidmain(String[]args)
4{
5inta,b,c;
6doubles,A;
7
8a=3;
9b=3;
10c=3;
11s=(a+b+c)/2;
12A=[Link](s*(sa)*(sb)*(sc));
[Link]("Atrianglewithsides3,3,3hasanareaof"+
A);
14
15a=3;
16b=4;
17c=5;
18s=(a+b+c)/2;
19A=[Link](s*(sa)*(sb)*(sc));
[Link]("Atrianglewithsides3,4,5hasanareaof"+
A);
21
22a=7;
23b=8;
24c=9;
25s=(a+b+c)/2;
26A=[Link](s*(sa)*(sb)*(sc));
[Link]("Atrianglewithsides7,8,9hasanareaof"+
A);
28
29a=5;
30b=12;
31c=13;
32s=(a+b+c)/2;
33A=[Link](s*(sa)*(sb)*(sc));
[Link]("Atrianglewithsides5,12,13hasanareaof"+A
);
35
36a=10;
37b=9;
38c=11;
39s=(a+b+c)/2;
40A=[Link](s*(sa)*(sb)*(sc));
[Link]("Atrianglewithsides10,9,11hasanareaof"+A
);
42
43a=8;

11 (ThevariableAitselfdoesnotgetreturned,[Link],rememberthatthescopeofavariableislimitedto
theblockofcodeinsidewhichitisdefined?(YoulearnedthatinExercise21.)Thevariableaisonlyinscopeinsidethe
functionmain,andthevariabless,A,andtheparametervariablesa,bandcareonlyinscopeinsidethefunction
triangleArea.)
44b=15;
45c=17;
46s=(a+b+c)/2;
47A=[Link](s*(sa)*(sb)*(sc));
[Link]("Atrianglewithsides8,15,17hasanareaof"+A
);
49}
50}

WhatYouShouldSee
Atrianglewithsides3,3,3hasanareaof2.0
Atrianglewithsides3,4,5hasanareaof6.0
Atrianglewithsides7,8,9hasanareaof26.832815729997478
Atrianglewithsides5,12,13hasanareaof30.0
Atrianglewithsides10,9,11hasanareaof42.42640687119285
Atrianglewithsides8,15,17hasanareaof60.0

StudyDrills
1. Whichoneislonger,theonewiththefunctionortheonewithout?
2. [Link](a+b+c)isanoddnumber,dividingby2
[Link](a+b+c)/2youhave(a+b+c)/[Link]
harderwouldithavebeentofixtheversionthatdidntuseafunction?
3. Addonemoretest:findtheareaofatrianglewithsides9,9,[Link]?How
muchharderwouldithavebeentoaddthetesttotheversionthatdidntuseafunction?

WhatYouShouldSeeAfterDoingtheStudyDrills
Atrianglewithsides3,3,3hasanareaof3.897114317029974
Atrianglewithsides3,4,5hasanareaof6.0
Atrianglewithsides7,8,9hasanareaof26.832815729997478
Atrianglewithsides5,12,13hasanareaof30.0
Atrianglewithsides10,9,11hasanareaof42.42640687119285
Atrianglewithsides8,15,17hasanareaof60.0
Atrianglewithsides9,9,9hasanareaof35.074028853269766
Thatsbetter.
Exercise38:AreasofShapes
[Link]
threefunctions(fourifyoucountmain)andtheyallhaveparametersandallthreereturnvalues.
[Link];
2
3publicclassShapeArea
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9intchoice;
10doublearea=0;
11
[Link]("ShapeAreaCalculatorversion0.1(c)2013
MitchellSampleOutput,Inc.");
13
14do
15{
[Link]("\n==============\n");
[Link]("1)Triangle");
[Link]("2)Circle");
[Link]("3)Rectangle");
[Link]("4)Quit");
[Link](">");
22choice=[Link]();
23
24if(choice==1)
25{
[Link]("\nBase:");
27intb=[Link]();
[Link]("Height:");
29inth=[Link]();
30area=computeTriangleArea(b,h);
[Link]("Theareais"+area);
32}
33elseif(choice==2)
34{
[Link]("\nRadius:");
36intr=[Link]();
37area=computeCircleArea(r);
[Link]("Theareais"+area);
39}
40elseif(choice==3)
41{
[Link]("\nLength:");
43intlength=[Link]();
[Link]("Width:");
45intwidth=[Link]();
[Link]("Theareais"+
computeRectangleArea(length,width));
47}
48elseif(choice!=4)
49{
[Link]("ERROR.");
51}
52
53}while(choice!=4);
54
55}
56
57publicstaticdoublecomputeTriangleArea(intbase,intheight)
58{
59doubleA;
60A=0.5*base*height;
61returnA;
62}
63
64publicstaticdoublecomputeCircleArea(intradius)
65{
66doubleA;
67A=[Link]*radius*radius;
68returnA;
69}
70
71publicstaticintcomputeRectangleArea(intlength,intwidth)
72{
73return(length*width);
74}
75}

WhatYouShouldSee
ShapeAreaCalculatorversion0.1(c)2013MitchellSampleOutput,Inc.

==============

1)Triangle
2)Circle
3)Rectangle
4)Quit
>1

Base:3
Height:5
Theareais7.5

==============

1)Triangle
2)Circle
3)Rectangle
4)Quit
>2

Radius:3
Theareais28.274333882308138

==============

1)Triangle
2)Circle
3)Rectangle
4)Quit
>4
Online57wehavedefinedafunctiontocomputetheareaofatriangle(usingjustthebaseandheight
thistime).Itneedstwoargumentsandwillreturnadoublevalue.Online59wedeclareavariable
[Link]
line66,theyarenotthesamevariable.([Link]
havethesamenamedoesntmakethemthesameperson.)
Thevalueofthevariableb(definedonline27)ispassedinastheinitialvalueoftheparameterbasein
[Link],[Link]
[Link].
Online61thevalueofAisreturnedtomainandendsupgettingstoredinthevariablecalledarea.
Ididthreestrangethingsintherectangleareafunctionwhosedefinitionbeginsonline71.
First,theformalparametershavethesamenamesastheactualarguments.(Remember,theparameters
arethevariablesdeclaredinthefunctiondefinitiononline71andtheargumentsarethevariablesinthe
parenthesesinthefunctioncallonline46.)Thisisaneatcoincidence,[Link]
[Link]
versionoflengthgetsstoredintocomputeRectangleAreaslengthvariablebecausetheyareboth
listedfirstintheparenthesesandfornootherreason.
Secondly,Ididnotbothertocreateavariableforthevaluethefunctionisgoingtoreturnonline73.I
simplyreturnedthevalueoftheexpressionlength*[Link]
valueisandreturnitrightawaywithouteverstoringitintoavariable.
Thirdly,therectangleareavalueisreturnedbacktomainonline46,butIdidntbothertostorethe
returnvalueintoavariable:Ijustprinteditonthescreendirectly.(IalsodidthisinHeronsFormula
butIdidntcallattentiontoit.)[Link]
timeandwealmostalwaysusethereturnvalueofthefunctionbutwedontalwaysneedtostorethe
returnvalueintoitsownvariable.
Finally,beforewemoveontoanothertopicIshouldmentionthatinJava,functionscanonlyreturna
[Link]
Javafunctionscanreturnasinglevalueornovalue(ifthefunctionisvoid)butnevermorethanone.
[Link],Iamnotsureifit
[Link]
exampleisgoodforexplaining,anyway.

StudyDrills
1. [Link].
Exercise39:ThirtyDaysRevisitedwithJavadoc
[Link]
exercisewearegoingtoredoapreviousexercise,makingitbetterwithfunctions.
And,becauseIalwayshavetokeeppushing,Ihaveaddedspecialcommentsabovetheclassandabove
eachfunctioncalledJavadoccomments.
[Link];
2
3/**
4*Containsfunctionsthatmakeiteasiertoworkwithmonths.
5*/
6publicclassThirtyDaysFunctions
7{
8publicstaticvoidmain(String[]args)
9{
10Scannerkb=newScanner([Link]);
11
[Link]("Whichmonth?(112)");
13intmonth=[Link]();
14
[Link](monthDays(month)+"dayshath"+
monthName(month));
16
17}
18
19/**
20*Returnsthenameforthegivenmonthnumber(112).
21*
22*@authorGrahamMitchell
23*@parammonththemonthnumber(112)
24*@returnaStringcontainingtheEnglishnameforthegiven
month,or"error"ifmonthoutofrange
25*/
26publicstaticStringmonthName(intmonth)
27{
28StringmonthName="error";
29
30if(month==1)
31monthName="January";
32elseif(month==2)
33monthName="February";
34elseif(month==3)
35monthName="March";
36elseif(month==4)
37monthName="April";
38elseif(month==5)
39monthName="May";
40elseif(month==6)
41monthName="June";
42elseif(month==7)
43monthName="July";
44elseif(month==8)
45monthName="August";
46elseif(month==9)
47monthName="September";
48elseif(month==10)
49monthName="October";
50elseif(month==11)
51monthName="November";
52elseif(month==12)
53monthName="December";
54
55returnmonthName;
56}
57
58/**
59*Returnsthenumberofdaysinagivenmonth.
60*
61*@authorGrahamMitchell
62*@parammonththemonthnumber(112)
63*@returnthenumberofdaysinanonleapyearforthatmonth,or
31ifmonthoutofrange
64*/
65publicstaticintmonthDays(intmonth)
66{
67intdays;
68
69/*ThirtydayshathSeptember
70April,JuneandNovember
71Alltheresthavethirtyone
72Exceptthesecondmonthalone....*/
73
74switch(month)
75{
76case9:
77case4:
78case6:
79case11:days=30;
80break;
81case2:days=28;
82break;
83default:days=31;
84}
85
86returndays;
87}
88}

WhatYouShouldSee
Whichmonth?(112)9
30dayshathSeptember
IfyouignoretheJavadoccommentsfornow,hopefullyyoushouldseethatusingfunctionshereactually
[Link]()isveryshort,becausemostoftheinterestingworkisbeingdoneinthe
functions.
AllthecodeandvariablespertainingtothenameofthemonthisisolatedinthemonthName()
[Link]()
function.
Collectingvariablesandcodeintofunctionslikethisiscalledproceduralprogramminganditis
consideredamajoradvanceoverjusthavingallyourcodeinmain().Itmakesyourcodeeasierto
debugbecauseifyouhaveaproblemwiththenameofthemonth,youknowithastobeinsidethe
monthName()function.
Okay,nowletstalkabouttheJavadoccomments.
[Link]
writedocumentrightinyourcodebydoingaspecialsortofblockcommentaboveclasses,functionsor
variables.
Thecommentbeginswith/**andendswith*/andeverylineinbetweenstartswithanasterisk(*)
whichislineduplikeyouseeintheexercise.
Thefirstlineofthejavadoccommentisaonesentencesummaryofthething(classorfunction).And
thentherearetagslike@authoror@returnthatgivemoredetailaboutwhowrotethecode,what
parametersthefunctionexpectsorwhatvalueitisgoingtoreturn.
Okay,[Link]
code,andtypethefollowingcommand:
$[Link]
[Link]...
ConstructingJavadocinformation...
StandardDocletversion1.7.0_21
Buildingtreeforallthepackagesandclasses...
Generating/[Link]...
Generating/[Link]...
Generating/[Link]...
Generating/[Link]...
Generating/[Link]...
Buildingindexforallthepackagesandclasses...
Generating/[Link]...
Generating/[Link]...
Generating/[Link]...
Buildingindexforallclasses...
Generating/[Link]...
Generating/[Link]...
Generating/[Link]...
Generating/[Link]...
$
[Link],youwillseealotof
newfiles.(MaybeIshouldhavewarnedyoufirst.)[Link]
browserofyourchoice.
Thisisjavadocdocumentation,[Link]
putfortheclassnearthetop,andthecommentsforthefunctionsareinthesectioncalledMethod
Summary.
ThedetailsabouttheparametersandreturntypesaredownbelowinthesectioncalledMethodDetail.

StudyDrills
1. LookatthejavadocdocumentationforoneofthebuiltinJavaclasses:[Link]
howsimilaritlookstowhatthejavadoctoolgenerated?AlltheofficialJavadocumentationis
createdusingthejavadoctool,solearninghowtoreaditwillbeanimportantpartofbecoming
[Link],[Link]
togetafeelforhowitlooks.
IntheupperleftisalistofallthepackagesofcodethatareincludedaspartofJavaandbelow
thatontheleftisalistofalltheclasses/librariesyoucouldimporttosaveyoufromhavingto
[Link]
existingJavalibraries.
[Link]
[Link],mostprogrammersonlyknow
aboutafractionofthebuiltinJavalibraries,andtheysearchontheInternetandreadthe
documentationwhentheyneedtodosomethingnew,justlikeyoudo!
Exercise40:ImportingStandardLibraries
InthelastexerciseyougotaterrifyinglookatallofthebuiltinmodulesthatareavailableinJava.
TodaywewilllookatasimpleprogramthattookmeabouthalfanhourtowritebecauseIspentalot
oftimesearchingtheInternetandimportingthingsandtryingthingsthatdidntwork.
Thiscodeworks,[Link](oranything,really)andthenprints
outtheSHA256messagedigestofthatpassword.
Whenyouaretypinginthiscode,dontforgettoputthethrowsExceptionattheendofline7.
[Link];
[Link];
[Link];
4
5publicclassPasswordDigest
6{
7publicstaticvoidmain(String[]args)throwsException
8{
9Scannerkeyboard=newScanner([Link]);
10
11Stringpw,hash;
12
13MessageDigestdigest=[Link]("SHA256");
14
[Link]("Password:");
16pw=[Link]();
17
[Link]([Link]("UTF8"));
19hash=[Link]([Link]());
20
[Link](hash);
22}
23}

WhatYouShouldSee
Password:password
5E884898DA28047151D0E56F8DC6292773603D0D6AABBDD62A11EF721D1542D8
[Link]
alwaysbethesameforthatinput.
Ifyoutypeinadifferentpassword,youllgetadifferentdigest,ofcourse:
Password:Thisisareallylongpasswordandnoonewilleverguessit.
A113B65D8BA8DB72D631D97B7A3698E82CDB9D1F52456C8957312CB91EC02B10
Backintheearlydaysofprogramming,whenmachinesfirststartedhavingusernamesandpassword,it
[Link],they
wouldstoresomesortofcryptographichashofthepassword.
Cryptographichasheshavetwousefulproperties:
1. [Link].
2. [Link],butfiguringoutthe
inputthatgaveyouacertainoutputisveryhardorimpossible.
SHA256isaverygoodcryptographichashfunction,anditproducesadigestforagiveninput(or
message)[Link]
outthebase64representationofthosebits,whichendsupbeing64characterslongwhereeach
characterisahexadecimaldigit.
Backinthe1970s,tochangeyourpasswordonacertainmachineyouwouldtypeyourpasswordandthe
machinewouldstoreyourusernameandthehashofyournewpasswordinafile.
Thenwhenyouwantedtologintothemachinelater,itwouldmakeyoutypeinyourusernameand
[Link]
[Link]
computedhashmatch,thenyoumusthavetypedinthecorrectpasswordandyouwouldbeallowed
accesstothemachine.
[Link].
However,nowadayscomputersarewaytoofastandhavewaytoomuchstoragespaceforthistobe
enoughsecurity.SincemachinescancomputetheSHA256ofapasswordveryquickly,itdoesnttake
longforadeterminedhackertofigureoutwhatyourpasswordwas.
(Ifyoureallywanttosecurelystorepasswordsinadatabase,youshouldbeusing
bcrypt,[Link],so
youwillneedtodownloadabcryptlibrarymadebysomeoneelse.)
Okay,enoughaboutsecurepasswords,[Link]
javadocdocumentationforthesetwolibrariesopen.
[Link]
[Link]
Onlines2and3weimportthetwolibrarieswewillbeusingtodothehardpartsofthisexercise.
Online13wecreateavariableoftypeMessageDigest(whichnowexistsbecauseweimported
[Link],althoughIcouldhavecalledit
[Link]
[Link]().WepassinaStringasanargumenttothismethod,whichis
[Link]"SHA256",but"SHA1"and"MD5"wouldhave
[Link].
[Link]()insteadofjustnext()toread
inthepassword,whichallowsthehumantotypeinmorethanoneword.
Online18wecallthegetBytes()methodoftheStringclass,withanargumentof"UTF8".This
convertstheStringvaluetoarawlistofbytesinUTF8formatwhichwepassdirectlyasanargumentto
theupdate()[Link]()
methodbyreadingthejavadocdocumentationfortheStringclass!
[Link]
Online19wecallthedigest()[Link]
rawlistofbytesandisntsuitableforprintingonthescreen,sowepassthatrawlistofbytesdirectlyas
aparametertotheprintHexBinary()[Link],
whichwestoreintothevariablehash.
[Link]!
Ifthisexercisefreakedyououtalittlebit,dontworry.Ifyoucanmakeitthroughthefirst39exercises
inthebook,thenyoucouldlearntodothissortofthing,[Link]
documentationtolearnwhatsortoftoolsotherpeoplehavealreadywrittenforyouandhowtoconnect
[Link]!Rememberthatwritingthisexercise
thefirsttimetookmemorethanhalfanhour,andIvebeenprogrammingsincethe1980sandstarted
codinginJavain1996!
StudyDrills
1. Lookatthejavadocdocumentationforallthemethodsusedinthisexercise:getInstance,
getBytes,update,digest,[Link]
thetypesofvaluestheywillreturn.
2. [Link].(Thenputitback.)
Youwilllearnatinybitaboutexceptionsinthenextexercise.
Exercise41:ProgramsthatWritetoFiles
[Link]
goingtocreateaprogramthatcanputinformationintoatextfileinsteadofonlybeingabletoprint
thingsonthescreen.
Whenyouaretypinginthiscode,dontmissthethrowsExceptionattheendofline6.(Andin
thisexercise,Illactuallyexplainwhatthatmeans.)
[Link];
[Link];
3
4publicclassLetterRevisited
5{
6publicstaticvoidmain(String[]args)throwsException
7{
8PrintWriterfileout;
9
10fileout=newPrintWriter(newFileWriter("[Link]"));
11
[Link]("++");
[Link]("|####|");
[Link]("|####|");
[Link]("|####|");
[Link]("||");
[Link]("||");
[Link]("|BillGates|");
[Link]("|1MicrosoftWay|");
[Link]("|Redmond,WA98104|");
[Link]("||");
[Link]("++");
[Link]();
24}
25}

WhatYouShouldSee

[Link],[Link],it
[Link]
fileusingthesametexteditoryouareusingtowriteyourcode.
IfforsomereasonyouareusingtheversionofNotepadthatcamewithWindows95,itwilllookalittle
somethinglikethis:

(Imadethatscreenshotalongtimeago,okay?Ivebeendoingthisalongtime,[Link]
gavethisassignmenttostudents,[Link],Iguessthe
zipcodechangedatsomepoint.)
Onlines1and2therearetwonewimportstatements,oneforeachoftheJavaclassesthatwillmake
thiseasy.
[Link]
fileout(althoughthevariablesnamedoesntmatter).
Online10wegivethePrintWritervariableavalue:[Link]
thePrintWriterobjectrequiresanargument,[Link]
object,whichitselfiscreatedwiththefilenameasanargument.
ItispossibletowritetoatextfileusingonlyaFileWriterobjectandwithoutusinganyPrintWriter
[Link],PrintWritersaremucheasiertoworkwith,asyoucantellbylookingattherestofthe
[Link],wewraptheFileWriterobjectwitha
PrintWriterobjectandjustworkthroughthePrintWriterobject.
([Link]
understandthemtowritetofiles.)
ThegoodnewsisthatoncethePrintWriterobjectissetup,[Link]
secretlybeenworkingwithPrintWriterssincetheverybeginning![Link]
PrintWriter!
[Link]
String(+)[Link]
[Link]!
[Link],itscontentswillbeoverwrittenwithout
[Link],itwillbecreated.
[Link]
[Link],yourprogramwillmost
[Link],butthefilewillbeempty.
Okay,beforeIendtheexercise,[Link]
wedomuchinRealProgramming,andexplainingitproperlyisbeyondthescopeofthisbook,butIdo
wanttotouchonit.
Intheoriginalversionoftheexercise,whenyouputthrowsExceptionafterthefirstlineofa
function,itmeansIhavewrittencodeinthisfunctionthatmightnotwork,andifitfailsitwillblowup
(bythrowinganexception).
InthiscasethethingthatmightnotworkisthelinenewFileWriter("[Link]")
[Link]
[Link]
otherreasontheprogramcantgetwritepermissiontothefile.
[Link]
so:
[Link];
[Link];
[Link];
4
5publicclassLetterRevisitedException
6{
7publicstaticvoidmain(String[]args)
8{
9PrintWriterfileout;
10
11try
12{
13fileout=newPrintWriter(newFileWriter("[Link]"));
14}
15catch(IOExceptionerr)
16{
[Link]("Sorry,Ican'twritetothefile'[Link]'.");
[Link]("Maybethefileexistsandisreadonly?");
19fileout=null;
[Link](1);
21}
22
[Link]("++");
[Link]("|####|");
[Link]("|####|");
[Link]("|####|");
[Link]("||");
[Link]("||");
[Link]("|BillGates|");
[Link]("|1MicrosoftWay|");
[Link]("|Redmond,WA98104|");
[Link]("||");
[Link]("++");
[Link]();
35}
36}

Thetryblockmeansthiscodemaythrowanexception,[Link](if
thereisnoexceptionthrown)[Link],the
catchblockgetsexecuted,andtheexceptionthatwasthrowngetspassedinasaparameter.(Ihave
namedtheexceptionparametererr,thoughitcouldbenamedanything.)
InsidethecatchblockIprintoutasuitableerrormessageandthenendtheprogrambycallingthe
[Link]().[Link](),theprogram
willend,butthezeromeanseverythingisfine.Anargumentof1meansthisprogramisending,and
itisbecausesomethingwentwrong.
SoIwontusetryandcatchanymoreinthisbook,butatleastnowyouknowwhatyouareavoiding
byputtingthrowsException.
Exercise42:GettingDatafromaFile
[Link]
howtoreadinformationthatisalreadyinatextfile.
Ifyoutypeupthiscodeandcompileitandrun,[Link]
[Link],[Link]
probablydonthaveafilelikethis!
Sobeforeyouevenwritethecode,[Link]
lookslikethis:

([Link]?)
Okay,tothecode!
[Link];
[Link];
3
4publicclassGettingFromFile
5{
6publicstaticvoidmain(String[]args)throwsException
7{
8ScannerfileIn=newScanner(newFile("[Link]"));
9
10inta,b,c,sum;
11Stringname;
12
[Link]("Gettingnameandthreenumbersfromfile...");
14name=[Link]();
15a=[Link]();
16b=[Link]();
17c=[Link]();
[Link]();
19
[Link]("done.");
[Link]("Yournameis"+name);
22sum=a+b+c;
[Link](a+"+"+b+"+"+c+"="+sum);
24}
25}
WhatYouShouldSee
Gettingnameandthreenumbersfromfile...done.
YournameisSamanthaShowalter
5+6+7=18
DidyouknowthattheScannerobjectdoesnthavetogetinputfromthehumanatthekeyboard?Itcan
readdatafromtextfiles,too!
WejustcreatetheScannerobjectslightlydifferently:[Link],weuse
newFile("[Link]").[Link](whichIhave
chosentocallfileIn)willbeattachedtothefilelikeastrawstuckintoajuicebox.(Thejuiceboxisthe
textfile,andtheScannerobjectisthestraw.)
[Link]
object,[Link].
Lines15through17aresimple,[Link]
puttingitinthevariables.
Whatifthenextthinginthefileisntaninteger?[Link]
blamethehumananymore:[Link]
it,andinwhatorder.
Online18thefileisclosed,whichmeansyourScannerobjectisntconnectedtoitanymore.
Wasthiseasierthanyouexpectedittobe?Hopefullyso.

StudyDrills
1. [Link](you
donthavetocompileitagain;thecodehasntchangedanditdoesntopenthefileuntilitis
run.)
Exercise43:SavingaHighScore
Nowthatyouknowhowtogetinformationfromfilesandhowtoputinformationinfiles,wecancreate
agamethatsavesthehighscore!
Thisisthecoinflippinggamefromafewexercisesago,butnowthehighscoreissavedfromruntorun.
[Link];
[Link];
[Link];
[Link];
5
6publicclassCoinFlipSaved
7{
8publicstaticvoidmain(String[]args)throwsException
9{
10Scannerkeyboard=newScanner([Link]);
11
12Stringcoin,again,bestName,saveFile="[Link]";
13intflip,streak=0,best;
14
15Filein=newFile(saveFile);
16if([Link]())
17{
[Link]("Savegamefiledoesn'[Link].");
19best=1;
20bestName="";
21}
22else
23{
24Scannerinput=newScanner(in);
25bestName=[Link]();
26best=[Link]();
[Link]();
[Link]("Highscoreis"+best+"flipsinarowby"
+bestName);
29}
30
31
32do
33{
34flip=1+(int)([Link]()*2);
35
36if(flip==1)
37coin="HEADS";
38else
39coin="TAILS";
40
[Link]("Youflipacoinanditis..."+coin);
42
43if(flip==1)
44{
45streak++;
[Link]("\tThat's"+streak+"inarow....");
[Link]("\tWouldyouliketoflipagain(y/n)?");
48again=[Link]();
49}
50else
51{
52streak=0;
53again="n";
54}
55}while([Link]("y"));
56
[Link]("Finalscore:"+streak);
58
59if(streak>best)
60{
[Link]("That'sanewhighscore!");
[Link]("Yourname:");
63bestName=[Link]();
64best=streak;
65}
66elseif(streak==best)
67{
[Link]("[Link].");
69}
70else
71{
[Link]("You'llhavetodobetterthan"+streak+"
ifyouwantahighscore.");
73}
74
75//Savethisnameandhighscoretothefile.
76PrintWriterout=newPrintWriter(newFileWriter(saveFile));
[Link](bestName);
[Link](best);
[Link]();
80}
81}

WhatYouShouldSee
Savegamefiledoesn'[Link].
Youflipacoinanditis...HEADS
That's1inarow....
Wouldyouliketoflipagain(y/n)?y
Youflipacoinanditis...HEADS
That's2inarow....
Wouldyouliketoflipagain(y/n)?y
Youflipacoinanditis...HEADS
That's3inarow....
Wouldyouliketoflipagain(y/n)?n
Finalscore:3
That'sanewhighscore!
Yourname:Mitchell
(Okay,[Link].)
[Link]
evenifthefiledoesntexist.
Online16thereisanifstatement,andintheconditionIcallthecreateNewFile()methodofthe
[Link],itwilldonothingandreturntheBooleanvalue
[Link],itwillcreatethefileemptyandreturnthevaluetrue.
Whentheifstatementistrue,then,[Link]
[Link],thentheresalreadyafilethere,soweusea
[Link],eh?
[Link].
[Link],weprintoutamessagetothateffect
andletthementertheirname.
Iftheytiedthehighscore,wesayso,buttheydontgetanyfameforthat.
[Link],ofcourse.
Onlines75through79wesavethecurrenthighscorealongwiththenameofthehighscorertothefile.
Thismightbeanewscore,oritmightbethepreviousvaluewereadatthebeginningoftheprogram.

StudyDrills
1. Changetheprogramsothatitonlysavestothehighscorefileifithaschanged.
2. [Link]
friendswithyouramazingluckystreak!
Exercise44:CountingwithaForLoop
Asyouhaveseeninpreviousexercises,whileloopsanddowhileloopscanbeusedtotomake
somethinghappenmorethanonce.
[Link]
howmanytimeswewanttodosomething,Javahasaspecialkindofloopdesignedjustformakinga
variablechangevalues:theforloop.
[Link];
2
3publicclassCountingFor
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9intn;
10Stringmessage;
11
[Link]("Typeinamessage,andI'lldisplayitfive
times.");
[Link]("Message:");
14message=[Link]();
15
16for(n=1;n<=5;n++)
17{
[Link](n+"."+message);
19}
20
[Link]("\nNowI'lldisplayittentimesandcountby5s."
);
22for(n=5;n<=50;n+=5)
23{
[Link](n+"."+message);
25}
26
[Link]("\nFinally,threetimescountingbackward.");
28for(n=3;n>0;n=1)
29{
[Link](n+"."+message);
31}
32
33}
34}

WhatYouShouldSee
Typeinamessage,andI'lldisplayitfivetimes.
Message:Howdy,y'all!
[Link],y'all!
[Link],y'all!
[Link],y'all!
[Link],y'all!
[Link],y'all!

NowI'lldisplayittentimesandcountby5s.
[Link],y'all!
[Link],y'all!
[Link],y'all!
[Link],y'all!
[Link],y'all!
[Link],y'all!
[Link],y'all!
[Link],y'all!
[Link],y'all!
[Link],y'all!

Finally,threetimescountingbackward.
[Link],y'all!
[Link],y'all!
[Link],y'all!
[Link].
Thefirstpart(n=1)[Link]
verybeginningoftheloopandusuallysetsastartingvalueforsomevariablethatisgoingtobeusedto
[Link],ourloopcontrolvariableisnanditwillstartwithavalueof1.
Thesecondpart(n<=5)isacondition,[Link]
loopisapretestloopjustlikeawhileloop,whichmeansthatthisconditionistestedbeforetheloop
[Link],[Link],
theloopbodywillbeskippedandtheloopisover.
Thethirdpart(n++)runsaftereachiterationoftheloop,justbeforeitcheckstheconditionagain.
Rememberthat++addsonetoavariable.
Soifweunrollthisloop,thesearethestatementsthatwillhappenandtheirorder:
n=1;
//checkif(n<=5),whichistrue
[Link](1+"."+message);
n++;//sonownis2
//checkif(n<=5),whichistrue
[Link](2+"."+message);
n++;//sonownis3
//checkif(n<=5),whichistrue
[Link](3+"."+message);
n++;//sonownis4
//checkif(n<=5),whichistrue
[Link](4+"."+message);
n++;//sonownis5
//checkif(n<=5),whichistrue
[Link](5+"."+message);
n++;//sonownis6
//checkif(n<=6),[Link]
Noticethatthefirstpartonlyhappenedonce,andthatthethirdparthappenedexactlyasmanytimesas
theloopbodydid.
[Link].(Noticethattheloopcontrol
[Link].)
Thefirstpart(theinitializationexpression)[Link]
[Link],thebodyisexecutedonetimeandthenthethird
partisexecuted.Thethirdpartadds5totheloopcontrolvariable,andthentheconditionischecked
[Link],[Link],theloopstops.
Online28thereisonefinalforloop.Thistimetheloopcontrolvariablestartsat3andtheloop
[Link](the
updateexpression)subtracts1fromtheloopcontrolvariable.
Sowhenshouldyouuseaforloopversusawhileloop?
forloopsarebestwhenweknowinadvancehowmanytimeswewanttodosomething.
Dothistentimes.
Dothisfivetimes.
Pickarandomnumber,anddoitthatmanytimes.
Takethislistofitems,anddoitonetimeforeachiteminthelist.
Ontheotherhand,whileanddowhileloopsarebestforrepeatingaslongassomethingistrue:
Keepgoingaslongastheyhaventguessedit.
Keepgoingaslongasyouhaventgotdoubles.
Keepgoingaslongastheykeeptypinginanegativenumber.
Keepgoingaslongastheyhaventtypedinazero.

StudyDrills
1. Deletethefirstpart(theinitializationexpression)[Link]
correctly,[Link]?
Exercise45:CaesarCipher(LoopingThroughaString)
TheCaesarcipherisaverysimpleformofcryptographynamedafterJuliusCaesar,whouseditto
[Link],eachletterisshiftedupordowninthealphabetbyacertain
[Link],iftheshiftis2,thenallAsinthemessagearereplacedwithC,Bisreplacedwith
D,andsoon.
[Link];
2
3publicclassCaesarCipher
4{
5/**
6*Returnsthecharactershiftedbythegivennumberofletters.
7*/
8publicstaticcharshiftLetter(charc,intn)
9{
10intch=c;
11
12if(![Link](c))
13returnc;
14
15ch=ch+n;
16if([Link](c)&&ch>'Z'||[Link](c)&&ch>'z')
17ch=26;
18if([Link](c)&&ch<'A'||[Link](c)&&ch<'a')
19ch+=26;
20
21return(char)ch;
22}
23
24publicstaticvoidmain(String[]args)
25{
26Scannerkeyboard=newScanner([Link]);
27Stringplaintext,cipher="";
28intshift;
29
[Link]("Message:");
31plaintext=[Link]();
[Link]("Shift(026):");
33shift=[Link]();
34
35for(inti=0;i<[Link]();i++)
36{
37cipher+=shiftLetter([Link](i),shift);
38}
[Link](cipher);
40
41}
42}

WhatYouShouldSee
Message:[Link]
Shift(026):2
[Link]
Didyouknowthatmain()doesnthavetobethefirstfunctionintheclass?Well,[Link]
canappearinanyorder.
Alsoinadditiontoint,double,StringandbooleanthereisabasicvariabletypeIhavent
mentioned:[Link],butitcanonlyholdone
[Link]"Axe",whilechar
literalsinthecodeareinsinglequoteslike'A'.
Startingonline8thereisafunctioncalledshiftLetter().Ithastwoparameters:cisthecharacter
[Link]
shiftLetter('A',2)wouldreturnthecharacter'C'.
Wedontwanttotrytoshiftanythingthatisntaletter,soonline10weusethebuiltinCharacterclass
totellus.
Thenwearegoingtobedoingalittlemathwiththecharacter,sowestorethecharactersUnicodevalue
intoanintonline13tomakethiseasier.Thenonline15weaddthedesiredoffsettothecharacter.
Thiswouldbeit,exceptthatwewanttheoffsettowraparound,solines16through19makesurethat
thefinalvalueisstillaletter.Thenfinallyonline21wetakethevalueofch,castittoachar,and
returnit.
Inmain(),[Link],though,Ineedto
explaintwoStringclassmethods:charAt()andlength().
IfyouhaveaStringyoucangetasinglecharoutofitusingthecharAt()[Link]:
Strings="Howdy";
charc=[Link](2);
//Nowc=='w'
//[Link]()is5
charAt()iszerobased,[Link](0)[Link]
[Link]()tellsyouhowmanycharactersthereareins,[Link]([Link]()1)
getsthefinalcharacter.
[Link]
[Link]
charactersinthemessage.Andtheupdateexpressionwilladd1toieachtime.
Online38,[Link]
[Link]()
function,[Link]
Stringcipher.
Bythetimetheloopends,ithasgonethrougheachletterofthemessageoneatatimeandbuiltupa
newmessagefromtheshiftedversionsoftheletters.
[Link].

StudyDrills
1. Makeanewversionofthisexercisethatgetsthemessagefromatextfileinsteadandcreatesan
encryptedfilewiththeciphertextinsteadofjustprintingitonthescreen.
Exercise46:NestedForLoops
Inprogramming,[Link]
[Link],thenmeanstheinnerloop
willrepeatallitsiterationseverytimetheouterloopdoesonemoreiteration.
1publicclassNestingLoops
2{
3publicstaticvoidmain(String[]args)
4{
5//thisis#1I'llcallit"CN"
6for(charc='A';c<='E';c++)
7{
8for(intn=1;n<=3;n++)
9{
[Link](c+""+n);
11}
12}
13
[Link]("\n");
15
16//thisis#2I'llcallit"AB"
17for(inta=1;a<=3;a++)
18{
19for(intb=1;b<=3;b++)
20{
[Link]("("+a+","+b+")");
22}
23//*Youwilladdalineofcodehere.
24}
25
[Link]("\n");
27
28}
29}

WhatYouShouldSee
A1
A2
A3
B1
B2
B3
C1
C2
C3
D1
D2
D3
E1
E2
E3

(1,1)(1,2)(1,3)(2,1)(2,2)(2,3)(3,1)(3,2)(3,3)

StudyDrills
1. Lookatthefirstsetofnestedloops(CN).Whichvariablechangesfaster?Isitthevariable
controlledbytheouterloop(c)orthevariablecontrolledbytheinnerloop(n)?
2. Changetheorderoftheloopssothatthecloopisontheinsideandthenloopisonthe
[Link]?
3. Lookatthesecondsetofnestedloops(AB).Changetheprint()statementtoprintln().
Howdoestheoutputchange?(Thenchangeitbacktoprint().)
4. [Link]()statementaftertheclosebraceoftheinnerloop(theb
loop),[Link]?
Exercise47:GeneratingandFilteringValues
Nestedforloopsaresometimeshandybecausetheyareverycompactandcanmakesomevariables
changethroughalotofdifferentcombinationsofvalues.
Manyyearsago,astudentposedthefollowingmathproblemtome:
FarmerBrownwantstospendexactly$100.00andwantstopurchaseexactly100
[Link]$10each,goatscost$3.50eachandchickensare$0.50apiece,
thenhowmanyofeachanimalshouldhebuy?
Afterheleft,Ithoughtaboutitforafewsecondsandthenwrotethefollowingprogram.
1publicclassFarmerBrown
2{
3publicstaticvoidmain(String[]args)
4{
5for(ints=1;s<=100;s++)
6{
7for(intg=1;g<=100;g++)
8{
9for(intc=1;c<=100;c++)
10{
11if(s+g+c==100&&10.00*s+3.50*g+0.50*c==100.00)
12{
[Link](s+"sheep,");
[Link](g+"goats,and");
[Link](c+"chickens.");
16}
17}
18}
19}
20}
21}

WhatYouShouldSee
4sheep,4goats,and92chickens.
[Link](justin
frontoftheifstatementonline11willseeonemilliondifferentcombinationsofs,gandcflowby.
Thefirstcombinationattemptedwillbe1sheep,1goat,[Link]
[Link],andnothingwillbeprinted.
Thenthenextcombinationwillbe1sheep,[Link].Then1sheep,1
goat,3chickens.Andsoonupto1sheep,1goatand100chickenswhentheinnerlooprunsitslast
iteration.
Thentheg++online7willexecute,theconditiononline7willchecktomakesuregisstilllessthanor
equalto100(whichitis)andthebodyofthemiddleforloopwillexecuteagain.
Thiswillcausetheinitializationexpressionoftheinnermostlooptorunagain,[Link]
thenextcombinationofvariablethatwillbetestedintheifstatementis1sheep,2goatsand1chicken.
Then1sheep,2goats,2chickens,then1sheep,2goats,[Link].
Bytheendall100*100*100combinationshavebeentestedand999,[Link]
computersareveryfast,theanswerappearsinstantaneously.
SincecurlybracesareoptionalinJavawhenthereisonlyasinglelineofcodeinthebodyofanif
statementorinthebodyofaforloop,Icouldhavemadethecodeevenmorecompact:
1publicclassFarmerBrownCompact
2{
3publicstaticvoidmain(String[]args)
4{
5for(ints=1;s<=100;s++)
6for(intg=1;g<=100;g++)
7for(intc=1;c<=100;c++)
8if(s+g+c==100&&10.00*s+3.50*g+0.50*c==100.00)
[Link](s+"sheep,"+g+"goats,and"+c+"
chickens.");
10}
11}

[Link]
wewouldhavetowriteifwehadsolvedthisprogramwithwhileloopsinsteadofforloops:
1publicclassFarmerBrownWhile
2{
3publicstaticvoidmain(String[]args)
4{
5ints=1;
6while(s<=100)
7{
8intg=1;
9while(g<=100)
10{
11intc=1;
12while(c<=100)
13{
14if(s+g+c==100&&10.00*s+3.50*g+0.50*c==100.00)
15{
[Link](s+"sheep,");
[Link](g+"goats,and");
[Link](c+"chickens.");
19}
20c++;
21}
22g++;
23}
24s++;
25}
26}
27}
Thewhileloopversionisalsomorefragilebecauseitwouldbeeasytoaccidentallyforgettoreseta
[Link]
togettocompilebutitismorelikelytohavesubtlelogicalerrorsthatcompilebutdontworkas
intended.

StudyDrills
1. Ourcodeworks,butitisnotasefficientasitcouldbe.(Forexample,thereisnoreasontomake
[Link]
theloopboundstomakethecombinationslesswasteful.
Exercise48:ArraysManyValuesinaSingleVariable
[Link]
kindofneat.
InJava,anarrayisatypeofvariablewithonename(identifier)butcontainingmorethanone
[Link],[Link],thatsgood
[Link]!
1publicclassArrayIntro
2{
3publicstaticvoidmain(String[]args)
4{
5String[]planets={"Mercury","Venus","Earth","Mars","Jupiter",
"Saturn","Uranus","Neptune"};
6
7for(Stringp:planets)
8{
[Link](p+"\t"+[Link]());
10}
11}
12}

WhatYouShouldSee
MercuryMERCURY
VenusVENUS
EarthEARTH
MarsMARS
JupiterJUPITER
SaturnSATURN
UranusURANUS
NeptuneNEPTUNE
[Link]:noticethesquare
[Link]
Stringsandtheyareseparatedintodistinctslotssowecanaccessthemoneatatime.
[Link]
[Link],thenthewholeinitializerlistisincurly
[Link].
Thesecondnewthinginthisexerciseisanewkindofforloop.(Thisissometimescalledaforeach
loop,sinceitworksabitlikealoopinanotherprogramminglanguagewherethekeywordactuallyis
foreachinsteadoffor.)
[Link]:foreachStringpin
thearrayplanets.
SoinsidethebodyofthisforeachlooptheStringvariablepwilltakeonacopyofthevalueofeach
[Link],thefirsttimethroughtheloop,pwillcontainacopyofthefirst
valueinthearray("Mercury").Thenthesecondtimethroughtheloop,pwillcontainacopyofthe
secondvalueinthearray("Venus").Andsoon,[Link]
theloopwillautomaticallystop.
Insidethebodyoftheloop(online9)wearejustprintingoutthecurrentvalueofpandanuppercase
[Link],Iguess.
Thisnewkindofforlooponlyworkswithcompoundvariableslikethis:variablesthathaveonename
[Link],butwewontbe
lookingatanyoftheothersinthisbook.
Arraysareabigdeal,[Link]
whatishappeninginthisassignmentbeforethrowingmoreonyourplate.
Exercise49:FindingThingsinanArray
Morewitharrays![Link]
usinghereissometimescalledalinearsearchbecauseitstartswiththefirstslotofthearrayandlooks
there,thenmovestothesecondslot,thenthethirdandsoondowntheline.
[Link];
2
3publicclassArrayLinearSearch
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9int[]orderNumbers={12345,54321,78753,101010,8675309,31415,
271828};
10inttoFind;
11
[Link]("Thereare"+[Link]+"ordersin
thedatabase.");
13
[Link]("Orders:");
15for(intnum:orderNumbers)
16{
[Link](num+"");
18}
[Link]();
20
[Link]("Whichordertofind?");
22toFind=[Link]();
23
24for(intnum:orderNumbers)
25{
26if(num==toFind)
27{
[Link](num+"found.");
29}
30}
31}
32}

WhatYouShouldSee
Thereare7ordersinthedatabase.
Orders:123455432178753101010867530931415271828
Whichordertofind?78753
78753found.
[Link].12345is
thefirstslot,[Link].
[Link]
variableisreadonly(youcanretrieveitsvaluebutnotchangeit)[Link],
sincethearrayorderNumbershassevenslots,thevariableorderNumbers.lengthisequalto7.
Thisisusedonline12.
[Link]
[Link],numwilltakeoneachvaluein
thearrayoneatatimeanddisplaythemall.
[Link]
[Link],wesayso.
(Youhavetoimaginethatwehavehundredsorthousandsofordersinthedatabase
insteadofjustsevenandthatweprintoutmorethanjusttheordernumberwhenwe
[Link].)

StudyDrills
1. [Link]
variableonceuponline10andthenremovedtheintfrombothloops?Tryitandsee.
2. Trytochangethecodesothatiftheordernumberisnotfound,itprintsoutasinglemessage
[Link],giveitagoodeffortbeforemovingonto
thenextexercise.
Exercise50:SayingSomethingIsNOTinanArray
Inlife,thereisagenerallackofsymmetrybetweencertaintypesofstatements.
Awhitecrowexists.
[Link],[Link].
Nowhitecrowsexist.
Thisstatementismuchhardertoprovebecausetoproveitwehavetogatherupeverythingintheworld
[Link],onlythencanwe
safelysaythatnoneexist.
Hopefullyyoutriedthestudydrillinyesterdaysexercise.
[Link];
2
3publicclassItemNotFound
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner([Link]);
8
9String[]heroes={
10"Abderus","Achilles","Aeneas","Ajax","Amphitryon",
11"Bellerophon","Castor","Chrysippus","Daedalus","Diomedes",
12"Eleusis","Eunostus","Ganymede","Hector","Iolaus","Jason",
13"Meleager","Odysseus","Orpheus","Perseus","Theseus"};
14Stringguess;
15booleanfound;
16
[Link]("PopQuiz!NameanymortalherofromGreekmythology:");
18guess=[Link]();
19
20found=false;
21for(Stringhero:heroes)
22{
23if([Link](hero))
24{
[Link]("That'scorrect!");
26found=true;
27}
28}
29
30if(found==false)
31{
[Link]("No,"+guess+"wasn'taGreekmortalhero.");
33}
34}
35}

WhatYouShouldSee
PopQuiz!NameanymortalherofromGreekmythology:Hercules
No,Herculeswasn'taGreekmortalhero.
Moststudentswanttosolvethisproblembyputtinganotherifstatement(oranelse)insidetheloop
[Link],itisokaytosaysoas
[Link],youhavetowaituntiltheloopis
overbeforeyouknowforsure.
[Link]
[Link]
thinghappenedornot.
MyflagvariableisaBooleancalledfound,[Link],we
[Link]
changetheflagtofalse,soonceithasbeenflippedtotrueitwillstaythatway.
Thenonline30,aftertheloopisdone,[Link],thenweknowthe
ifstatementinsidetheloopwasnevertrueandthereforeweneverfoundwhatwewerelookingfor.
Exercise51:ArraysWithoutForeachLoops
Asyoumightnoticedbynow,[Link]
situationswherewhatwehavebeendoingwontwork.
Aforeachloopcantiteratethroughanarraybackward;itcanonlygoforward.
[Link]
variableisareadonlycopyofwhatsinthearrayandchangingitdoesntchangethearray.
Inaddition,wehaveonlybeenputtingvaluesintoanarrayusinganinitializerlist(thecurlybraces
thing),whichhasitsownlimitations:
Aninitializerlistonlyworkswhenthearrayisbeingdeclared;youcantuseitelsewhereinthe
code.
Aninitializerlistisbestsuitedforrelativelysmallarrays,ifyouhave1000valuesinthearray,
aninitializerlistwillbenofun.
Initializerlistsdonthelpusifwewantthevaluesinthearraytocomefromafileorsomeother
placewedonthavewhenwearetypingthecode.
[Link],itismorecommonthanwhat
[Link],wecanaccesstheslotsofanarray
individually.
1publicclassArraySlotAccess
2{
3publicstaticvoidmain(String[]args)
4{
5int[]arr=newint[3];
6inti;
7
8arr[0]=0;
9arr[1]=0;
10arr[2]=0;
11
[Link]("Arraycontains:"+arr[0]+""+arr[1]+""+
arr[2]);
13
14//Filleachslotofthisarraywitharandomnumber1100
15arr[0]=1+(int)([Link]()*100);
16arr[1]=1+(int)([Link]()*100);
17arr[2]=1+(int)([Link]()*100);
18
19//Displaythemagain.
[Link]("Arraycontains:"+arr[0]+""+arr[1]+""+
arr[2]);
21
22//Thisisabitsilly,buttrytounderstandit.
23i=0;
24arr[i]=1+(int)([Link]()*100);
25i=1;
26arr[i]=1+(int)([Link]()*100);
27i=2;
28arr[i]=1+(int)([Link]()*100);
29
30//Displaythemagain.
[Link]("Arraycontains:");
32i=0;
[Link](arr[i]+"");
34i=1;
[Link](arr[i]+"");
36i=2;
[Link](arr[i]+"");
[Link]();
39
40//[Link]
headed?
41i=0;
42arr[i]=1+(int)([Link]()*100);
43i++;
44arr[i]=1+(int)([Link]()*100);
45i++;
46arr[i]=1+(int)([Link]()*100);
47i++;
48
49//Displaythemagain.
[Link]("Arraycontains:");
51i=0;
[Link](arr[i]+"");
53i++;
[Link](arr[i]+"");
55i++;
[Link](arr[i]+"");
57i++;
[Link]();
59
60//Ah!Let'sjustusearegular'for'loop!
61for(i=0;i<[Link];i++)
62{
63arr[i]=1+(int)([Link]()*100);
64}
65
66//Displaythemagain.
[Link]("Arraycontains:");
68for(i=0;i<[Link];i++)
69{
[Link](arr[i]+"");
71}
[Link]();
73}
74}

WhatYouShouldSee
Arraycontains:000
Arraycontains:984918
Arraycontains:83771
Arraycontains:627432
Arraycontains:401754
[Link][3]meansthatthe
[Link],everyslotinthearraystartsoutwithavalueof
[Link],itscapacitycantbechanged.
Onlines8through10thereisasurprise.Thearrayhas3slots,buttheslotnumbersare0based.(The
[Link]
(INNduhSEEZ)butmostpeoplejustsayindexes.)
[Link],[Link]
[Link].lengthis3,butthereisnotaslotwith
[Link],buteventuallyyouwilllearn.
Anyway,lines8through10storethevalue0intoallthreeslotsinthearray.(Whichisthevaluethat
wasalreadyinthem,sothiscodedoesntdoanythinguseful.)
Online12weprintoutallthreecurrentvaluesinthearraysoyoucanseethattheyreallzero.
[Link]
line20.
[Link].
Forgettingaboutwhyyoumightwanttodoit,doyouseethatline24isessentiallyidenticaltoline15?
[Link]?Theindexdependsonthecurrent
[Link]?
Soonline25wechangethevalueofifrom0to1.Thenonline26westorearandomvalueintheslot
indexedbythevalueofi,[Link]?Weird,butlegal.
Ihaveusedsimilarshenanigansonlines31through38todisplayallthevaluesonthescreenagain.
Now,[Link],ittookme8linesof
codetodowhatIhadbeendoinginoneline.(Staywithme.)
Onlines40through47wedosomethingthatmightevenbeworsethanlines22through28.Lines41
and42arethesame,butinsteadofputtinga1directlyintoionline43,Ijustsayincreasethevalueof
iby1.Soihadcontaineda0;itcontainsa1afterline43isdone.
Prettymuchtheonlyadvantagetothisapproachisthatatleastcopyandpasteiseasier.Lines42and43
[Link],likebyteforbytethe
same.
Wedisplaytheminasimilarsillyfashiononlines50through58.
[Link]
[Link]
variableincreasebyoneeachtime,right?
Thatsright:[Link],amI?
Lines61through64arethesameaslines41through47exceptthatwelettheforloophandlethe
[Link](thefirstpart)oftheforloopsets
itostartat0,[Link]
[Link](whichis3).Andnotethatthatislessthan,notlessthanor
equalto,[Link](thethirdpart)justadds1toieachtime.
Lines67through72displaythevaluesonthescreen.
Heresthething:thissortofcodeonlines61through72mightseemalittlebitcomplex,butworking
[Link]
Ihavewrittenaforloopjustlikethatforworkingwithanarray.
Infact,ifyourquestionisHowdoI________anarray?(Fillintheblankwithanytaskyoulike.)The
[Link].

StudyDrills
1. Atthetopofthecode,[Link]
[Link]?Thoseforloopsatthebottom
mighthavebeenalittlemoreworktowriteandtounderstand,butoncewrittentheyworkjustas
[Link].
Exercise52:LowestTemperature
Beforewemoveonfromarrays,thisexercisewillpulltogetherfunctions,loops,arraysandreading
fromfilestodosomething(hopefully)interesting!
IhavecreatedatextfilecontainingtheaveragedailytemperatureinAustin,TexasfromJanuary1,1995
throughJune23,[Link],sothereareatotalof6717temperaturesin
[Link]:
[Link]

[Link](directlyoffthe
Internet,even)intoanarrayofdoublesandthenusealooptofindthelowesttemperatureinthatentire
171/[Link]?Letsgo.
[Link];
[Link];
3
4publicclassLowestTemperature
5{
6publicstaticvoidmain(String[]args)throwsException
7{
8double[]temps=
arrayFromUrl("[Link]
9
[Link]([Link]+"temperaturesindatabase.");
11
12doublelowest=9999.99;
13
14for(inti=0;i<[Link];i++)
15{
16if(temps[i]<lowest)
17{
18lowest=temps[i];
19}
20}
21
[Link]("Thelowestaveragedailytemperaturewas");
[Link](lowest+"F("+fToC(lowest)+"C)");
24}
25
26publicstaticdouble[]arrayFromUrl(Stringurl)throwsException
27{
28Scannerfin=newScanner((newURL(url)).openStream());
29intcount=[Link]();
30
31double[]dubs=newdouble[count];
32
33for(inti=0;i<[Link];i++)
34dubs[i]=[Link]();
[Link]();
36
37returndubs;
38}
39
40publicstaticdoublefToC(doublef)
41{
42return(f32)*5/9;
43}
44
45}
WhatYouShouldSee
6717temperaturesindatabase.
Thelowestaveragedailytemperaturewas22.1F(5.499999999999999C)
(IfyouhavetorunthisprogramonamachinewithoutInternetaccess,[Link]
youknowhowtoreadfromatextfilealready,youcouldmodifyityourselftoreadfromalocalfile(a
fileinthesamefolderasyourcodeinsteadofontheInternet).ButifyouarelazyIhavelistedan
alternateversiondownbelow.)
Well,rightoffthebatIhavethrownacurveball.Online8wedeclareanarrayofdoublesnamed
temps,butinsteadofjustdoingthenormalthingandsettingitscapacitylikethis:
double[]temps=newdouble[6717];
Iinitializethearraywithanarraythatisthereturnvaluefromafunction!Soletslookdownatthe
functionbeforeweproceed.
[Link]()andithasone
parameter:[Link]?Itreturnsnotadoublebutdouble[](anarrayof
doubles).
Online28wecreateaScannerobjecttoreaddatafromafile,butinsteadofgettingthedatafromafile,
[Link].
Now,[Link],
[Link]
[Link].ThenafterthatIhave
6717linesoftemperatures,oneperline.
[Link]
[Link]
file,[Link]
trick,eh?
Online31wedefineanarrayofdoubleswithcountslots.(Currently6717.)
Online33theresaforloopthatiteratesthrougheachslotinthearray,andonline34wereada
doublefromthefileeachtime([Link]())andstoreitintothenextindexedslotin
array.
Thenwhentheloopends,Iclose()thefile.Thenonline37thearrayisreturnedfromthefunction
andthatarrayiswhatisstoredintothearraytempsbackonline8ofmain().
Online10weprintoutthecurrentlengthofthearraytomakesurenothingwentwrongwiththe
reading.
[Link]
firstweputareallylargevalueinthere,though.
[Link],since
thearrayhas6717valuesinit,theindexeswillrunfrom0to6716.
Line16comparesthevaluewearecurrentlylookingatinthearray(dependingonthecurrentvalueof
i).Ifthatvalueislessthanwhateverisinlowest,thenwehaveanewrecord!Online18wereplacewhat
usedtobeinlowestwiththisnewsmallervalue.
[Link],the
variablelowestnowactuallydoescontainthesmallestvalue.
Thereisasmallfunctiondownonlines40through43toconvertatemperaturefromdegreesFahrenheit
todegreesCelsius.Soonline23wedisplaythelowesttemperatureasitcamefromthefileandalso
convertedtoCelsius.
Youmaybethinkingthat22.1F(5.5C)[Link],[Link]
rememberthatthetemperaturesarentthelowesttemperatureoftheday,theyaretheaverageof24
hourlytemperaturesamplesforeachday.

StudyDrills
1. Changethecodetodisplayboththelowestaveragedailytemperatureandandthehighest.
2. Trytofindanothertemperaturefileonlineforacityclosertowhereyouliveandchangeyour
codetoreadfromitinstead!
(Imentioneditabove,butthisisthemodifiedcodetoreadthetemperaturedatafromalocalfileincase
youcantrunyourJavaprogramonamachinewithInternetaccess.)
[Link];
[Link];
3
4publicclassLowestTemperatureLocal
5{
6publicstaticvoidmain(String[]args)throwsException
7{
8double[]temps;
9doublelowest=9999.99;
10
11//Readvaluesfromfile
12Scannerfin=newScanner(newFile("[Link]"));
13temps=newdouble[[Link]()];
14
[Link]([Link]+"temperaturesindatabase.");
16
17for(inti=0;i<[Link];i++)
18temps[i]=[Link]();
[Link]();
20
21for(inti=0;i<[Link];i++)
22if(temps[i]<lowest)
23lowest=temps[i];
24
[Link]("Thelowestaveragedailytemperaturewas");
[Link](lowest+"F("+fToC(lowest)+"C)");
27}
28
29publicstaticdoublefToC(doublef){return(f32)*5/9;}
30}
Exercise53:MailingAddresses(Records)
[Link]++theyare
[Link]
typeandtheyaredistinguishedbyindex(slotnumber).Arecordisafewdifferentvaluesinonevariable
butthevaluescanbedifferenttypesandtheyaredistinguishedbyname(usuallycalledafield).12
[Link].(Thelinethatsays
[Link].)
1classAddress
2{
3Stringstreet;
4Stringcity;
5Stringstate;
6intzip;
7}
8
9publicclassMailingAddresses
10{
11publicstaticvoidmain(String[]args)
12{
13Addressuno,dos,tres;
14
15uno=newAddress();
[Link]="191MarigoldLane";
[Link]="Miami";
[Link]="FL";
[Link]=33179;
20
21dos=newAddress();
[Link]="3029LoshLane";
[Link]="Crafton";
[Link]="PA";
[Link]=15205;
26
27tres=newAddress();
[Link]="2693HannahStreet";
[Link]="Hickory";
[Link]="NC";
[Link]=28601;
32
[Link]([Link]+"\n"+[Link]+","+[Link]+"
"+[Link]+"\n");
[Link]([Link]+"\n"+[Link]+","+[Link]+"
"+[Link]+"\n");
[Link]([Link]+"\n"+[Link]+","+[Link]
+""+[Link]+"\n");
36}
37}

WhatYouShouldSee
191MarigoldLane

12 Theresonlyoneproblemwillallofthis:[Link]
withnomethodsandonlypublicvariablesitworksjustlikeastructevenifitisnttheJavaWay.
[Link]
[Link]
waythatworksperfectlyfineandwouldbeverynicecodeinlotsofdifferentprogramminglanguages.
SomediehardobjectorientedJavaheadisgoingtostumbleacrossthisexerciseandsendmeannastyemailthatIamDoing
ItWrongandwhyamIfillingthesepoorkidsheadswithlies?Oh,well.
Miami,FL33179

3029LoshLane
Crafton,PA15205

2693HannahStreet
Hickory,NC28601

Souponlines1through7wehavedefinedarecordcalledAddress.
(Iknowitsaysclass,[Link]
callthisarecordanyway,[Link]
JavaprogrammerthatlovesobjectorientedprogrammingandifyoucallitastructatleasttheCand
C++programmerswillunderstandyou.)
[Link]
[Link].
Thenonline9ourrealclassstarts.
Online13wedeclarethreevariablesnameduno,[Link]
Strings;[Link].
Online15wehavetostoreanAddressobjectinthevariablebecauserememberweonlydeclaredthe
variablesandtheyhaventbeeninitializedyet.
OncethatistakencareofyouwillseethatwecanstoretheString"191MarigoldLane"intothe
streetfieldoftheAddressrecordnameduno,andthatsexactlywhatwedoonline16.
Line17storestheString"Miami"intothecityfieldoftherecorduno.
ImnotgoingtobothertoexplainwhatishappeningfortherestoftheprogrambecauseIthinkitis
[Link]
Strings,[Link].

StudyDrills
1. CreateafourthAddressvariableonline13andchangethecodetoputyourmailingaddressinit.
Dontforgettoprintitoutatthebottom.

FrequentlyAskedQuestions
Wheredidyougettheseaddresses?
[Link]
realaddress,letmeknowandIllchangeit.
Exercise54:RecordsfromaFile
[Link]
ofaloopthatreadsintheentirefile,nomatterhowlongitis.
IfyourunthisprogramonamachinethatisntconnectedtotheInternet,thiscodewontworkas
written,[Link],whichyoucandownloadifyou
needto.
[Link]

[Link].(Thelinethatsaysclass
[Link].)
[Link];
2
3classActor
4{
5Stringname;
6Stringrole;
7Stringbirthdate;
8}
9
10publicclassActorList
11{
12publicstaticvoidmain(String[]args)throwsException
13{
14Stringurl="[Link]
15//ScannerinFile=newScanner([Link]("[Link]"));
16ScannerinFile=newScanner(([Link](url)).openStream());
17
18while([Link]())
19{
20Actora=getActor(inFile);
[Link]([Link]+"wasbornon"+[Link]);
[Link]("andplayedtheroleof"+[Link]);
23}
[Link]();
25}
26
27publicstaticActorgetActor(Scannerinput)
28{
29Actora=newActor();
[Link]=[Link]();
[Link]=[Link]();
[Link]=[Link]();
33
34returna;
35}
36}

WhatYouShouldSee
SeanBeanwasbornon19590417andplayedtheroleofEddard'Ned'Stark
MarkAddywasbornon19640114andplayedtheroleofRobertBaratheon
NikolajCosterWaldauwasbornon19700727andplayedtheroleofJaime
Lannister
MichelleFairleywasbornon1964andplayedtheroleofCatelynStark
ThistimeourrecordiscalledActorandhasthreefields,allofwhichareStrings.
[Link]
[Link]?Youonlyneedtoimportaclassifyouwant
tobeabletotypetheshortversionoftheclassname.
Inthiscase,[Link],Icouldhavejustwritten:
ScannerinFile=newScanner((newURL(url)).openStream());
//insteadof
ScannerinFile=newScanner(([Link](url)).openStream());
SometimesifIamgoingtobeusingaclassonlyonce,Idratherjustusethefullnameinmycode
insteadofbotheringtoimportit.Iusedthesametrickonline15;[Link]
Ijustusedthefullclassnamehere.
(IfyourmachinedoesnthaveInternetaccess,removethetwoslashesatthebeginningofline15sothat
itisnolongeracommentandthenaddtwoslashesatthebeginningonline16tomakeitacomment.
ThentheprogramwillreadthefilelocallyinsteadofovertheInternet.)
WhetheryouopenthefilefromtheInternetoryourownmachine,afterline17wehaveaScannerobject
namedinFilewhichisconnectedtoatextfile.
Alotofthetimewhenwearereadingfromatextfile,wedontknowinadvancehowlongitisgoingto
[Link]:storingthenumber
[Link]:justusea
loopthatrepeatsuntilwereachtheendofthefile.
[Link]()methodoftheScannerobjectwillreturntrueifthereismoredatathathasntbeen
[Link].Soonline18wecreateawhileloopthat
[Link]()continuestoreturntrue.
Beforewelookatline20letusskipdowntolines27through35whereIhavecreatedafunctionthat
willreadallthedataforasingleActorrecordfromthefile.
[Link]:aScannerobject!Thatsright,youpassinan
[Link]
[Link].
IfwearegoingtoreturnanActorobjectfromthefunctionweneedavariableoftypeActorto
return,[Link]
[Link]
short,meaninglessnamelikeaisperfectlyfine.
Lines30through32readthreelinesfromthetextfileandstorethemintothethreefieldsoftherecord.
Thenthefunctionhasdoneitsjobandwereturntherecordbackuptoline20inmain().
WhymustwecreateanActorvariablenamedahereinmain()andalsodowninthefunction?
[Link](akavisible)withintheblockinwhichitwas
[Link]
itisnotthevariableitselfwhichisreturnedbutacopyofthevalueofthevariable.
ThereisanActorvariablecalledadeclared(anddefined)online20inmain(),butthatvariable
[Link]
calledadeclared(anddefined)online29inthegetActor()function,butitgoesoutofscopewhen
theclosecurlybraceoccursonline35.
Okay,[Link]().
WepassintheopenScannerobjectinFileastheargumenttothefunctionanditreturnstousanActor
objectwithallitsfieldsfilledin.
(WhyistheargumentcalledinFileandtheparameternamedinput?Becausetheyarenotthesame
variable.Theparameterinputisdeclaredonline27andgetsacopyofthevaluefromtheargument
[Link].)
Afterallthat,lines21and22areprettyboring:theysimplydisplaythevaluesofallthefieldsofthe
record.Online23thelooprepeatsbackuptochecktheconditionagain:nowthatwehavereadanother
recordfromthefile,doesthefilestillhavemore?Ifso,[Link],skipdowntoline24where
weclosethefile.
Noticethatbothinthefunctionandinthewhileloopinmain()thevariableaonlyholdsonerecord
[Link],butwhenthe
programisfinishingitslasttimethroughtheloop,[Link]
theotherrecordsarestillinthefileandhavebeendisplayedonthescreen,buttheirvaluesarenot
currentlybeingheldinanyvariables.
Wecanfixthat,butnotuntilthenextexercise.
Exercise55:AnArrayofRecords
Recordsaregreatandarraysarebetter,butthereisnotmuchinthislifeyoucantcodewhenyouput
recordsintoanarray.
1classStudent
2{
3Stringname;
4intcredits;
5doublegpa;
6}
7
8publicclassStudentDatabase
9{
10publicstaticvoidmain(String[]args)
11{
12Student[]db;
13db=newStudent[3];
14
15db[0]=newStudent();
16db[0].name="Esteban";
17db[0].credits=43;
18db[0].gpa=2.9;
19
20db[1]=newStudent();
21db[1].name="Dave";
22db[1].credits=15;
23db[1].gpa=4.0;
24
25db[2]=newStudent();
26db[2].name="Michelle";
27db[2].credits=132;
28db[2].gpa=3.72;
29
30for(inti=0;i<[Link];i++)
31{
[Link]("Name:"+db[i].name);
[Link]("\tCredithours:"+db[i].credits);
[Link]("\tGPA:"+db[i].gpa+"\n");
35}
36
37intmax=0;
38for(inti=1;i<[Link];i++)
39if(db[i].gpa>db[max].gpa)
40max=i;
41
[Link](db[max].name+"hasthehighestGPA.");
43}
44}

WhatYouShouldSee
Name:Esteban
Credithours:43
GPA:2.9

Name:Dave
Credithours:15
GPA:4.0

Name:Michelle
Credithours:132
GPA:3.72
DavehasthehighestGPA.
Whenyouseethesquarebracketsjusttotherightofsomethinginavariabledefinition,thatsanarray
[Link],sincethisbookisalmostover,maybeIshouldexplainthatpublicstatic
[Link].
publicstaticvoidmain(String[]args)
[Link]:an
arrayofStringsnamedargs(whichisshortforarguments).Thefunctiondoesnt
returnanyvalue;itisvoid.
Anyway.
[Link],justa
[Link]
intn;
[Link],buttheresnonumberinityet.n
[Link],onceline12hasfinishedexecuting,dbisavariablethat
couldrefertoanarrayofStudents,butisstillundefined.
Fortunatelywedonthavetowaitlong;line13initializesdbbycreatinganactualarrayofStudentswith
[Link],db.lengthis3anddbhasthreelegalindexes:0,1and2.
Okay,atthispoint,[Link]
variables,eachofwhichcanpotentiallyholdaStudentrecord,[Link]
thearrayareundefined.
(Technicallytheycontainthevaluenull,whichisthespecialvaluethatreference
variablesinJavahavewhentheresnoobjectinthemyet.)
Soonline15itisimportantthataStudentobjectiscreatedandstoredintothefirstslot(index0)ofthe
array.Thenonline16wecanstoreavalueintothenamefieldoftheStudentrecordwhichisinindex0
ofthearraydb.
Letstraceitfromtheoutsidein:
expression type description
db Student[] anarrayofStudentrecords
db[0] Student asingleStudentrecord(thefirstone)
db[0].name String thenamefieldofthefirstStudentinthearray
[Link] error thewholearraydoesnthaveasinglenamefield

Soline16storesavalueintothenamefieldofthefirstrecordinthearray.Lines17and18storevalues
intotheremainingfieldsinthatrecord.Lines20through28createthenfilltheothertworecordsinthe
array
Onlines30though34weusealooptodisplayallthevaluesonthescreen.
[Link].
[Link];itis
goingtoholdonlyitsindex.
SowhenIput0intomaxImeanAsthispointinthecode,asfarasIknow,thehighestscoringstudent
[Link],butsincewehaventlookedatanyofthevaluesinthedatabase
yetitisasgoodastartingplaceasany.
[Link],however,thattheloop
startswithindex1(thesecondslot).Why?
Becausemaxisalready0.Soifistartedat0toothentheifstatementwouldbecomparing
if(db[0].gpa>db[0].gpa)
whichisawaste.Sobystartingiat1,thenthefirsttimethroughthelooptheifstatementmakesthe
followingcomparisoninstead:
if(db[1].gpa>db[0].gpa)
IfDavesGPAisgreaterthanEstebansGPA,thenchangemaxfrom0tothecurrentvalueofi(1).
Sobythetimetheloopisover,[Link]
exactlywhatwedisplayonline42.

StudyDrills
1. [Link]
[Link]?
2. [Link]
studentahigherGPAthanDaveandconfirmthatthecodecorrectlylabelsthemashavingthe
highestGPA.
3. Changethecodesothatitfindsthepersonwiththefewestcreditsinsteadofthepersonwiththe
highestGPA.
Exercise56:ArrayofRecordsfromaFile(Temperatures
Revisited)
[Link]
needtodownloadacopyofthisfileorifyourcomputercanjustopenitfromtheInternet.
[Link]

UnlikealltheotherfilesyouhaveusedsofarinthisbookthisdatafileisexactlythewayIdownloaded
[Link]:
1. Thereisnonumberinthefirstlineofthefiletellingushowmanyrecordsthereare.
2. Inadditiontothetemperatureeachrecordalsohasthemonth,dayandyearforthesample.
3. [Link],Weuse99asanodataflagwhendataarenot
available.
[Link].
[Link];
2
3classTemperatureSample
4{
5intmonth,day,year;
6doubletemperature;
7}
8
9publicclassTemperaturesByDate
10{
11publicstaticvoidmain(String[]args)throwsException
12{
13Stringurl=
"[Link]
14ScannerinFile=newScanner(([Link](url)).openStream());
15
16TemperatureSample[]tempDB=newTemperatureSample[10000];
17intnumRecords,i=0;
18
19while([Link]()&&i<[Link])
20{
21TemperatureSamplee=newTemperatureSample();
[Link]=[Link]();
[Link]=[Link]();
[Link]=[Link]();
[Link]=[Link]();
26if([Link]==99)
27continue;
28tempDB[i]=e;
29i++;
30}
[Link]();
32numRecords=i;
33
[Link](numRecords+"dailytemperaturesloaded.");
35
36doubletotal=0,avg;
37intcount=0;
38for(i=0;i<numRecords;i++)
39{
40if(tempDB[i].month==11)
41{
42total+=tempDB[i].temperature;
43count++;
44}
45}
46
47avg=total/count;
48avg=roundToOneDecimal(avg);
[Link]("Averagedailytemperatureover"+count+"days
inNovember:"+avg);
50}
51
52publicstaticdoubleroundToOneDecimal(doubled)
53{
[Link](d*10)/10.0;
55}
56}

WhatYouShouldSee
6717dailytemperaturesloaded.
Averagedailytemperatureover540daysinNovember:59.7
Lines3through7declareourrecord,whichwillstoreasingleaveragedailytemperaturevalue(a
double)butalsohasfieldsforthemonth,dayandyear.
[Link],[Link]
providingacapacityandwedontknowthecapacityweneeduntilweseehowmanyrecordsareinthe
[Link]:
1. [Link]
[Link],butthatsomethingelseisbeyondthescope
ofthisbook.
2. [Link]
[Link].
3. [Link]
manyrecordsyouactuallyhavewhilereadingtheminandusethatcountinsteadofthearrays
[Link],[Link]
requirescompromise,andthisisoneofthem.
Soline16declaresthearrayanddefinesittohavetenthousandslots:bigenough.
[Link]
[Link]
moreintegersinitandwehaventrunoutofcapacityinourarray.
Justbecausewetookashortcutbymakingourarraybigenoughdoesntmeanwearegoingtobe
[Link]
earlyratherthanblowuptheprogramwithanArrayIndexOutOfBoundsexception.
Line21definesaTemperatureSamplerecordnamede.Lines22through25loadthenextfewvalues
fromthefileintotheappropriatefieldsofthatrecord.
But![Link]
99,soweputinanifstatementonline26todetectthatbeforeweputthemintoourdatabase.
Thenonline27thereissomethingnew:[Link]
[Link]
backuptothetopforthenextiteration.
Thiseffectivelythrowsawaythecurrent(invalid)recordbecauseitskipslines28and29,whichstore
thecurrentrecordinthenextavailableslotinthearrayandthenincrementtheindex.
Somepeopledontliketousecontinueandwouldwriteitlikethis:
if([Link]!=99)
{
tempDB[i]=e;
i++;
}
Andthatsperfectlyfine,too.Onlyputthisentryintothearraywhenthetemperatureisnot99.I
[Link]
whichevermakesthemostsensetoyou.
Oncetheloopisdoneonline31wemakesuretoclosethefileandthenstorethefinalindexinto
[Link],wemadethearray
biggerthanweneededandthelast3283slots(inthisexample)[Link]
numRecordsslightlymoreefficient,wecanavoidexamininganyinvalidrecordsthatway.
Online34wedisplaythenumberofrecordsonthescreen,whichcanhelpyoutoseeifanythingwent
wrongwhilereading.
Lines36through45loopthroughallourrecords.Anyrecordwithamonthfieldof11(November)gets
addedtoarunningtotal,andwealsocountthetotalnumberofmatchingrecordswhileweareatit.
Thenwhenthatloopisover,wecangettheaveragedailytemperatureofallNovemberdaysinthe
databasebydividingthesumbythecount.
Now,[Link]
onlydoesthislookbadbutitsnotcorrect:alltheinputtemperatureswereonlyaccuratetoatenthofa
[Link].
[Link]
haveabuiltinfunctionforthisasfarasIknow,butitdoeshaveabuiltinfunctiontoroundtothe
nearestwholenumber:[Link]().SoImultiplythenumberbyten,rounditandthendivideby
[Link].
Line48passestheaveragetemperatureastheargumenttomyfunctionandthentakestherounded
returnvalueandstoresthatasthenewvalueofavg.

StudyDrills
1. VisittheUniversityofDaytonstemperaturearchiveanddownloadafilewithtemperaturedata
foracitynearyou!Makeyourcodereaddatafromthatfileinstead.
2. Changethecodetofindoutotherthings,likethehighesttemperatureinFebruaryorwhatever
suitsyourfancy.
3. [Link]:
TemperatureSamplets=tempDB[0];
[Link](ts);
[Link];itisattempting
[Link]?
Trychangingtheindextopulldifferentvaluesoutofthearrayandseehowitchangeswhatgetsprinted.
Exercise57:ADeckofPlayingCards
BeforethisbookendsIneedtoshowyouhowtouseanarrayofrecordstosimulateadeckofplaying
cards.
1classCard
2{
3intvalue;
4Stringsuit;
5Stringname;
6
7publicStringtoString()
8{
9returnname+"of"+suit;
10}
11}
12
13publicclassPickACard
14{
15publicstaticvoidmain(String[]args)
16{
17Card[]deck=buildDeck();
18//displayDeck(deck);
19
20intchosen=(int)([Link]()*[Link]);
21Cardpicked=deck[chosen];
22
[Link]("Youpickeda"+picked+"outofthedeck.");
[Link]("InBlackjackyourcardisworth"+[Link]+"
points.");
25}
26
27publicstaticCard[]buildDeck()
28{
29String[]suits={"clubs","diamonds","hearts","spades"};
30String[]names={"ZERO","ONE","two","three","four","five","six",
31"seven","eight","nine","ten","Jack","Queen","King","Ace"};
32
33inti=0;
34Card[]deck=newCard[52];
35
36for(Strings:suits)
37{
38for(intv=2;v<=14;v++)
39{
40Cardc=newCard();
[Link]=s;
[Link]=names[v];
43if(v==14)
[Link]=11;
45elseif(v>10)
[Link]=10;
47else
[Link]=v;
49
50deck[i]=c;
51i++;
52}
53}
54returndeck;
55}
56
57publicstaticvoiddisplayDeck(Card[]deck)
58{
59for(Cardc:deck)
[Link]([Link]+"\t"+c);
61}
62}
WhatYouShouldSee
Youpickedasevenofheartsoutofthedeck.
InBlackjackyourcardisworth7points.
Ofcourse,eventhoughthisisalmostthefinalexercise,Icantresistsneakinginsomemorenewthings
[Link],dontyou?
Firstofall,Isnuckafunctionintotherecord.(Actually,becausethisfunctionisinsideaclassitisnta
functionbutamethod.)
[Link]
wecreateaStringbyconcatenatingthenamefield,thesuitfield,andtheword"of".Themethod
doesntneedanyparametersbecauseithasaccesstothefieldsoftherecord.(Infact,thatiswhatmakes
itamethodandnotafunction.)
Otherwise,theCardrecordishopefullywhatyouwouldexpect:ithasfieldsforthevalueofthecard
(211),thesuitnameandthenameofthecarditself.
Onlines17though24youcanseethemain(),whichisreallyshort.Line17declaresanarrayofcards
andinitializesitusingthereturnvalueofthebuildDeck()function.
Line18iscommentedout,butwhenIwaswritingthisprogramoriginallyIusedthedisplayDeck()
functiontomakesurethatbuildDeck()wasworkingcorrectly.
[Link]
exactlytherangeoflegalindexesintothearray,andthatisnotacoincidence.
Infact,youcouldalsosaythatline20choosesarandomindexintothearrayorthatline20choosesa
slotofthearrayrandomly.
Thenonline21wedeclareanewCardvariablecalledpickedandgiveitavaluefromthe
randomlychosenslotofthearray.
[Link]?Itis
[Link],Javadoesntknowwhich
fieldsyouwantprintedorinwhatordersoitjustprintsgarbageonthescreen.(Yousawthatinthe
StudyDrillforthepreviousexercise,right?)
ButifyouprovideamethodcalledtoString()insideyourrecord,whichreturnsaStringandhas
noparameters,[Link]
returnvalueandprintthatoutinsteadofgarbage.
Soline23willprintonthescreentheresultofrunningthepickedcardstoString()method.
Bycontrast,[Link].
BeforewegettobuildDeck(),whichisthemostcomplexpartofthisexercise,letusskipdownto
thedisplayDeck()[Link]()expectsyoutopassinanarrayofCardsasan
argument.
Thenonline59weseesomethingwehaventseenforafewexercises:[Link]
eachCardcinthedeckAndsincethereisonlyonelineofcodeinthebodyofthisforloop,I
omittedthecurlybraces.
Line60displaysthevalueofthecurrentcard,atab,andthentheresultofcallingthetoString()
methodonbehalfofCardc.
Okay,letustacklethisbuildDeck()[Link]()doesntneedanyparametersbecause
[Link],though:anarrayofCards.
[Link](online29)containsthenamesof
[Link].
YoumaynoticethatIhaveacardcalled"ZERO"andanothercalled"ONE".Why?ThisissoIcanthis
arrayasalookuptable.Iamgoingtowritemyloopsothatmycardvaluesgofrom2through14and
Iwanttheword"two"tohaveindex2inthisarray.SoIneededtoputsomeStringsintoslots0and1
totakeupspace.
OriginallyIhadjustputintwoemptyStringslikeso:
String[]names={"","","two","three","four","five","six",
butthenIwasworriedthatifIhadabuginmycodeitwouldbehardtotellifnothingwasbeing
printedorifitwasthevalueofnames[0](ornames[1]).SoIputwordsinforthosetwoindexesbut
madethemallcapssoitwouldcatchmyattentioniftheygotprintedout.
Online33wecreatei,whichwillkeeptrackofwhichindexneedstohaveaCardputintoitnext.
Andline34definesourarrayof52cards(indexed0`through``51).
[Link]"clubs",then
"diamonds",then"hearts"andthenfinally"spades".
[Link]
vgofrom2through14beforetheouterloopeverchangessfrom"clubs".
Line40definesaCardnamedc.Online41wesetthesuitfieldofthiscardtowhatevervalueis
currentlyins("clubs",atfirst).
Dependingonwhichtimethroughtheloopthisis,vwillbesomevaluebetween2and14,soonline42
[Link],whenvis5wegointothesixth(!)slotofthearray,
wherewewillfindtheString"five".Weputacopyofthisvalueintothenamefieldofthecurrent
card.
[Link]
togofrom214forourlookuptable,butnowthatthatisalreadydone,weneedtomakesurethatno
cardgetsavalueof1214.
Cardnumber14istheace,soweuse11forthecardvalue.Thencardnumbers11,12and13arethe
facecards,[Link].
Finallywestorethiscardintothenextavailableslotofthedeck(indexedwithi)andmakeibiggerby1.
Whenthenestedloopsfinishedwehavesuccessfullycreatedall52cardsinastandarddeckandgiven
[Link]()
online18ifyouwanttobesure.
ThelastthingthatbuildDeck()needstodoisreturnthenowfullarrayofCardssoitcanbe
storedintothedeckvariableonline17ofmain().

StudyDrills
1. AddafunctioncalledshuffleDeck().Itshouldtakeinanarrayofcardsasaparameterand
returnanarrayofcards.Onewaytoshuffleistochoosetworandomnumbersfrom051and
[Link]
abittrickytogetright.
Exercise58:FinalProjectTextAdventureGame
Ifyouhavedonealltheexercisesuptothispoint,[Link]
longerthananyotherexercisethatyouhavedone,butitisntmuchmoredifficultthanthelastfew.
[Link]
anythingabouttheadventureitself;thegameisdetermined100%[Link]
andyouchangethegameplay.
Sostartbydownloadingacopyofthegamedatafileandsavingitintothesamefolderasyouaregoing
toputyourcode.
[Link]

Then,[Link],butIthinkitwillbeworthit.
[Link];
2
3classRoom
4{
5introomNumber;
6StringroomName;
7Stringdescription;
8intnumExits;
9String[]exits=newString[10];
10int[]destinations=newint[10];
11}
12
13publicclassTextAdventureFinal
14{
15publicstaticvoidmain(String[]args)
16{
17Scannerkeyboard=newScanner([Link]);
18
19//initializeroomsfromfile
20Room[]rooms=loadRoomsFromFile("[Link]");
21
22//showAllRooms(rooms);//fordebugging
23
24//Okay,solet'splaythegame!
25intcurrentRoom=0;
26Stringans;
27while(currentRoom>=0)
28{
29Roomcur=rooms[currentRoom];
[Link]([Link]);
[Link](">");
32ans=[Link]();
33
34//Seeifwhattheytypedmatchesanyofourexitnames
35booleanfound=false;
36for(inti=0;i<[Link];i++)
37{
38if([Link][i].equals(ans))
39{
40found=true;
41//ifso,changeournextroomtothatexit'sroomnumber
42currentRoom=[Link][i];
43}
44}
45if(!found)
[Link]("Sorry,Idon'tunderstand.");
47}
48
49}
50
51publicstaticRoom[]loadRoomsFromFile(Stringfilename)
52{
53Scannerfile=null;
54try
55{
56file=newScanner([Link](filename));
57}
58catch([Link])
59{
[Link]("Sorry,Ican'treadfromthefile'"+
filename+"'.");
[Link](1);
62}
63
64intnumRooms=[Link]();
65Room[]rooms=newRoom[numRooms];
66
67//initializeroomsfromfile
68introomNum=0;
69while([Link]())
70{
71Roomr=getRoom(file);
72if([Link]!=roomNum)
73{
[Link]("Readingroom#"+[Link]+",but
"+roomNum+"wasexpected.");
[Link](2);
76}
77rooms[roomNum]=r;
78roomNum++;
79}
[Link]();
81
82returnrooms;
83}
84
85publicstaticvoidshowAllRooms(Room[]rooms)
86{
87for(Roomr:rooms)
88{
89StringexitString="";
90for(inti=0;i<[Link];i++)
91exitString+="\t"+[Link][i]+"("+[Link][i]+
")";
[Link]([Link]+")"+[Link]+"\n"+
exitString);
93}
94}
95
96publicstaticRoomgetRoom(Scannerf)
97{
98//anyroomsleftinthefile?
99if(![Link]())
100returnnull;
101
102Roomr=newRoom();
103Stringline;
104
105//readintheroom#forerrorcheckinglater
[Link]=[Link]();
[Link]();//skip"\n"afterroom#
108
[Link]=[Link]();
110
111//readintheroom'sdescription
[Link]="";
113while(true)
114{
115line=[Link]();
116if([Link]("%%"))
117break;
[Link]+=line+"\n";
119}
120
121//finally,we'llreadintheexits
122inti=0;
123while(true)
124{
125line=[Link]();
126if([Link]("%%"))
127break;
128String[]parts=[Link](":");
[Link][i]=parts[0];
[Link][i]=[Link](parts[1]);
131i++;
132}
[Link]=i;
134
135//shouldbedone;returntheRoom
136returnr;
137}
138
139}

WhatYouShouldSee
Thisistheparlor.
It'sabeautifulroom.

Therelookstobeakitchentothe"north".
Andthere'sashadowycorridortothe"east".
>north
[Link]
thereis,asyou'dexpect,[Link]"refrigerator"
or"goback".
>goback
Thisistheparlor.
It'sabeautifulroom.

Therelookstobeakitchentothe"north".
Andthere'sashadowycorridortothe"east".
>east
[Link],thedoor
[Link].

[Link]"quit"todie.
>quit
BeforeIstarttalkingaboutthecode,letmetakeamomenttotalkabouttheadventuregamefile
format.
[Link];theseareonly
usedforthegameengineandarenevershowntotheplayer.
Eachroomalsohasadescriptionandoneormoreexits,whichisapathtoanotherroom.
Theadventuregamefilestartswithanumber:thetotalnumberoflocations(rooms)[Link]
[Link]:
1
KITCHEN
[Link]
thereis,asyou'dexpect,[Link]"refrigerator"
or"goback".
%%
fridge:3
refrigerator:3
goback:0
back:0
%%
Thefirstlineofthisrecordistheroomnumber,[Link]
istheroomname,whichweonlyusefordebugging.
Startingwiththethirdlineoftherecordisthedescriptionoftheroom,whichcontinuesuntilthereisa
linewithnothingbut%%[Link].
[Link](whattheplayer
willtypetotakethatroute)followedbyacolon,followedbytheroomnumberwherethatexitleads.
Forexample,inthisroomiftheplayertypes"fridge"thenthegameenginewillmovethemfrom
thisroom(room#1)intoroom#[Link]"goback"thentheywilltraveltoroom#0
[Link]
[Link]"fridge"or"refrigerator"willtakethemtoroom
#3.
Thelistofexitsendswithanotherlinecontainingonly%%.Andthatstheendoftherecord.
Okay,[Link]
[Link]
thearrayofexitStrings(exits)andthearrayofdestinationroomnumbers(destinations)havean
arbitrarycapacityof10andthentheresanumExitsfieldtokeeptrackofhowmanyexitsthereactually
areinthisroom.Feelfreetomakethiscapacitylargerifyouthinkyoullneedmorethan10exitsina
room.
Movingintomain(),line20declaresthearrayofroomsandinitializesitfromthe
loadRoomsFromFile()functionthatIwillexplainlater.
Line22hasacommentedoutcalltoashowAllRooms()functionthatIusefordebugging.
Online25youwillseethedefinitionofourcurrentRoomvariable,whichholdstheroomnumberofthe
roomtheplayerisinside.Theystartinroom0,whichisthefirstroominthefile.Andonline26isthe
declarationoftheStringans,whichwillholdwhatevertheplayertypes.
Line27isthebeginningofthemaingameloop.ItrepeatsaslongasthecurrentRoomvariableis0or
[Link]:whentheplayerdies(orwins)wewillsetcurrentRoom
equalto1.
[Link]
[Link][currentRoom]istheentirerecordforthe
um,currentroom.Inline29westoreacopyofthisroomintotheRoomvariablecur.(Ionlydothis
[Link]
rooms[currentRoom].description.)
Speakingofwhich,line30printsoutthedescriptionofthecurrentroom,whichisstoredinthe
descriptionfield.
Onlines31and32weprintoutalittlepromptandlettheplayerenterinaStringforwheretheywantto
go.
Lines36through44searchthroughthisroomsarrayofexitslookingtoseeifanyofthemmatchwhat
theplayertyped.Rememberthattheexitsarrayhasacapacityof10,butthereareprobablynotthat
[Link]
fieldinsteadof10.
Ifwefindanexitthatmatchestheplayerscommand,wesetourflagtotrue(soweknowifweshould
complainiftheyenduptypingsomethingthatsnotinourlist).Thensincethewordsintheexitsarray
lineupwiththeroomnumbersinthedestinationsarray,wepulltheroomnumberoutofthe
[Link],whenthe
maingamelooprepeatsagain,wewillhaveautomaticallytraveledtothenewroom.
[Link],itmeansthehumantypedsomethingweneverfoundin
[Link],loopingaroundagain
inthemaingameloopwilljustprintoutthedescriptionagainfortheroomtheywerealreadyin.
Andthatstheendofthemaingameloopandtheendofmain().Allthatsleftistoactuallyfillupthe
arrayofroomsfromtheadventuregamefile.
Line51isthebeginningoftheloadRoomsFromFile()function,whichtakesthefilenametoopen
asaparameterandreturnsanarrayofRooms.
(IdecidedthatIdidntwanttohavethrowsExceptionanywhereinthisfile,sotheresatrycatch
[Link].
[Link]
filetotellushowmanyroomsthereare.Thenline65definesanarrayofRoomrecordswiththe
appropriatecapacity.
Online68ImadeavariablecalledroomNum,[Link]:itistheindexfor
[Link],itisusedtodoublecheckthattheroomnumber
(fromthefile)[Link],theresprobablysomesortoferror
[Link](online72),wecomplainandendtheprogram.
([Link]()endstheprogram,evenfrominsideafunctioncall.)
[Link]
[Link]:ifthenumberofroomsatthetopofyourdatafileis
alie,thenthisloopcouldgotoofarinthearrayandblowup.(Forexample,ifthefirstlineofthefile
saysyouonlyhave7roomsbutthenyouhave8roomrecordsthenthisloopwillrepeattoomany
times.)
Online71wegetreadasingleroomrecordusingthegetRoom()functionIllexplainlater.
Lines72through76aretheroomnumbersanitycheckIalreadymentioned,andthenline77juststores
thisnewroomintothenextavailableslotintheroomsarray.Andline78incrementstheroomindex.
Afterthatloopisover,alltheroomshavebeenreadinfromthefileandstoredeachintotheirownslot
ofthearray.Soonline82wecanreturnthearrayofroomsbackuptoline20ofmain().
Lines85through94aretheshowAllRooms()[Link]
theroomsinthearrayonthescreen,andforeachroomitalsoshowsalltheexitsandwheretheylead.
OurfinalfunctionisgetRoom(),whichexpectsaScannerobjecttobepassedinasaparameterand
whichreturnsasingleRoomobject.
[Link]
thinginthefileisnotaninteger,thenjustreturnnull(thevalueofanuninitializedobject).Puttinga
returnupherewillreturnfromthefunctionrightawaywithoutbotheringtorunanyoftheremaining
code.
Online102theemptyroomobjectisdefined.Line103createsaStringcalledline,whichIusefora
coupleofdifferentthings.
[Link].
TherestofthisfunctionisgoingtouseonlytheScannerobjectsnextLine()method,anda
nextLine()afteranextInt()usuallydoesntworkbecauseitreadsonlytheendofthelineafter
theintegerthatwasjustread.
Soline107callsthenextLine()methodbutdoesntbothertostoreitsreturnvalueanywhere
becauseitdoesntreadanythingworthsaving.
[Link].
[Link]
toitwithoutgettinganerror.(Justlikewewouldsetatotalvariableto0beforeaddingtoitinaloop.)
[Link]
becausewedontknowhowmanylinesaregoingtobeintheroomsdescription;itjustgoeshowever
longuntilweseealineconsistingofnothingbut%%.Thereareotherwaystodothis,butIlikethe
[Link]
Ivesaidbefore,reasonablepeopledisagree.
Oncewereinsidetheinfiniteloop,[Link],online
116wechecktoseeifwhatwejustreadwas%%.Ifso,wedontwanttoaddittothedescriptionsowe
[Link];continueskipsbackupto
theconditionofaloopandbreakjustskipstotheendandstopslooping.
Ifwerestillaroundtoseeline118,itmeansthatwereadinalineofdescriptionanditwasnt%%.So
weuse+=toaddthatline(anda\n)[Link]
thelooprepeats.(Nomatterwhat.)
Eventuallywehopefullyhita%%andtheloopstopslooping.
Line122definesi,whichIusefortheindexofwhichslotintheexitsanddestinationsarrayswere
[Link]
similarapproachtoreadinalltheexits.
Line125readsinthewholeline,whichmeansthatlinecontainssomethinglike"refrigerator:3".
(Ifitsnotsomethinglikethatbutisactually%%,lines126and127stoplooping.)
[Link],theStringclasshasabuiltin
methodcalledsplit().
[Link](":")searchesthroughtheStringlineandbreaksitupeverytimeitseesa:(colon).
[Link],iflinecontainedthisXisXaXtestthen
[Link]("X")wouldreturnanarraycontaining{"this","is","a","test"}.In
ourcasetheresonlyonecoloninline,soitreturnssomethinglike{"refrigerator","3"}.
So,afterline128parts[0]containstheexitword(likerefrigerator)andparts[1]containsa
Stringforthedestinationroomnumber(like"3").Thisdoesntquiteworkforus,becauseweneedthe
roomnumbertobeaninteger,notaString.
Fortunatelyforus(again),[Link]
convertaStringtoaninteger:[Link]().Weusethisonline130.
Recallthatiistheindexoftheslotintheexitsarraywhereweneedtostorethenextvalue.Soline129
storesparts[0](thenameoftheexit)intotheappropriateslotoftheexitsarray.Andline130
convertsparts[1](theroomnumbertomoveto)fromaStringtoanintandstoresthatinthesame
slotofthedestinationsarray.Thenline131incrementstheexitindexforthenextgoaround.
Eventuallywewillhita%%andthisloop,too,[Link],however.
[Link],thisloopwilljust
[Link].
Aftertheloopends,[Link]
thatintothenumExitsfieldofthecurrentroomonline133.
[Link],andwereturnthisRoom
objecttoline71oftheloadRoomsFromFile()function.

StudyDrills
1. [Link],emailittome!
2. Addasavegamefeature,sothattheplayercantypesomethingtostopthegame,andthegame
willstoretheircurrentroomnumbertoatextfileandthenloaditbackupwhenthegamebegins
again.

Learn Java
the
Hard Way
Graham Mitchell
Version 20130720.004
Copyright 2013 Graham Mitchell. All rights reserved.
Version 20130720.004
10 09 08 07 06 05 XYZABC 04 03 02 01
Preface
I have been teaching beginners how to code for over fifteen years. More than 2,000 students have taken 
my classes an
Contents
●
Preface: Learning by Doing
●
Introduction: The Challenge of Java as a First Language
●
Exercise 0: The Setup
●
Exe
●
Exercise 45: Caesar Cipher (Looping Through a String)
●
Exercise 46: Nested For Loops
●
Exercise 47: Generating and Filteri
Introduction: Java
Java is not a language for beginners. I am convinced that most “beginner” Java books only work on 
people 
Also, I hope to write two more books after this one. My second book will cover graphics and 
object­oriented programming in J
Exercise 0: The Setup
This exercise has no code but do not skip it. It will help you to get a decent text editor installed an
Windows
1. Go to http://notepad­plus­plus.org/ with your web browser, get the Notepad++ text editor, and 
install it. You do 

You might also like