Вы находитесь на странице: 1из 189

Learn Java

the
Hard Way
Graham Mitchell
Version20130720.004
Copyright2013GrahamMitchell.Allrightsreserved.
Version20130720.004
100908070605XYZABC04030201
Preface
Ihavebeenteachingbeginnershowtocodeforoverfifteenyears.Morethan2,000studentshavetaken
myclassesandleftknowinghowtowritesimpleprogramsthatwork.Somelearnedhowtodoonlya
littleandothersgainedincredibleskilloverthecourseofjustafewyears.
Ibelievethatnearlyanyonecanteachachildprodigyhowtocode.Itaughtmy9yearolddaughterto
code,andshemadeherfirstAndroidappsixweekslater!Ifyouarethechildprodigy,thisbookisnot
writtenforyou.
Ihavealsocometobelievethatthereisnosubstituteforwritingsmallprograms.Sothatswhatyouwill
dointhisbook.Youwilltypeinsmallprogramsandrunthem.

Thebestwaytolearnistodo.
P.R.Halmos
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
Javaisnotalanguageforbeginners.IamconvincedthatmostbeginnerJavabooksonlyworkon
peoplewhoalreadyknowhowtocodeorwhoareprodigies.
IcanteachyouJava,evenifyouhaveneverprogrammedbeforeandevenifyouarenotagenius.ButI
amgoingtohavetocheatabit.
WhatIwillteachyouisJava.ButitisnotallofJava.Ihavetoleavepartsoutbecauseyourenotready
forthem.IfyouthinkyouarereadyforthemorecomplexpartsofJava,then1)yourewrong,and2)
buyadifferentbook.ThereareagreatmanybooksonthemarketthatwillthrowallthecomplexityJava
hastooffer,fasterthanyoucanhandleit.
Inparticular,Ihaveonehugeomission:IamgoingtoavoidthetopicofObjectOrientedProgramming
(OOP).Imprettysurethatuncomfortablebeginnerscantlearnhowtocodewellandalsolearn
objectorientedprogrammingatthesametime.Ihavealmostneverseenitwork.
IplantowriteafollowupbookthatwillcoverObjectOrientedProgrammingandthemorecomplex
partsofJava.Butyoushouldfinishthisbookfirst.Ihavebeenteachingstudentstoprogramformany
manyyears,andIhaveneverhadastudentcomevisitmefromcollegeandsayIwishyouhadspent
lesstimeonthefundamentals.

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

Inthefinalchapteryoullwriteanotsosimpletextbasedadventuregamewithlevelsloadedfromtext
files.YoushouldalsobeabletowriteatextbasedcardgamelikeHeartsorSpades.

WhatYouWillNotLearn
Graphics
Objectorientedprogramming
HowtomakeanAndroidapp

Ilikegraphics,andtheyrenothardinJavacomparedto,say,C++,butIcantcovereverythingand
teachthebasicswell,sosomethinghadtogo.
Objectorientedprogramminghasnoplaceinanintroductorybook,inmyopinion.
Androidappsareprettycomplex,andifyoureabeginner,anappiswaybeyondyourability.Nothing
inthisbookwillhurtyourchancesofmakinganapp,though,andthekinder,gentlerpacemaykeepyou
goingwhenotherbookswouldfrustrateyouintoquitting.
Also,Ihopetowritetwomorebooksafterthisone.Mysecondbookwillcovergraphicsand
objectorientedprogramminginJava.MythirdbookwillcovermakingasimpleAndroidapp,assuming
youhavefinishedworkingthroughthefirsttwobooks.

HowtoReadThisBook
AlthoughIhaveprovidedazipfilecontainingthesourcecodeforalltheexercisesinthebook,you
shouldtypethemin.
Foreachexercise,typeinthecode.Yourself,byhand.Howareyougoingtolearnotherwise?Noneof
myformerstudentseverbecamegreatatprogrammingbymerelyreadingotherscode.
Workthestudydrills,ifthereareany.Dothechallengeassignments,ifprovided.Andbytheendyou
willbeabletocode,atleastalittle.

License
Somechaptersofthisbookaremadeavailablefreetoreadonlinebutyouarenotallowedtomake
copiesforothers.Unlessotherwisestated,allcontentiscopyright2013GrahamMitchell.
Exercise0:TheSetup
Thisexercisehasnocodebutdonotskipit.Itwillhelpyoutogetadecenttexteditorinstalledandto
installtheJavaDevelopmentKit(JDK).Ifyoudonotdobothofthesethings,youwillnotbeabletodo
anyoftheotherexercisesinthebook.Youshouldfollowtheseinstructionsasexactlyaspossible.
Warning!
Thisexerciserequiresyoutodothingsinaterminalwindow(alsocalleda
shell,consoleorcommandprompt.Ifyouhavenoexperiencewitha
terminalwindow,thenyoumightneedtogolearnthatfirst.
ZedShawsexcellentCommandLineCrashCourseisat
http://cli.learncodethehardway.org/book/andwillteachyouhowtouse
PowerShellonWindowsortheTerminalonOSXorbashonLinux.

MacOSX
Tocompletethisexercise,completethefollowingtasks:
1. Gotohttp://www.barebones.com/products/textwrangler/withyourwebbrowser.Downloadthe
TextWranglertexteditorandinstallit.
2. PutTextWranglerinyourdocksoyoucanreachiteasily.
3. FindaprogramcalledTerminal.(Searchforitifyouhaveto.)
4. PutyourTerminalinyourdockaswell.
5. LaunchtheTerminal.
6. IntheTerminalprogram,typejavacversionandpressRETURN.Youshouldseea
responselikejavac1.7.0_04.Itisokayifthenumberafterjavacisnotexactlythesame
aslongasitis1.6orgreater.Ifyougetanerrormessage,however,youmayneedtoinstallthe
JDK.
7. Afterthis,youshouldbebackataprompt.
8. Learnhowtocreateafolder(makeadirectory)fromtheTerminal.Makeadirectorysothatyou
canputallyourcodefromthisbookinit.
9. LearnhowtochangeintothisnewdirectoryfromtheTerminal.Changeintoit.
10. Useyourtexteditor(TextWrangler)tocreateafilecalledtest.txtandsaveitintothe
directoryyoujustcreated.
11. GobacktotheTerminalusingonlythekeyboardtoswitchwindows.
12. BackinTerminal,seeifyoucanlistthecontentsofthedirectorytoseeyournewlycreatedfile.

OSX:WhatYouShouldSee
IdontcurrentlyhaveaccesstoaMac,sohereisZedfollowingthestepsaboveonhiscomputerin
Terminal.Yourcomputerwouldbedifferent,soseeifyoucanfigureoutallthedifferencesbetween
whathedidandwhatyoushoulddo.
Lastlogin:FriJul1900:56:54onttys001
~$javacversion
javac1.6.22
~$mkdirjavacode
~$cdjavacode
javacode$ls
#...UseTextWranglerheretoedittest.txt....
javacode$ls
test.txt
javacode$
Windows
1. Gotohttp://notepadplusplus.org/withyourwebbrowser,gettheNotepad++texteditor,and
installit.Youdonotneedtobeanadministratortodothis.
2. MakesureyoucangettoNotepad++easilybyputtingitonyourdesktopand/orinQuick
Launch.Bothoptionsareavailableduringsetup.
3. RunPowerShellfromtheStartmenu.SearchforitandyoucanjusthitEntertorunit.
4. MakeashortcuttoPowerShellonyourdesktopand/orQuickLaunchforyourconvenience.
5. Gotohttp://www.oracle.com/technetwork/java/javase/downloads/withyourwebbrowser.
A) ClickthebigJavabuttonontheleftnearthetoptodownloadtheJavaPlatform(JDK)
7u25.Clickingthiswilltakeyoutoadifferentpage.
B) OnthispageyouwillhavetoacceptthelicenseagreementandthenchoosetheWindows
x86versionnearthebottomofthelist.Downloadthefile.
C) Oncedownloaded,runjdk7u25windowsi586.exetoinstallit.Afteryouclick
Next>theveryfirsttimeyouwillseeascreenthatsaysInstallto:C:\Program
Files(x86)\Java\jdk1.7.0_25\orsomethingsimilar.Makeanoteofthis
location;youwillneeditsoon.
6. OncetheJDKisinstalledyouwillneedtofindouttheexactnameofthefolderwhereitwas
installed.LookontheC:driveinsidetheProgramFilesfolderortheC:\Program
Files(x86)folderifyouhaveone.YouarelookingforafoldercalledJava.Insidethatis
afoldercalledjdk1.7.0_25thathasafoldercalledbininsideit.Thefoldernamemusthave
jdk1.7init;jre7isnotthesame.Makesuretheresabinfolder.
7. Onceyouareinthisfolder,youcanleftclickupinthefolderlocationanditwillchangeto
somethingthatlookslikeC:\ProgramFiles(x86)\Java\jdk1.7.0_25\bin.You
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;
andthenrightclickinthePowerShellwindowanditshouldpastethefoldernameforyou.Thenyou
canjustfinishthelinebytyping","User")andpressingENTER.Ifyougetanerror,youtyped
somethingincorrectly.Youcanpresstheuparrowtogetitbackandtheleftandrightarrowstofindand
fixyourmistake,thenpressENTERagain.
1. OncethesetEnvironmentVariablecommandcompleteswithoutgivingyouanerror,
closethePowerShellwindowbytypingexitattheprompt.Ifyoudontcloseitthechangeyou
justmadewonttakeeffect.
2. LaunchPowerShellagain.
3. Typejavacversionattheprompt.Youshouldseearesponselikejavac1.7.0_25.
Congratulations!Ifyougotthattowork,therestofthisbookoughttoberelativelyeasy.
4. Afterthis,youshouldbebackatablinkingPowerShellprompt.
5. Learnhowtocreateafolder(makeadirectory)fromtheterminalwindow(PowerShell).Makea
directorysothatyoucanputallyourcodefromthisbookinit.
6. Learnhowtochangeintothisnewdirectoryfromtheprompt.Changeintoit.
7. Useyourtexteditor(Notepad++)tocreateafilecalledtest.txtandsaveitintothedirectory
youjustcreated.
8. Gobacktotheterminalusingonlythekeyboardtoswitchwindows.
9. Backintheterminal,seeifyoucanlistthecontentsofthedirectorytoseeyournewlycreated
file.

Windows:WhatYouShouldSee
WindowsPowerShell
Copyright(C)2009MicrosoftCorporation.Allrightsreserved.

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++tomaketest.txtinjavacode...
PSC:\Users\Graham_Mitchell\javacode>ls

Directory:C:\Users\Graham_Mitchell\javacode

ModeLastWriteTimeLengthName

a7/19/20137:45PM4test.txt

PSC:\Users\Graham_Mitchell\javacode>
Youwillprobablyseeadifferentpromptandotherslightdifferencesbutyoushouldntgetanyerrors
andthisisthegeneralidea.
Linux
TherearealotofdifferentversionsofLinuxoutthere,soIamgoingtogiveinstructionsforthelatest
versionofUbuntu.Ifyouarerunningsomethingelse,youprobablyknowwhatyouaredoingwell
enoughtofigureouthowtomodifythedirectionsforyoursetup.
1. UseyourLinuxpackagemanagertoinstallthegedittexteditor(Whichmightjustbecalled
TextEditor.)
2. MakesureyoucangettogediteasilybyputtingitintheLauncher.
3. Rungeditsowecanchangesomeofthedefaultstobebetterforprogrammers:
A) OpenPreferencesandselecttheEditortab.
B) ChangeTabwidth:to4.
C) PutacheckmarknexttoAutomaticindentation
D) OpentheViewtabandturnonDisplaylinenumbers.
4. FindyourTerminalprogram.ItcouldbecalledGNOMETerminal,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)fromtheterminal.Makeadirectorysothatyou
canputallyourcodefromthisbookinit.
10. Learnhowtochangeintothisnewdirectoryfromtheprompt.Changeintoit.
11. Useyourtexteditor(gedit)tocreateafilecalledtest.txtandsaveitintothedirectoryyou
justcreated.
12. Gobacktotheterminalusingonlythekeyboardtoswitchwindows.Lookitupifyoudont
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++tomaketest.txtinjavacode...
mitchell@grahamdesktop:~/javacode$ls
test.txt
mitchell@grahamdesktop:~/javacode$
Youwillprobablyseeadifferentpromptandotherslightdifferencesbutyoushouldntgetanyerrors
andthisisthegeneralidea.
WarningsforBeginners
Youaredonewiththefirstexercise.Thisexercisemighthavebeenquitehardforyoudependingon
yourfamiliaritywithyourcomputer.Ifitwasdifficultandyoudidn'tfinishit,gobackandtakethetime
toreadandstudyandgetthroughit.Programmingrequirescarefulreadingandattentiontodetail.
IfaprogrammertellsyoutousevimoremacsorEclipse,justsayno.Theseeditorsareforwhenyou
areabetterprogrammer.Allyouneedrightnowisaneditorthatletsyouputtextintoafile.Wewilluse
gedit,TextWrangler,orNotepad++(fromnowoncalledthetexteditororatexteditor)becauseitis
simpleandthesameonallcomputers.Professionalprogrammersusethesetexteditorssoitsgood
enoughforyoustartingout.
AprogrammerwilleventuallytellyoutouseMacOSXorLinux.Iftheprogrammerlikesfontsand
typography,helltellyoutogetaMacOSXcomputer.Ifhelikescontrolandhasahugebeard,theyll
tellyoutoinstallLinux.Again,usewhatevercomputeryouhaverightnowthatworks.Allyouneedis
aneditor,aTerminal,andJava.
Finally,thepurposeofthissetupissoyoucandothreethingsveryreliablywhileyouworkonthe
exercises:
Writeexercisesusingyourtexteditor(geditonLinux,TextWrangleronOSX,orNotepad++on
Windows).
Runtheexercisesyouwrote.
Fixthemwhentheyarebroken.
Repeat.
Anythingelsewillonlyconfuseyou,sosticktotheplan.

FrequentlyAskedQuestions
DoIhavetousethislametexteditor?IwanttouseEclipse!
DonotuseEclipse.Althoughitisaniceprogramitisnotforbeginners.Itisbadforbeginnersin
twoways:
1. Itmakesyoudothingsthatyoudontneedtoworryaboutrightnow.
2. Itdoesthingsforyouthatyouneedtolearnhowtodoforyourselffirst.
Sofollowmyinstructionsanduseadecenttexteditorandaterminalwindow.Onceyouhave
learnedhowtocodeyoucanuseothertoolsifyouwant,butnotnow.
CanIworkthroughthisbookonmytablet?OrmyChromebook?
Unfortunatelynot.YoucantinstalltheJavadevelopmentkit(JDK)oneitherofthosemachines.
Youmusthavesomesortoftraditionalcomputer.
Exercise1:AnImportantMessage
InthisexerciseyouwillwriteaworkingprograminJavatodisplayanimportantmessageonthescreen.
Ifyouarenotusedtotypingdetailedinstructionsforacomputerthenthiscouldbeoneoftheharder
exercisesinthebook.Computersareverystupidandifyoudontgeteverydetailright,thecomputer
wontunderstandyourinstructions.Butifyoucangetthisexercisedoneandworking,thenthereisa
goodchancethatyouwillbeabletohandleeveryexerciseinthebookaslongasyouworkonitevery
dayanddontquit.
OpenthetexteditoryouinstalledinExercise0andtypethefollowingtextintoasinglefilenamed
FirstProg.java.MakesuretomatchwhatIhavewrittenexactly,includingspacing,punctuation,
andcapitalization.
1publicclassFirstProg
2{
3publicstaticvoidmain(String[]args)
4{
5System.out.println("Iamdeterminedtolearnhowtocode.");
6System.out.println("Today'sdateis");
7}
8}
Ihaveputlinenumbersinfrontofeachline,butdonottypethelinenumbers.TheyareonlytheresoI
cantalkaboutthelines.Also,dependingonwhetherornotyouhavesavedthefileyet,thedifferent
wordsmaynotbecoloredatall.Oriftheyarecolored,theymightbedifferentcolorsthanmine.These
differencesarefine.
Imgoingtowalkthroughthislinebyline,justtomakesureyoutypedeverythingcorrectly.
Thefirstlinestartswiththewordpublicfollowedbyasinglespacethenthewordclassfollowed
byasinglespaceandthenthewordFirstProg.TheFinFirstiscapitalized,thePinProgis
capitalized.Thereareonlytwocapitallettersinthefirstline.Thereareonlytwospaces.
Thesecondlineisjustasinglecharacter:abrace.YougetittoshowupbyholdingdownSHIFTand
thenpressingthe[keywhichisusuallytotherightoftheletterP.
BeforeIgoontothethirdlineoftheprogram,Ishouldtellyouwhatprogrammersusuallycalleach
funnysymbolthatappearsinthisprogram.
(and)arecalledparentheses(thatsplural).Justoneofthemiscalleda
parenthesis,butsomepeoplejustcallthemparens(puhRENZ).Thisone(()is
sometimescalledaleftparenandtheother())iscalledarightparenbecause
parenthesesusuallycomeinpairsandoneisusuallytotheleftoftheother.Theleft
parenthesis(()isalsooftencalledanopenparenandtherightoneiscalleda
closeparenforsimilarreasons.
Theresanopenparenonline3andacloseparen,too,andnootherparenthesesinthe
wholefile.
[and]arecalledbrackets,butmanyprogrammerscallthemsquarebracketsto
makesuretheresnoconfusion.InJava,parenthesesandsquarebracketsarenot
interchangeable.Bracketscomeinpairsandtheyarecalledleftbracketoropen
bracketandrightbracketorclosebracket.
Theresanopenandclosesquarebracketrightnexttoeachotheronline3.
{and}arecalledbraces,andsomeprogrammerscallthemcurlybraces.These
alsoalwayscomeinpairsofleftandrightcurlybraces/openandclosebraces.
"iscalledaquotationmark,oftenjustabbreviatedquote.InJava,thesealways
comeinpairs.Thefirstoneinapairisusuallycalledanopenquoteandthesecond
oneisaclosequoteeventhoughitstheexactsamecharacterinbothplaces.Butthe
firstquoteservestobeginsomethingandthesecondoneendsthatthing.
'istechnicallyanapostrophe,butalmostallprogrammerscallthemsingle
quotes.Forthisreasonaquotationmarkisoftencalledadoublequote.Insome
programminglanguages,singlequotesanddoublequotesareinterchangeable,butnot
inJava.Javadoesusesinglequotessometimes,buttheyregoingtobeprettyrarein
thisbook.
.istechnicallyaperiod,butalmostallprogrammersjustsaydot.Theyareuseda
lotinprogramminglanguages,andtheyareusuallyusedasseparatorsinsteadof
enders,sowedontcallthemperiods.
Therearefourdotsinthisprogramandoneperiod.
;iscalledasemicolon.ItsbetweentheletterLandthequoteonthekeyboard.
Javausesalotofsemicolonsalthoughthereareonlytwooftheminthisprogram:one
ontheendofline5andanotherattheendofline6.
:iscalledacolon.YougetitbyholdingSHIFTandtypingasemicolon.Javadoes
usecolons,buttheyreveryrare.
Finally,<isalessthansignand>isagreaterthansign,butsometimestheyare
usedsortoflikebracesorbrackets.Whentheyareusedthisway,theyreusually
calledanglebrackets.Javausesanglebrackets,butyouwontseethemusedinthis
book.
Okay,sobacktothelinebyline.Youhavealreadytypedthefirsttwolinescorrectly.
YoushouldstartthethirdlinebypressingTABonetime.Yourcursorwillmoveoverseveralspaces
(probably4or8).Thentypethewordpublicagain,onespace,thewordstatic,onespace,the
wordvoid,onespace,thewordmainfollowedbyanopenparen(nospacebetweenthewordmain
andtheparen).Aftertheparentheresonespace,thewordStringwithacapitalS,anopenand
closesquarebracketrightnexttoeachother,onespace,thewordargs,onespaceandfinallyaclose
parenthesis.
Solinethreestartswithatab,hasatotalofsixspaces,andonlytheSinStringiscapitalized.Whew.
Onthefourthline,yourtexteditormayhavealreadystartedyourcursordirectlyunderneaththepin
public.Ifitdidnotdothat,thenyoullhavetostartline4bypressingTAByourself.Thenjusttype
anotheropencurlybraceandthatsit.
Thefifthlineshouldstartwithtwotabs.ThentypethewordSystemwithacapitalS,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.
Line7startswithonlyonetab.Ifyourtexteditorputtwotabsinthereforyou,youshouldbeabletoget
ridoftheextratabbypressingBACKSPACEonetime.Thenafterthetabtheresaclosecurlybrace.
Finally,line8hasnotabsandonemoreclosecurlybrace.YoucanpressENTERafterline8ornot:
Javadoesntcare.
Noticethatwehavetwoopencurlybracesandtwoclosecurlybracesinthefile.Threeopenparensand
threecloseparens.Twoopenquotesandtwoclosequotes.Oneopensquarebracketandoneclose
squarebracket.Thiswillalwaysbetrue.
Alsonoticethateverytimewedidanopencurlybrace,theline(s)belowithadmoretabsatthe
beginning,andthelinesbelowclosecurlybraceshadfewertabs.
Okay,nowsavethis(ifyouhaventalready)asFirstProg.javaandsaveitinthecodefolder
youcreatedinExercise0.
Makesurethefilenamematchesmineexactly:theFinFirstiscapitalized,thePinProgis
capitalized,andeverythingelseislowercase.Andthereshouldbenospacesinthefilename.Javawill
refusetorunanyprogramwithaspaceinthefilename.Alsomakesurethefilenameendsin.java
andnot.txt.

CompilingYourFirstProgram
Nowthattheprogramhasbeenwrittenandhopefullycontainsnomistakes(wellseesoonenough),
launchyourTerminal(orPowerShell)andchangeintothedirectorywherethecodeissaved.
DoadirectorylistingtomakesuretheJavafileisthere.Onmycomputer,itlookslikethis:
mitchell@grahamdesktop:~$cdjavacode/
mitchell@grahamdesktop:~/javacode$ls
FirstProg.javatest.txt
mitchell@grahamdesktop:~/javacode$
Inthefuture,sinceyourterminalprobablydoesntlooklikemine,Iamgoingtoabbreviatetheprompt
likethis:
$ls
FirstProg.javatest.txt
$
Thatwayitwillbelessconfusing,sincethereislesswrongstufftoignoreandyouonlyhavetolook
atwhatyoushouldtypeandwhatyoushouldsee.
Now,wehavetypedalistofcommandsinaprogramminglanguagecalledJava.Butthecomputer
cannotexecuteourcommandsdirectlyinthisform.Wehavetogivethisfiletoacompiler,whichisa
programthatwilltranslateourinstructionsintosomethingmorelikeonesandzerosthatthecomputer
canexecute.InJavathatonesandzerosfileiscalledbytecode.SowearegoingtoruntheJava
compilerprogramtocompileourJavasourcecodeintoabytecodefilethatwewillbeabletoexecute.
TheJavacompilerisnamedjavac(thecisforcompiler),andwerunitlikeso:
$javacFirstProg.java
$
IfyouhaveextraordinaryattentiontodetailanddideverythingthatItoldyou,thiscommandwilltakea
secondtorun,andthenthepromptwilljustpopbackupwithnomessage.Ifyoumadesomesortof
mistake,youwillseeanerrorlikethis:
$javacFirstProg.java
FirstProg.java:8:error:reachedendoffilewhileparsing
}
^
1error
$
Dontworrytoomuchabouttheparticularerrormessage.Whenitgetsconfused,thecompilertriesto
guessaboutwhatyoumighthavedonewrong.Unfortunately,theguessesaredesignedforexpert
programmers,soitusuallydoesntguesswellforbeginnertypemistakes.
Hereisanexampleofadifferenterrormessageyoumightget:
$javacFirstProg.java
FirstProg.java:5:error:';'expected
System.out.println("Iamdeterminedtolearnhowtocode."):
^
1error
$
Inthiscase,thecompilerisactuallyright:theerrorisonline5andthespecificerroristhatasemicolon
wasexpected(';'expected).(Thelineendswithacolon(:)butitoughttobeasemicolon(;).
Heresonemore:
$javacFirstProg.java
FirstProg.java:1:error:classFirstprogispublic,shouldbedeclaredinafile
namedFirstprog.java
publicclassFirstprog
^
1error
$
Thistimeisitacapitalizationerror.ThecodesayspublicclassFirstprog(notethelowercase
p)butthefilenameisFirstProg.java.Becausetheydontmatchexactly,capitalizationandall,
thecompilergetsconfusedandbailsout.
Soifyouhaveanyerrormessages,fixthem,thensaveyourcode,gobacktotheterminalandcompile
again.
Warning!
Ifyoumakeachangetothecodeinyourtexteditor,youmustsavethefile
beforeattemptingtorecompileit.Ifyoudontsavethechanges,youwillstillbe
compilingtheoldversionofthecodethatwassavedpreviously,evenifthecode
inyourtexteditoriscorrect.
Eventuallyyoushouldgetitrightanditwillcompilewithnoerrorsandnomessageofanykind.Doa
directorylistingandyoushouldseethebytecodefilehasappearedinthefolder:
$javacFirstProg.java
$ls
FirstProg.classFirstProg.javatest.txt
$
Nowthatwehaveavalidbytecodefilewecanrunit(orexecuteit)byrunningitthroughtheJava
VirtualMachine(JVM)programcalledjava:
WhatYouShouldSee
$javaFirstProg
Iamdeterminedtolearnhowtocode.
Today'sdateis
$
NotethatthecommandyoutypeisjavaFirstProg,notjavaFirstProg.javaorevenjava
FirstProg.class.
Areyoustoked?YoujustwroteyourfirstJavaprogramandranit!Ifyoumadeitthisfar,thenyou
almostcertainlyhavewhatittakestofinishthebookaslongasyouworkoniteverydayanddontquit.

StudyDrills
Aftermostoftheexercises,Iwilllistsomeadditionaltasksyoushouldtryaftertypingupthecodeand
gettingittocompileandrun.Somestudydrillswillbefairlysimpleandsomewillbemorechallenging,
butyoushouldalwaysgivethemashot.
1. Changewhatisinsidethequotesonline6toincludetodaysdate.Savethefileonceyouhave
madeyourchanges,compilethefileandrunitagain.
2. Changewhatisinsidethequotesonline5tohavethecomputerdisplayyourname.

WhatYouShouldSeeAfterCompletingtheStudyDrills
$javaFirstProg
I,GrahamMitchell,amdeterminedtolearnhowtocode.
Today'sdateisFriday,July19,2013.
$
Exercise2:MorePrinting
Okay,nowthatwevegottenthatfirst,hardassignmentoutoftheway,welldoanother.Thenicething
isthatinthisone,westillhavealotofthesetupcode(whichwillbenearlythesameeverytime),but
theratioofsetuptousefulcodeismuchbetter.
TypethefollowingtextintoasinglefilenamedLetterToYourself.java.Makesuretomatch
whatIhavewrittenexactly,includingspacing,punctuation,andcapitalization.
1publicclassLetterToYourself
2{
3publicstaticvoidmain(String[]args)
4{
5System.out.println("++");
6System.out.println("|####|");
7System.out.println("|####|");
8System.out.println("|####|");
9System.out.println("||");
10System.out.println("||");
11System.out.println("|BillGates|");
12System.out.println("|1MicrosoftWay|");
13System.out.println("|Redmond,WA98104|");
14System.out.println("||");
15System.out.println("++");
16}
17}

Noticethatthefirstlineisthesameasthepreviousassignment,exceptthatthenameoftheclassisnow
LetterToYourselfinsteadofFirstProg.Alsonotethatthenameofthefileyoureputting
thingsintoisLetterToYourself.javainsteadofFirstProg.java.Thisisnotacoincidence.
InJava,eachfilecancontainonlyonepublicclass,andthenameofthepublicclassmustmatchthefile
name(capitalizationandall)exceptthatthefilenameendsin.javaandthepublicclassnamedoes
not.
So,whatdoespublicclassmeaninJava?Illtellyouwhenyoureolder.Seriously,tryingtogointo
thatkindofdetailupfrontiswhymostbeginnerprogrammingbooksarebadforactualbeginners.So
dontworryaboutit.Justtypeitfornow.(Unfortunately,theresgoingtobealotofthat.)
Youwillprobablynoticethatthesecond,thirdandfourthlinesofthisprogramareexactlythesameas
thepreviousassignment.Therearenodifferenceswhatsoever.
Then,afterthesecondopenbrace,thereareelevenprintingstatements.Theyareallidenticalexceptfor
whatisbetweenthequotationmarks.Thelittleverticalbar(|)iscalledthepipecharacter,andyou
cantypeitusingShift+backslash(\).AssumingyouareusinganormalUSkeyboard,thebackslash
keyislocatedbetweentheBackspaceandEnterkeys.
OnceeverythingistypedinandsavedasLetterToYourself.java,youcancompileandrunitthe
samewayyoudidthepreviousassignment.Switchtoyourterminalwindow,changethedirectoryinto
theonewhereyouaresavingyourcodeandtypethistocompileit:
$javacLetterToYourself.java
Ifyouareextremelygoodwithannoyingdetailsandfortunate,youwillhavenoerrorsandthejavac
commandwillcompletewithoutsayinganythingatall.Probably,youwillhaveerrors.Ifso,goback
andcomparewhatyoutypewithwhatIwroteverycarefully.Eventuallyyouwilldiscoveryourerror(s).
Fixthem,savethefileagain,andtrycompilingagain.
Onceitcompileswithnoerrors,youcanrunitlikebefore:
$javacLetterToYourself.java
$javaLetterToYourself
++
|####|
|####|
|####|
||
||
|BillGates|
|1MicrosoftWay|
|Redmond,WA98104|
||
++
Twoprogramsdone.Nice!Whatyouhaveaccomplishedsofarisnoteasy,andanyonethatthinksitis
hasalotofexperienceandhasforgottenwhatitisliketotrythisstuffforthefirsttime.Dontquit!
Workalittleeverydayandthiswillgeteasier.

StudyDrills
1. ThisfileiscalledLetterToYourself.javanotLetterToBillGates.java!Goback
toyourtexteditorandchangethenameandaddressfromBillGatesaddressatMicrosoftto
yourownnameandaddress.Thensaveit,compileitandrunitagain.

CommonStudentQuestions
DoIhavetousemyrealaddress?
Ofcoursenot.Butmakesureyourfakeaddresstakesupthreelines.
WhydoesntmyletterlineupwhenIruntheprogram?!?Everythinglooksperfectinthecode!
Youprobablyusedamixtureoftabsandspacesbetweenthequotesinyourprintln()statements.
Manytexteditorswillonlymovethecursor4spaceswhenyoupressTAB.Butwhenyourprogram
runs,anytabsembeddedinsidethequoteswilltakeup8spaces,not4.IfyoudeleteALLthetabs
betweenthequotesandreplacethemwithspaces,thingsshouldlookthesameinyourcodeand
whenyouruntheprogram.
Exercise3:PrintingChoices
Javahastwocommoncommandsusedtodisplaythingsonthescreen.Sofarwehaveonlylookedat
println(),butprint()issometimesused,too.Thisexercisewilldemonstratethedifference.
Typethefollowingcodeintoasinglefile.Byreadingthecode,couldyouguessthatthefilemustbe
calledPrintingChoices.java?Infutureassignments,ImaynottellyouwhattonametheJava
file.
1publicclassPrintingChoices
2{
3publicstaticvoidmain(String[]args)
4{
5System.out.println("Alpha");
6System.out.println("Bravo");
7
8System.out.println("Charlie");
9System.out.println("Delta");
10System.out.println();
11
12System.out.print("Echo");
13System.out.print("Foxtrot");
14
15System.out.println("Golf");
16System.out.print("Hotel");
17System.out.println();
18System.out.println("India");
19
20System.out.println();
21System.out.println("This"+""+"is"+""+"a"+"test.");
22
23}
24}
Whenyourunit,thisiswhatyoushouldsee.
Alpha
Bravo
Charlie
Delta

EchoFoxtrotGolf
Hotel
India

Thisisatest.
Canyoufigureoutthedifference?
Bothprint()andprintln()displayonthescreenwhateverisbetweenthequotationmarks.But
println()movestoanewlineafterfinishingprinting,andprint()doesnot:itdisplaysandthen
leavesthecursorrightattheendofthelinesothatthefollowingprintingstatementpicksupfromthat
samepositionontheline.
Youwillalsonotice(online10)thatwecanhaveaprintln()statementwithnothingbetweenthe
parentheses.Noquotationmarksoranything.Thatstatementinstructsthecomputertoprintnothing,and
thenmovethecursortothebeginningofthenextline.
Youmayalsonoticethatthisprogramhassomelineswithnothingonthem(lines7,11,14,19and22).
Ontheveryfirstexercise,whenIwrotethatyoumustmatchwhatIhavewrittenexactly,including
spacing,punctuation,andcapitalization,Iwasntquitebeinghonest.Extrablanklinesinyourcodeare
ignoredbytheJavacompiler.Youcanputtheminorremovethem,andtheprogramwillworkexactly
thesame.
Mystudentsoftenaccusemeofbeingfulloflies.Thisistrue.Ihavelearnedthehardwaythatwhen
studentsarejustlearningsomethingashardasprogramming,tellingthemthetruthwillconfusethem
toomuch.SoIoftenoversimplifywhatIsay,evenwhenthatmakesittechnicallyinaccurate.
Ifyoualreadyknowhowtoprogram,andmyliesoffendyou,thenthisbookwillbedifficulttoread.
Butforthosethatarejustlearning,Iassureyouthatyouwantmetosimplifythingsatfirst.Ipromise
Illrevealthetrutheventually.
Anyway,online21,Ididonemorenewthing.Sofaryouhaveonlybeenprintingasinglethinginside
quotationmarks.Butitisperfectlyfinetoprintmorethanonething,aslongasyoucombinethose
thingsbeforeprinting.
Soonline21,IhavesixStrings1inquotationmarks:thewordthis,aspace,thewordis,aspace,
theworda,andfinallyaspacefollowedbytestfollowedbyaperiod.Thereisaplussign(+)
betweeneachofthosesixStrings,sothereareatotaloffiveplussignsonline21.Whenyouputaplus
signbetweenStrings,Javaadds2themtogethertomakeonelongthinginquotationmarks,andthen
displaysthatallatonce.
Ifyouhaveanerrorinyourcode,itisprobablyonline21.Rememberingtostartandstopallthequotes
correctlyandgettingallthosedetailsrightistricky.
Todayslessonwashopefullyrelativelyeasy.Dontworry,Illmakeupforitonthenextone.

1 WhatisaString?Abunchofcharacters(letters,numbers,symbols)betweenapairofquotationmarks.Illexplain
morelater.
2 Technicallycombiningsmallerwordstomakealargeroneiscalledconcatenation,notadding.Javaconcatenatesthe
Stringstogether.
Exercise4:EscapeSequencesandComments
Haveyouthoughtaboutwhatmighthappenifwewantedtodisplayaquotationmarkonthescreen?
Sinceeverythingwewanttodisplayiscontainedbetweenquotationmarksintheprintln()
statement,puttingaquoteinsidethequoteswouldbeaproblem.
Mostprogramminglanguagesallowforescapesequences,whereyousignalwithsomesortofescape
characterthatthenextcharacteryouseeshouldntbehandledinthenormalway.
Thefollowing(evil)codedemonstratesanumberofJavasescapesequences.Callit
EscapeSequences.java.
1publicclassEscapeSequences
2{
3publicstaticvoidmain(String[]args)
4{
5//InitialversioncreatedusingFIGlet,font"BigMoney",orientedsouthwest
6
7System.out.print("\t_____\n\t/|\n\tJJJJJ|");
8System.out.println("________________");
9System.out.println("\tJJ|/\\/\\/|/\\");
10System.out.println("\t__JJ|aaaaaa|\"\"\\/\"\"/aaaaaa|");
11System.out.println("\t/|JJ|/aa|\"\"/\"\"//aa|");
12System.out.println("\tJJ\\__JJ|/aaaaaaa|\"\"\"\"//aaaaaaa|");
13System.out.println("\tJJJJ/aaaa|\"\"\"/aaaa|");
14System.out.println("\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
upbutwithoutholdingShift.AllescapesequencesinJavamustbeinsideasetofquotes.
\"representsaquotationmark.
\tisatab;itisthesameasifyoupressedtheTabkeywhiletypingyourcode.Itprobablyseemsmore
complicatednowbecauseyouveneverseenitbefore,butwhenyourereadingsomeoneelsescodea
\tinsidethequotesislessambiguousthanabunchofblankspacesthatmightbespacesormightbea
tab.
\nisanewline.Whenprintingitwillcausetheoutputtomovedowntothebeginningofthenextline
beforecontinuingprinting.
\\ishowyoudisplayabackslash.
Online5youwillnoticethatthelinebeginswithtwoslashes(orforwardslashes,ifyouinsist).This
marksthelineasacomment,whichisintheprogramforthehumanprogrammersbenefit.Comments
aretotallyignoredbythecomputer.
Infact,thetwoslashestomarkacommentdonthavetobeatthebeginningoftheline;wecouldwrite
somethinglikethis:
System.out.println("A");//printsan'A'onthescreen
anditwouldtotallywork.Everythingfromthetwoslashestotheendofthatlineisignoredbythe
compiler.
(Thatsnotaverygoodcomment,though;anyprogrammerwhoknowsJavaalreadyknowswhat
thatlineofcodedoes.Ingeneralyoushouldputcommentsexplainingwhythecodeisthere,not
whatthecodedoes.Youllgetbetteratwritinggoodcommentsasyougetbetteratcodingin
general.)
Anyway,thisonewasatoughone,sonoStudyDrillsthistime.Thenextexercisewillfeature
somethingnewandreturntonormaldifficulty.
Exercise5:SavingInformationinVariables
Programswouldbeprettyboringiftheonlythingyoucoulddowasprintthingsonthescreen.We
wouldlikeourprogramstobeinteractive.
Unfortunately,interactivityrequiresseveraldifferentconceptsworkingtogether,andexplainingthemall
atoncemightbeconfusing.SoIamgoingtocoverthemoneatatime.
Firstup:variables!IfyouhaveevertakenanAlgebraclass,youarefamiliarwiththeconceptof
variablesinmathematics.Programminglanguageshavevariables,too,andthebasicconceptisthe
same:
Avariableisanamethatreferstoalocationthatholdsavalue.
VariablesinJavahavefourmajordifferencesfrommathvariables:
1. Variablenamescanbemorethanoneletterlong.
2. Variablescanholdmorethanjustnumbers;theycanholdwords.
3. Youhavetochoosewhattypeofvaluesthevariablewillholdwhenthevariableisfirstcreated.
4. Thevalueofavariable(butnotitstype)canchangethroughouttheprogram.Thevariable
scoremightstartoutwithavalueof0,butbytheendoftheprogram,scoremightholdthe
value413500instead.
Okay,enoughdiscussion.Letsgettothecode!Imnotgoingtotellyouwhatthenameofthefileis
supposedtobe.Youllhavetofigureitoutforyourself.
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
21System.out.println("Thevariablexcontains"+x);
22System.out.println("Thevalue"+y+"isstoredinthevariabley.");
23System.out.println("Theexperimentcompletedin"+seconds+"seconds.");
24System.out.println("MyfavoriteirrationalnumberisEuler'sconstant:"+e);
25System.out.println("Hopefullyyourbalanceismorethan$"+checking+"!");
26System.out.println("Myfullnameis"+title+""+firstName+last_name);
27}
28}

WhatYouShouldSee
Thevariablexcontains10
Thevalue400isstoredinthevariabley.
Theexperimentcompletedin4.71seconds.
MyfavoriteirrationalnumberisEuler'sconstant:2.718281828459045
Hopefullyyourbalanceismorethan$1.89!
MyfullnameisMr.GrahamMitchell
Onlines5through7wedeclare3ninevariables.Thefirstthreearenamedx,y,andage.Allthreeof
thesevariablesareintegers,whichisthetypeofvariablethatcanholdavaluebetweentwobillion.
Avariablewhichisanintegercouldholdthevalue10.Itcouldholdthevalue8192.Aninteger
variablecanhold123456789.Itcouldnotholdthevalue3.14becausethathasafractionalpart.An
integervariablecouldnotholdthevalue10000000000becausetenbillionistoobig.
Online6wedeclarevariablesnamedseconds,e,andchecking.Thesethreevariablesaredoubles,
whichisthetypeofvariablethatcanholdanumberthatmighthaveafractionalpart.
Avariablewhichisadoublecouldholdthevalue4.71.Itcouldholdthevalue8192.(Itmayhavea
fractionalpartbutdoesnthaveto.)Itcanprettymuchholdanyvaluebetween1.7976910308and
4.9406510324.
However,doubleshavelimitedprecision.Noticethatonline14Istorethevalue
2.71828182845904523536intothevariablenamede,butwhenIprintoutthatvalueonline24,
only2.718281828459045comesout.Doublesdonothaveenoughsignificantfigurestoholdthe
value2.71828182845904523536precisely.Integershaveperfectprecision,butcanonlyhold
wholenumbersandcantholdhugehugevalues.
ThelasttypeofvariablewearegoingtolookatinthisexerciseistheString.Online7wedeclare
threeStringvariables:firstName,last_nameandtitle.Stringvariablescanholdwordsandphrases;the
nameisshortforstringofcharacters.
Onlines9through11weinitialize4thethreeintegervalues.Thevalue10isstoredintox.Beforethis
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;
11System.out.println("ais"+a+",bis"+b);
12
13c=a+b;
14System.out.println("a+bis"+c);
15d=ab;
16System.out.println("abis"+d);
17e=a+b*3;
18System.out.println("a+b*3is"+e);
19f=b/2;
20System.out.println("b/2is"+f);
21g=b%10;
22System.out.println("b%10is"+g);
23
24x=1.1;
25System.out.println("\nxis"+x);
26y=x*x;
27System.out.println("x*xis"+y);
28z=b/2;
29System.out.println("b/2is"+z);
30System.out.println();
31
32one="dog";
33two="house";
34both=one+two;
35System.out.println(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()willsubtractonenumberfromanother.Justlikeaddition,itworkswithtwointegers,
twodoubles,oroneintegerandonedouble(ineitherorder).
Anasterisk(*)isusedtorepresentmultiplication.Youcanalsoseeonline17thatJavaknowsaboutthe
correctorderofoperations.bismultipliedby3giving81andthenaisadded.
Aslash(/)isusedfordivision.Noticethatwhenanintegerisdividedbyanotherinteger(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
precision.Youwillmostlybeabletoignorethatfactinthisbook,butIwould
likeyoutokeepinthebackofyourmindthatdoublevariablessometimesgive
youvaluesthatareslightlydifferentthanyoudexpect.
Exercise7:GettingInputfromaHuman
Nowthatwehavepracticedcreatingvariablesforabit,wearegoingtolookattheotherpartof
interactiveprograms:lettingthehumanwhoisrunningourprogramhaveachancetotypesomething.
Goaheadandtypethisup,butnoticethatthefirstlineintheprogramisnotthepublicclassline.
Thistimewestartwithanimportstatement.
Noteveryprogramneedstogetinteractiveinputfromahumanusingthekeyboard,sothisisnotpartof
thecoreoftheJavalanguage.JustlikeaFormula1racecardoesnotincludeanairconditioner,
programminglanguagesusuallyhaveasmallcoreandthenlotsofoptionallibraries6thatcanbe
includedifdesired.
1importjava.util.Scanner;
2
3publicclassForgetfulMachine
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9System.out.println("WhatcityisthecapitalofFrance?");
10keyboard.next();
11
12System.out.println("Whatis6multipliedby7?");
13keyboard.nextInt();
14
15System.out.println("Whatisyourfavoritenumberbetween0.0and1.0?");
16keyboard.nextDouble();
17
18System.out.println("Isthereanythingelseyouwouldliketotellme?");
19keyboard.next();
20}
21}

Whenyoufirstrunthisprogram,itwillonlyprintthefirstline:
WhatcityisthecapitalofFrance?
andthenitwillblinkthecursoratyou,waitingforyoutotypeinaword.WhenIrantheprogram,I
typedthewordParis,buttheprogramwillworkthesameevenifyoutypeadifferentword.
ThenafteryoutypeawordandpressEnter,theprogramwillcontinue,printing:
Whatis6multipliedby7?
andsoon.Assumingyoutypeinreasonableanswerstoeachquestion,itwillenduplookinglikethis:

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

6 libraryormoduleachunkofcodethataddsextrafunctionalitytoaprogramandwhichmayormaynotbeincluded.
Soletustalkaboutthecode.Online1wehaveanimportstatement.Thelibraryweimportisthe
scannerlibraryjava.util.Scanner(javadotutildotScanner).Thislibrarycontains
functionalitythatallowsustoreadininformationfromthekeyboardorotherplaceslikefilesorthe
Internet.
Lines2through7arehopefullyboring.Online8weseesomethingelsenew:wecreateaScanner
objectnamedkeyboard.(Itdoesnthavetobenamedkeyboard;youcoulduseadifferentword
thereaslongasyouuseiteverywhereinyourcode.)ThisScannerobjectnamedkeyboardcontains
abilitieswellcallfunctionsormethods.YoumustcreateandnameaScannerobjectbeforeyoucan
useone.
Online10weasktheScannerobjectnamedkeyboardtodosomethingforus.WesayKeyboard,run
yournext()function.TheScannerobjectwillpausetheprogramandwaitforthehumantotype
something.OncethehumantypessomethingandpressesEnter,theScannerobjectwillpackageitintoa
Stringandallowyourcodetocontinue.
Online13weasktheScannerobjecttoexecuteitsnextInt()function.Thispausestheprogram,
waitsforthehumantotypesomethingandpressEnter,thenpackagesitintoanintegervalue(if
possible)andcontinues.
Whatifthehumandoesnttypeanintegerhere?Tryrunningtheprogramagainandtype41.9asthe
answertothesecondquestion.
Theprogramblowsupanddoesntrunanyotherstatementsbecause41.9cannotbepackagedintoan
integervalue:41.9isadouble.Eventuallywewilllookatwaystohandleerrorcheckingforissues
likethis,butinthemeantime,ifthehumantypesinsomethingincorrectlywhichblowsupourprogram,
wewillblamethehumanfornotfollowingdirectionsandnotworryaboutit.
Line16letsthehumantypeinsomethingwhichtheScannerobjectwillattempttoconvertintoadouble
value,andline19letsthehumantypeinaString.(AnythingcanbepackagedasaString,including
numbers,sothisisntlikelytofail.)
Tryrunningtheprogramseveralmoretimes,noticingwhenitblowsupandwhenitdoesnt.
Exercise8:StoringtheHumansResponses
Inthelastexercise,youlearnedhowtopausetheprogramandallowthehumantotypeinsomething.
Butwhathappenedtowhatwastyped?WhenyoutypedintheanswerParisforthefirstquestion,
wheredidthatanswergo?Well,itwasthrownawayrightafteritwastypedbecausewedidntputany
instructionstotelltheScannerobjectwheretostoreit.Sothatisthetopicoftodayslesson.
1importjava.util.Scanner;
2
3publicclassRudeQuestions
4{
5publicstaticvoidmain(String[]args)
6{
7Stringname;
8intage;
9doubleweight,income;
10
11Scannerkeyboard=newScanner(System.in);
12
13System.out.print("Hello.Whatisyourname?");
14name=keyboard.next();
15
16System.out.print("Hi,"+name+"!Howoldareyou?");
17age=keyboard.nextInt();
18
19System.out.println("Soyou're"+age+",eh?That'snotoldatall.");
20System.out.print("Howmuchdoyouweigh,"+name+"?");
21weight=keyboard.nextDouble();
22
23System.out.print(weight+"!Betterkeepthatquiet.Finally,what'syourincome,"+
name+"?");
24income=keyboard.nextDouble();
25
26System.out.println("Hopefullythatis"+income+"perhourandnotperyear!");
27System.out.println("Well,thanksforansweringmyrudequestions,"+name+".");
28}
29}

(Sorrythatline23wrapslikethat.Ididn'twanttomakethefonttinyjustonaccountofthatoneline.
Justtypeitallononelinelikeusual.)
Justlikethelastexercise,whenyoufirstrunthisyourprogramwillonlydisplaythefirstquestionand
thenpause,waitingforaresponse:
Hello.Whatisyourname?
Noticethatbecausethatfirstprintingstatementonline13isprint()ratherthanprintln(),the
cursorisleftblinkingattheendofthelinethequestionison.Ifyouhadusedprintln(),thecursor
wouldblinkonthebeginningofthenextlineinstead.

WhatYouShouldSee
Hello.Whatisyourname?Brick
Hi,Brick!Howoldareyou?25
Soyou're25,eh?That'snotoldatall.
Howmuchdoyouweigh,Brick?192
192.0!Betterkeepthatquiet.Finally,what'syourincome,Brick?8.75
Hopefullythatis8.75perhourandnotperyear!
Well,thanksforansweringmyrudequestions,Brick.
Atthetopoftheprogramwedeclaredfourvariables:oneStringvariablenamedname,oneinteger
variablenamedage,andtwodoublevariablesnamedweightandincome.
Online14weseethekeyboard.next()thatweknowfromthepreviousexercisewillpausethe
programandletthehumantypeinsomethingitwillpackageupinaString.Sonowwheredoesthe
Stringtheytypego?Inthiscase,wearestoringthatvalueintotheStringvariablenamedname.The
StringvaluegetsstoredintoaStringvariable.Nice.
So,assumingyoutypeBrickforyourname,theStringvalue"Brick"getsstoredintothevariable
nameonline14.Thismeansthatonline16,wecandisplaythatvalueonthescreen!Thatsprettycool,
ifyouaskme.
Online17weasktheScannerobjecttoletthehumantypeinsomethingwhichitwilltrytoformatasan
integer,andthenthatvaluewillbestoredintotheintegervariablenamedage.Wedisplaythatvalueon
thescreenonline19.
Line21readsinadoublevalueandstoresitintoweight,andline24readsinanotherdoublevalueand
storesitintoincome.
Thisisareallypowerfulthing.WithsomevariablesandwiththehelpoftheScannerobject,wecannow
letthehumantypeininformation,andwecanrememberitinavariabletouselaterintheprogram!
BeforeIwrapup,noticeforexamplethatthevariableincomeisdeclaredallthewayuponline9(we
chooseitsnameandtype),butitisundefined(itdoesnthaveavalue)untilline24.Online24incomeis
finallyinitialized(givenitsfirstvalueoftheprogram).Ifyouhadattemptedtoprintthevalueofincome
onthescreenpriortoline24,theprogramwouldnothavecompiled.
Anyway,playwithtypingindifferentanswerstothequestionsandseeifyoucangettheprogramto
blowupaftereachquestion.
Exercise9:CalculationswithUserInput
Nowthatweknowhowtogetinputfromtheuserandstoreitintovariablesandsinceweknowhowto
dosomebasicmath,wecannowwriteourfirstusefulprogram!
1importjava.util.Scanner;
2
3publicclassBMICalculator
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8doublem,kg,bmi;
9
10System.out.print("Yourheightinm:");
11m=keyboard.nextDouble();
12
13System.out.print("Yourweightinkg:");
14kg=keyboard.nextDouble();
15
16bmi=kg/(m*m);
17
18System.out.println("YourBMIis"+bmi);
19}
20}

WhatYouShouldSee
Yourheightinm:1.75
Yourweightinkg:73
YourBMIis23.836734693877553
Thisexerciseis(hopefully)prettystraightforward.Wehavethreevariables(alldoubles):m(meters),kg
(kilograms)andbmi(bodymassindex).Wereadinvaluesformandkg,butbmisvaluecomesnotfrom
thehumanbutastheresultofacalculation.Online16wecomputethemassdividedbythesquareof
theheightandstoretheresultintobmi.Andthenweprintitout.
Thebodymassindex(BMI)iscommonlyusedbyhealthandnutritionprofessionalstoestimatehuman
bodyfatinpopulations.Sothisresultwouldbeinformativeforahealthprofessional.Fornowthatsall
wecandowithit.
EventuallywewilllearnhowtodisplayadifferentmessageonthescreendependingonwhattheBMI
equals,butfornowthiswillhavetodo.
Aprettyeasyassignmentfortoday,butIhavesomechallengesforyouintheStudyDrillsthatshould
makethingsabittougher.

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

2.Makeitsothehumancaninputtheirheightinfeetandinchesseparately.
Yourheight(feetonly):5
Yourheight(inches):9
Yourweightinpounds:160
YourBMIis23.625289
Exercise10:VariablesOnlyHoldValues
Okay,nowthatwecangetinputfromthehumananddocalculationswithit,Iwanttocallattentionto
somethingthatmanyofmystudentsgetconfusedabout.Thefollowingcodeshouldcompile,butit
probablywillnotworkthewayyouexpect.
Ihaveintentionallymadealogicalerrorinthecode.Itisnotaproblemwiththesyntax(thepartofthe
codethecompilercaresabout),anditisnotaruntimeerrorlikeyougetwhenthehumantypesadouble
whentheScannerobjectisexpectinganinteger.ThislogicalerrorisaflawwithhowIhavedesigned
theflowofinstructions,sothattheoutputisnotwhatIwastryingtoaccomplish.
1importjava.util.Scanner;
2
3publicclassSequencing
4{
5publicstaticvoidmain(String[]args)
6{
7//BROKEN
8
9Scannerkeyboard=newScanner(System.in);
10doubleprice=0,salesTax,total;
11
12salesTax=price*0.0825;
13total=price+salesTax;
14
15System.out.print("Howmuchisthepurchaseprice?");
16price=keyboard.nextDouble();
17
18System.out.println("Itemprice:\t"+price);
19System.out.println("Salestax:\t"+salesTax);
20System.out.println("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.
Lookatline12.Mystudentssometimesthinkthatlinestorestheformulaprice*0.0825intothe
variablesalesTaxandthenlaterthehumanstoresthevalue7.99intothevariableprice.Theythinkthat
online19whenweprintoutsalesTaxthatthecomputerthenrunstheformulasomehow.
Thisisnotwhathappens.Infact,thisprogramshouldnthaveevencompiled.Thevariablepricedoesnt
evenhaveapropervalueonline12.TheonlyreasonitdoeshaveavalueisbecauseIdidsomething
sneakyonline10.
Normallywehavebeendeclaringvariablesupatthetopofourprogramsandtheninitializingthem
later.Butonline10Ideclaredpriceandinitializeditwithavalueof0.Whenyoudeclareandinitialize
avariableatthesametime,thatiscalleddefiningthevariable.salesTaxandtotalarenotdefinedon
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
intosalesTaxbutitdoesstoreavalue.Whatvalue?Ittakesthevalueofthevariablepriceatthispoint
inthecode(whichis0),multipliesitby0.0825(whichisstillzero),andthenstoresthatzerointo
salesTax.
Asline12isbeginning,thevalueofsalesTaxisundefined.(salesTaxisdeclaredbutnotdefined.)By
theendofline12,salesTaxholdsthevalue0.ThereisnolineofcodethatchangessalesTax(thereisno
lineofcodethatbeginswithsalesTax=),sothatvalueneverchangesandsalesTaxisstillzerowhen
itisdisplayedonline19.
Line13issimilar.Ittakesthevalueofpricerightthen(zero)andaddsittothevalueofsalesTaxright
then(alsozero)andstoresthesum(zero)intothevariabletotal.Andtotalsvalueisneverchanged,and
totaldoesnotsomehowrememberthatitsvaluecamefromaformulainvolvingsomevariables.
Sothereyouhaveit.Variablesholdvalues,notformulas.Computerprogramsarenotasetofrules,they
areasequenceofinstructionsthatthecomputerexecutesinorder,andthingslaterinyourcodedepend
onwhathappenedbefore.

StudyDrills
1. Removethe=0online10,sothatpricenolongergetsdefinedonline10,onlydeclared.
Whathappenswhenyoutrytocompilethecode?Doestheerrormessagemakesense?(Nowput
the=0backsothattheprogramcompilesagain.)
2. MovethetwolinesofcodethatgivevaluestosalesTaxandtotalsotheyoccurafterpricehas
beengivenapropervalue.Confirmthattheprogramnowworksasexpected.
3. Nowthattheselinesoccurafterthevariablepricehasbeenproperlygivenarealvalue,try
removingthe=0online10again.Doestheprogramstillgiveanerror?Areyousurprised?
Exercise11:VariableModificationShortcuts
Thevalueofavariablecanchangeovertimeasyourprogramruns.(Itwontchangeunlessyouwrite
codetochangeit,butitcanchangeiswhatImsaying.)
Infact,thisisprettycommon.Somethingwedoprettyoftenistakeavariableandaddsomethingtoit.
Forexample,letssaythevariablexcontainsthevalue10.Wewanttoadd2toitsothatxnow
contains12.
Wecandothis:
intx=10,temp_x;
temp_x=x+2;
x=temp_x;
Thiswillwork,butitisannoying.Ifwewant,wecantakeadvantageofthefactthatavariablecanhave
onevalueatthebeginningofalineofcodeandhaveadifferentvaluestoredinitbytheend.Sowecan
writesomethinglikethis:
intx=10;
x=2+x;
Thisalsoworks.Thatsecondlinesaystakethecurrentvalueofx(10),add2toit,andstorethesum
(12)intothevariablex.Sowhenthesecondlineofcodebeginsexecutingxis10,andwhenitisdone
executing,xis12.Theorderofaddingdoesntmatter,sowecanevendosomethinglikethis:
intx=10;
x=x+2;
whichisidenticaltothepreviousexample.Okay,nowtothecode!
1publicclassVariableChangeShortcuts
2{
3publicstaticvoidmain(String[]args)
4{
5inti,j,k;
6
7i=5;
8j=5;
9k=5;
10
11System.out.println("i:"+i+"\tj:"+j+"\tk:"+k);
12i=i+3;
13j=j3;
14k=k*3;
15System.out.println("i:"+i+"\tj:"+j+"\tk:"+k);
16
17i=5;
18j=5;
19k=5;
20
21System.out.println("\ni:"+i+"\tj:"+j+"\tk:"+k);
22i+=3;
23j=3;
24k*=3;
25System.out.println("i:"+i+"\tj:"+j+"\tk:"+k);
26
27i=j=k=5;
28
29System.out.println("\ni:"+i+"\tj:"+j+"\tk:"+k);
30i+=1;
31j=2;
32k*=3;
33System.out.println("i:"+i+"\tj:"+j+"\tk:"+k);
34
35i=j=k=5;
36
37System.out.println("\ni:"+i+"\tj:"+j+"\tk:"+k);
38i=+1;
39j=2;
40System.out.println("i:"+i+"\tj:"+j+"\tk:"+k);
41
42i=j=k=5;
43
44System.out.println("\ni:"+i+"\tj:"+j+"\tk:"+k);
45i++;
46j;
47System.out.println("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
Hopefullylines121areniceandboring.Wecreatethreevariables,givethemvalues,displaythem,
changetheirvaluesandprintthemagain.Thenstartingonline17wegivethevariablesthesamevalues
theystartedwithandprintthem.
Online22weseesomethingnew:ashortcutcalledacompoundassignmentoperator.Thei+=3
meansthesameasi=i+3:takethecurrentvalueofi,add3toit,andstoretheresultasthenew
valueofi.Whenwesayitoutloud,wewouldsayiplusequals3.
Online23wesee=(minusequals),whichsubtracts3fromk,andline24demonstrates*=,which
multiplies.Thereisalso/=,whichdivideswhatevervariableisonthelefthandsidebywhatevervalue
therighthandsideendsupequaling.(Modulusequals(%=)alsoexists,whichsetsthevariableonthe
lefthandsideequaltowhatevertheremainderiswhenitspreviousvalueisdividedbywhateverison
theright.Whew.)
Thenonline27Idosomethingelseweird.Insteadoftakingthreelinesofcodetoseti,jandkallto5,I
doitinoneline.(Somepeopledontapproveofthistrick,butIthinkitsfineincaseslikethis.)Line27
meansPutthevalue5intothevariablek.Thentakeacopyofwhatevervalueisnowink(5)andstore
itintoj.Thentakeacopyofwhateverisnowinjandstoreitintoi.Sowhenthislineofcodeisdone,
allthreevariableshavebeenchangedtoequal5.
Lines30through32arebasicallythesameaslines22through24exceptthatwearenolongerusing3
asthenumbertoadd,subtractormultiply.
Line38mightlooklikeatypo,andifyouwrotethisinyourowncodeitprobablywouldbe.Noticethat
insteadof+=Iwrote=+.Thiswillcompile,butitisnotinterpretedthewayyoudexpect.Thecompiler
seesi=+1;,thatis,Setiequaltopositive1.Andline39issimilarSetjequaltonegative2.So
watchforthat.
Online45weseeonemoreshortcut:thepostincrementoperator.i++justmeansadd1towhatever
isini.Itsthesameaswritingi=i+1ori+=1.Adding1toavariableissupercommon.
(Youllsee.)Thatswhytheresaspecialshortcutforit.
Online46weseethepostdecrementoperator:j.Itsubtracts1fromthevalueinj.
Todayslessonisunusualbecausetheseshortcutsareoptional.Youcouldwritecodeyourwholelife
andneverusethem.Butmostprogrammersarelazyanddontwanttotypeanymorethantheyhaveto,
soifyoueverreadotherpeoplescodeyouwillseetheseprettyoften.
Exercise12:BooleanExpressions
Sofarwehaveonlyseenthreetypesofvariables:
int
integers,holdnumbers(positiveornegative)withnofractionalparts
double
doubleprecisionfloatingpointnumbers(positiveornegative)thatcouldhaveafractionalpart
String
astringacharacters,holdwords,phrases,symbols,sentences,whatever
ButinthewordsofYoda:Thereisanother.ABooleanvariable(namedafterthemathematician
GeorgeBoole)cannotholdnumbersorwords.Itcanonlystoreoneoftwovalues:trueorfalse.
Thatsit.Wecanusethemtoperformlogic.Tothecode!
1importjava.util.Scanner;
2
3publicclassBooleanExpressions
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9booleana,b,c,d,e,f;
10doublex,y;
11
12System.out.print("Givemetwonumbers.First:");
13x=keyboard.nextDouble();
14System.out.print("Second:");
15y=keyboard.nextDouble();
16
17a=(x<y);
18b=(x<=y);
19c=(x==y);
20d=(x!=y);
21e=(x>y);
22f=(x>=y);
23
24System.out.println(x+"isLESSTHAN"+y+":"+a);
25System.out.println(x+"isLESSTHANorEQUALTO"+y+":"+b);
26System.out.println(x+"isEQUALTO"+y+":"+c);
27System.out.println(x+"isNOTEQUALTO"+y+":"+d);
28System.out.println(x+"isGREATERTHAN"+y+":"+e);
29System.out.println(x+"isGREATERTHANorEQUALTO"+y+":"+f
);
30System.out.println();
31
32System.out.println(!(x<y)+""+(x>=y));
33System.out.println(!(x<=y)+""+(x>y));
34System.out.println(!(x==y)+""+(x!=y));
35System.out.println(!(x!=y)+""+(x==y));
36System.out.println(!(x>y)+""+(x<=y));
37System.out.println(!(x>=y)+""+(x<y));
38
39}
40}
WhatYouShouldSee
Givemetwonumbers.First:3
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:theresultofacomparison.The
currentvalueinthevariablexiscomparedtothevalueofthevariabley.Ifxislessthany,thenthe
comparisonistrueandtheBooleanvaluetrueisstoredintoa.Ifxisnotlessthany,thenthe
comparisonisfalseandthebooleanvaluefalseisstoredintoa.(Ithinkthatiseasiertounderstand
thanitistowrite.)
Line18issimilar,exceptthatthecomparisonislessthanorequalto,andtheBooleanresultisstored
intob.
Line19isequalto:cwillbesettothevaluetrueifxholdsthesamevalueasy.Thecomparisonin
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
Java.Andinthethirdline,bdoesgetsettothevaluetruehere,butnotifyoureadthevalueintoa
variablelikeso:
Stringanimal;
animal=keyboard.next();//theusertypesin"horse"
b=(animal=="horse");
bwillalwaysgetsettothevaluefalse,nomatterifthehumantypes"horse"ornot!
Idontwanttotrytoexplainwhythisis.ThecreatorsofJavadohaveagoodreasonforthisapparently
weirdbehavior,butitsnotfriendlyforbeginnersandexplainingitwouldprobablyonlyconfuseyou
moreatthispointinyourlearning.
DoyourememberwhenIwarnedyouthatJavaisnotalanguageforbeginners?
SothereisawaytocompareStringsforequality,soletslookatit.
1importjava.util.Scanner;
2
3publicclassWeaselOrNot
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9Stringword;
10booleanyep,nope;
11
12System.out.println("Typetheword\"weasel\",please.");
13word=keyboard.next();
14
15yep=word.equals("weasel");
16nope=!word.equals("weasel");
17
18System.out.println("Youtypedwhatwasrequested:"+yep);
19System.out.println("Youignoredpoliteinstructions:"+nope);
20}
21}

WhatYouShouldSee
Typetheword"weasel",please.
no
Youtypedwhatwasrequested:false
Youignoredpoliteinstructions:true
SoStringshaveabuiltinmethodnamed.equals()(dotequals)thatcomparesitselftoanother
String,simplifyingtothevaluetrueiftheyareequalandtothevaluefalseiftheyarenot.Andyou
mustusethenotoperator(!)togetherwiththe.equals()methodtofindoutiftwoStringsare
different.
StudyDrills
1. Trychangingaroundthecomparisononline15sothat"weasel"isinfrontofthedotandthe
variablewordisinsidetheparentheses.Makesurethat"weasel"isstillsurroundedbyquotes
andthatwordisnot.Doesitwork?
Exercise14:CompoundBooleanExpressions
Sometimeswewanttouselogicmorecomplicatedthanjustlessthanorequalto.Imaginea
grandmotherwhowillonlyapproveyoudatinghergrandchildifyouareolderthan25andyoungerthan
40andeitherrichorreallygoodlooking.Ifthatgrandmotherwasaprogrammerandcouldconvince
applicantstoanswerhonestly,herprogrammightlookabitlikethis:
1importjava.util.Scanner;
2
3publicclassShallowGrandmother
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9intage;
10doubleincome,attractiveness;
11booleanallowed;
12
13System.out.print("Enteryourage:");
14age=keyboard.nextInt();
15
16System.out.print("Enteryouryearlyincome:");
17income=keyboard.nextDouble();
18
19System.out.print("Howattractiveareyou,onascalefrom0.0to10.0?");
20attractiveness=keyboard.nextDouble();
21
22allowed=(age>25&&age<40&&(income>50000||attractiveness>=8.5));
23
24System.out.println("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,probably.JavasyntaxismodeledafterC++ssyntax,
whichwasbasicallycopiedfromCssyntax,andthatwasmodifiedfromBssyntax,
whichwasinventedbyDennisRitchieandKenThompson.
TheprogramminglanguageBused&tomeanANDand|forOR,buttheywere
bitwise:theyonlyworkedontwointegersandtheywouldwalkonebitatatime
downtheintegersdoingabitwiseANDorORoneachpairofbits,puttinga1or0in
theoutputforeachcomparison.(|wasprobablyusedbecauseitwas
mathematicallookingandwasakeyonthekeyboardsofthePDP7computerthatB
wasoriginallydevelopedfor.)
WhenKenandDennisstarteddevelopingtheprogramminglanguageCtoreplaceB,
theydecidedtherewasaneedforalogicalANDandOR,andthe
onesymbollongthingswerealreadytaken,sotheyusedtwoampersandstorepresent
logicalANDandtwoverticalbarsorpipestorepresentlogicalOR.Whew.
Fortunatelyforyou,youdontneedtoknowanyofthat.Youjustneedtorememberwhattotypeand
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
goonacruiseifitischeapANDthealcoholisincludedintheprice.Sowewillpretendthatstatement
AisthecruiseischeapandstatementBisthealcoholisincluded.Eachrowinthetableisa
possiblecruiseline.
Row1isacruisewherebothstatementsaretrue.Willgrandmotherbeexcitedaboutcruise#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
mileage.StatementAiscariscoollooking,Bisgoodmilespergallonandtheresult,AORB,
determinesifitisacargrandmotherwouldwant.
Car#1isawesomelookinganditalsogoesalongwayonatankofgas.Isgrandmotherinterested?
Heck,yes!WecansaythatthevaluetrueORedwiththevaluetruegivesaresultoftrue.
Infact,theonlycargrandmotherwontlikeiswhenbotharefalse.AnexpressioninvolvingORisonly
falseifBOTHofitscomponentsarefalse.
StudyDrills
1. DidyouknowthatJavahasbitwiseoperators,too?Investigatehownumbersarerepresentedin
binaryandseeifyoucanfigureoutwhythefollowingcodesetsxtothevalue7andsetsytothe
value1.
intx=3|5;
inty=3&5;
Exercise15:MakingDecisionswithIfStatements
Hey!Ireallylikethisexercise.Yousufferedthroughsomeprettyboringonesthere,soitstimetolearn
somethingthatisusefulandnotsuperdifficult.
Wearegoingtolearnhowtowritecodethathasdecisionsinit,sothattheoutputisntalwaysthesame.
Thecodethatgetsexecutedchangesdependingonwhatthehumanenters.
1importjava.util.Scanner;
2
3publicclassAgeMessages
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9intage;
10
11System.out.print("Howoldareyou?");
12age=keyboard.nextInt();
13
14if(age<13)
15{
16System.out.println("YouaretooyoungtocreateaFacebook
account.");
17}
18if(age<16)
19{
20System.out.println("Youaretooyoungtogetadriver'slicense."
);
21}
22if(age<18)
23{
24System.out.println("Youaretooyoungtogetatattoo.");
25}
26if(age<21)
27{
28System.out.println("Youaretooyoungtodrinkalcohol.");
29}
30if(age<35)
31{
32System.out.println("YouaretooyoungtorunforPresidentofthe
UnitedStates.");
33System.out.println("Howsad!");
34}
35}
36}

WhatYouShouldSee
Howoldareyou?17
Youaretooyoungtogetatattoo.
Youaretooyoungtodrinkalcohol.
YouaretooyoungtorunforPresidentoftheUnitedStates.
Howsad!
Okay,thisiscalledanifstatement.Anifstatementstartswiththekeywordif,followedbya
conditioninparentheses.TheconditionmustbeaBooleanexpressionthatevaluatestoeithertrueor
false.Underneaththatstartsablockofcodesurroundedbycurlybraces,andthestuffinsidethecurly
bracesisindentedonemorelevel.Thatblockofcodeiscalledthebodyoftheifstatement.
Whentheconditionoftheifstatementistrue,allthecodeinthebodyoftheifstatementisexecuted.
Whentheconditionoftheifstatementisfalse,allthecodeinthebodyisskipped.Youcanhaveas
manylinesofcodeasyouwantinsidethebodyofanifstatement;theywillallbeexecutedorskipped
asagroup.
NoticethatwhenIranthecode,Iputin17formyage.Because17isnotlessthan13,theconditionon
line14isfalse,andsothecodeinthebodyofthefirstifstatement(lines15through17)wasskipped.
Thesecondifstatementwasalsofalsebecause17isnotlessthan16,sothecodeinitsbody(lines19
through21)wasskipped,too.
Theconditionofthethirdifstatementwastrue:17islessthan18,sothebodyofthethirdifstatement
wasnotskipped;itwasexecutedandthephraseYouaretooyoungtogetatattoowasprintedonthe
screen.Theremainingifstatementsintheexercisearealltrue.
Thefinalifstatementcontainstwolinesofcodeinitsbody,justtoshowyouwhatitwouldlooklike.

StudyDrills
1. Ifyoutypeinanagegreaterthan35whatgetsprinted?Why?
2. Addonemoreifstatementcomparingtheirageto65.Iftheirageisgreaterthanorequalto65,
sayYouareoldenoughtoretire!.
3. Foreachifstatement,addanotherifstatementthatsaystheopposite.Forexample,iftheirageis
greaterthanorequalto13,sayYouareoldenoughtocreateaFacebookaccount.Whenyou
aredone,yourprogramshouldshowsixmessageseverytimenomatterwhatageyouenter.
Exercise16:MoreIfStatements
Thereisalmostnothingnewinthisexercise.Itisjustmorepracticewithifstatements,becausetheyre
prettyimportant.Itwillalsohelpyoutoremembertherelationaloperators.
1importjava.util.Scanner;
2
3publicclassComparingNumbers
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8doublefirst,second;
9
10System.out.print("Givemetwonumbers.First:");
11first=keyboard.nextDouble();
12System.out.print("Second:");
13second=keyboard.nextDouble();
14
15if(first<second)
16{
17System.out.println(first+"isLESSTHAN"+second);
18}
19if(first<=second)
20{
21System.out.println(first+"isLESSTHANorEQUALTO"+second);
22}
23if(first==second)
24{
25System.out.println(first+"isEQUALTO"+second);
26}
27if(first>=second)
28{
29System.out.println(first+"isGREATERTHANorEQUALTO"+second);
30}
31if(first>second)
32{
33System.out.println(first+"isGREATERTHAN"+second);
34}
35
36if(first!=second)
37System.out.println(first+"isNOTEQUALTO"+second);
38
39}
40}

WhatYouShouldSee
Givemetwonumbers.First:3
Second:4
3.0isLESSTHAN4.0
3.0isLESSTHANorEQUALTO4.0
3.0isNOTEQUALTO4.0
Online37youwillseethatIdidsomethingquestionable:thebodyofthelastifstatementdoesnothave
anycurlybracesaroundit.Isthisokay?
Actually,itis.Whenthebodyofanifstatementdoesnothavecurlybraces,thenonlythefirstlineof
codeaftertheconditionisincludedinthebody.So,sincealltheifstatementsinthiswholeexercise
haveonlyonelineofcodeintheirbodies,alltheifstatementcurlybracesinthisexerciseareoptional.
Youcouldremoveandtheprogramwouldworkthesame.Itisneverwrongtoincludethem,though,
andsomeprogrammersalwaysputcurlybracesnomatterwhat.
StudyDrills
1. Addanotherlineofcodeafterline37thatsaysSystem.out.println("Hey.");.
Indentitsothatitlinesupwiththeprintln()statementaboveit,likeso:
if(first!=second)
System.out.println(first+"isNOTEQUALTO"+second);
System.out.println("Hey.");
Runtheprogram,andseewhathappens.IstheHeypartoftheifstatementbody?Thatis,whentheif
statementisskipped,istheHeyskipped,too,ordoesitrunnomatterwhat?Whatdoyouthink?
1. AddcurlybracesaroundthebodyofthefinalifstatementsothattheHeylineispartofthe
body.Thenremovealltheotherifstatementbodycurlybracessothatonlythelastifstatement
intheprogramhasthem.Confirmthateverythingworksasexpected.
Exercise17:Otherwise(IfStatementswithElse)
So,ifstatementsareprettygreat.Almosteveryprogramminglanguagehasthem,andyouusethem
ALLthetime.Infact,ifstatementsalonearefunctionalenoughthatyoucoulddoalotjustusingif
statements.
Butsometimes,havingsomethingelsecouldmakethingsalittlemoreconvenient.Likethisexample:
quick!Whatisthelogicaloppositeofthefollowingexpression?
if(onGuestList||age>=21||(gender.equals("F")&&attractiveness>=8))
Eh?Gotityet?Well,ifyousaid
if(!(onGuestList||age>=21||(gender.equals("F")&&attractiveness>=8)))

thenyourerightandyouremykindofperson.Cleverandknowswhentoletthemachinedothe
workforyou.Ifyousaid
if(!onGuestList&&age<21&&(!gender.equals("F")||attractiveness<8))

thenyourerightandnicejob.Thatsactuallyprettytoughtodocorrectly.Butwhataboutthe
logicaloppositeofthis:
if(expensiveDatabaseThatTakes45SecondsToLookup(userName,password)==true)
Dowereallywanttowrite
if(expensiveDatabaseThatTakes45SecondsToLookup(userName,password)==false)
becausenowwerehavingtowait90secondstodotwoifstatementsinsteadof45seconds.So
fortunately,programminglanguagesgiveussomethingelse.(Yeah,sorry.Couldntresist.)
1importjava.util.Scanner;
2
3publicclassClubBouncer
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9intage=22;
10booleanonGuestList=false;
11doubleattractiveness=7.5;
12Stringgender="F";
13
14if(onGuestList||age>=21||(gender.equals("F")&&
attractiveness>=8))
15{
16System.out.println("Youareallowedtoentertheclub.");
17}
18else
19{
20System.out.println("Youarenotallowedtoentertheclub.");
21}
22}
23}

WhatYouShouldSee
Youareallowedtoentertheclub.
Sowhatthekeywordelsemeansisthis:lookattheprecedingifstatement.Wastheconditionofthat
ifstatementtrue?Ifso,skip.Ifthatpreviousifstatementdidnotrun,however,thenthebodyofthe
elsestatementwillbeexecuted.Ifblahblahblahistrue,thenrunthisblockofcode.Otherwise(else),
runthisdifferentblockofcodeinstead.
Elseissuperconvenientbecausethenwedonthavetofigureoutthelogicaloppositeofsomecomplex
Booleanexpression.Wecanjustsayelseandletthecomputerdealwithit.
Anelseisonlylegalimmediatelyafteranifstatementends.(Technicallyitisonlyallowedafterthe
closingoftheblockofcodethatisthebodyofanifstatement.)

StudyDrills
1. Betweenline17and18,addaprintln()statementtoprintsomethingonthescreen(it
doesntmatterwhat,butIput"CCCCOMBOBREAKER"becauseImweird.)Tryto
compiletheprogram.Doesitcompile?Whynot?
Exercise18:IfStatementswithStrings
AfewexercisesbackyoulearnedhowcomparingStringsisnotaseasyascomparingnumbers.Solets
reviewwithanexampleyoucanactuallytestout.
1importjava.util.Scanner;
2
3publicclassSecretWord
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9Stringsecret="please",guess;
10
11System.out.print("What'sthesecretword?");
12guess=keyboard.next();
13
14if(guess==secret)
15{
16System.out.println("Impossible.(Thiswillneverbeprinted.)");
17}
18
19if(guess.equals(secret))
20{
21System.out.println("That'scorrect!");
22}
23else
24{
25System.out.println("Nope,thesecretwordisnot\""+guess+
"\".");
26}
27
28}
29}

WhatYouShouldSee
What'sthesecretword?abracadabra
Nope,thesecretwordisnot"abracadabra".
NoticethatasusualImsneakingsomethingin.Online9insteadofjustdeclaringsecretIalsogaveita
value.Thatis,Idefinedit(declaredandinitializedallatonce).
Anyway,theifstatementonline14willneverbetrue.Neverever.Nomatterwhatyoutypein,itwill
neverbethecasethatguess==secret.
(Icantreallyexplainwhywithoutgoingintowaytoomuchdetail,butithastodo
withthefactthat==onlycomparestheshallowvaluesofthevariables,andthe
shallowvaluesoftwoStringsareonlyequalwhentheyrefertothesamememory
location.)
Whatdoesworkisusingthe.equals()method(whichcomparesthedeepvaluesofthevariables
insteadoftheirshallowvalues).Thiswillbetrueiftheytypethecorrectsecretword.
Exercise19:MutualExclusionwithChainsofIfandElse
Inthepreviousexercise,wesawhowusingelsecanmakeiteasiertoincludeachunkofalternative
codethatyouwanttorunwhenanifstatementdidnothappen.
Butwhatifthealternativecodeisanotherifstatement?
1importjava.util.Scanner;
2
3publicclassBMICategories
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9doublebmi;
10
11System.out.print("EnteryourBMI:");
12bmi=keyboard.nextDouble();
13
14System.out.print("BMIcategory:");
15if(bmi<15.0)
16{
17System.out.println("veryseverelyunderweight");
18}
19elseif(bmi<=16.0)
20{
21System.out.println("severelyunderweight");
22}
23elseif(bmi<18.5)
24{
25System.out.println("underweight");
26}
27elseif(bmi<25.0)
28{
29System.out.println("normalweight");
30}
31elseif(bmi<30.0)
32{
33System.out.println("overweight");
34}
35elseif(bmi<35.0)
36{
37System.out.println("moderatelyobese");
38}
39elseif(bmi<40.0)
40{
41System.out.println("severelyobese");
42}
43else
44{
45System.out.println("veryseverely/\"morbidly\"obese");
46}
47}
48}

WhatYouShouldSee
EnteryourBMI:22.5
BMIcategory:normalweight
(Note:AlthoughBMIisaverygoodestimateofhumanbodyfat,theformuladoesntworkwellfor
athleteswithalotofmuscle,orpeoplewhoareextremelyshortorverytall.Ifyouareconcernedabout
yourBMI,checkwithyourdoctor.)
Noticethateventhoughseveraloftheifstatementsmighthaveallbeentrue,onlythefirsttrueif
statementprinteditsmessageonthescreen.Noothermessageswereprinted:onlyone.Thatsthepower
ofusingelsewithif.
Online15thereisanifstatementthatchecksifyourBMIislessthan15.0,andifso,displaysthe
propercategoryforthatbodymassindex.
Line19beginswithanelse.Thatelsepaysattentiontotheprecedingifstatementtheoneonline
15todetermineifitshouldrunitsbodyofcodeorskipitautomatically.AssumingyoutypedinaBMI
of22.5,thentheprecedingifstatementwasnottrueanddidnotrun.Becausethatifstatement
failed,theelsewillautomaticallyexecuteitsbodyofcode.
However,thatbodyofcodestartsrightafterthewordelsewithanewifstatement!Thismeansthat
thestatementif(bmi<=16.0)willonlybeconsideredwhenthepreviousifstatementwas
false.
Whenevermystudentsareconfusedaboutthis,IhaveananalogyIgivethem.(Itsalittlecrude,butit
seemstohelp.)
Imaginethatyouaresingle(romantically,Imean)andthatyouandsomeofyourfriendsareoutinabar
orthemallorwhatever.Acrosstheway,youseeareallyattractivesinglepersonandunderyourbreath
youtelltheothers:Okay,dibs.Igetthefirstshot.
Yourgrouptravelsovertothispersonbutnooneelsestartsflirtinguntiltheyseehowyoufare.Ifyou
seemtobemakingprogress,yourfriendswillbackoffandletyouchataway.Ifhowever,youget
rejectedthenoneofyourothercompanionsfeelsclearedtotryandmakeaplay.
Thisisbasicallyexactlywhathappenswithelseif.Anelseifstatement(anifstatementwith
anelseinfrontoftheif)containsaconditionthatmightbetrueormightbefalse.Buttheelse
meansthattheifstatementwillonlychecktoseeifitistrueorfalseassumingtheprecedingif
statement(andonlytheimmediatelyprecedingone)wasfalse.
Theelseonline23makesthatifstatementdefertotheifstatementthatstartsonline19:ifits
true,theline23ifstatementwillskipevenifitwouldhavebeentrueonitsown.Theelseonline27
makesitsifstatementdefertothepreviousifstatement,andsoon.Andtheelseattheveryendon
line43islikethesmallestdoginapack:itonlygetsashotifallthepreviousifstatementsinthechain
werefalse.
Welltalkalittlebitmoreaboutthisinthenextexercise,sothatsenoughfornow.

StudyDrills
1. Removetheelsefrominfrontoftheifstatementonline27.Runtheprogram,andenter
15.5fortheBMI.Doyouseehowthatmakestheifstatementonline27breakrankandno
longercareabouttheifstatementsbeforeit?
2. InsteadofmakingthehumanentertheirBMIdirectly,allowthemtotypeintheirheightand
weightandcomputetheBMIforthem.
Exercise20:MoreChainsofIfsandElse
Okay,letslookalittlemoreatmakingchainsofconditionsusingelseandif.
Aconfession:althoughIdidattendUTAustinIdontthinkthisistheirrealadmissionscriteria.Dont
relyontheoutputofthisprogramwhendecidingwhetherornottoapplytoabackupschool.
1importjava.util.Scanner;
2importstaticjava.lang.System.*;
3
4publicclassCollegeAdmission
5{
6publicstaticvoidmain(String[]args)
7{
8Scannerkeyboard=newScanner(System.in);
9intmath;
10
11out.println("WelcometotheUTAustinCollegeAdmissions
Interface!");
12out.print("PleaseenteryourSATmathscore(200800):");
13math=keyboard.nextInt();
14
15out.print("Admittancestatus:");
16
17if(math>=790)
18out.print("CERTAIN");
19elseif(math>=710)
20out.print("SAFE");
21elseif(math>=580)
22out.print("PROBABLE");
23elseif(math>=500)
24out.print("UNCERTAIN");
25elseif(math>=390)
26out.print("UNLIKELY");
27else//below390
28out.print("DENIED");
29
30out.println();
31}
32}

WhatYouShouldSee
WelcometotheUTAustinCollegeAdmissionsInterface!
PleaseenteryourSATmathscore(200800):730
Admittancestatus:SAFE
Now,beforeIgointothenewthingforthisexercise,IshouldexplainashortcutItookinthisprogram.
Didyounoticetherewasasecondimportstatementatthetop?Ifnot,thenyourcodedidntcompile
oryouthoughtImadeamistakebyputtingout.printlninsteadofSystem.out.println
everywhere.
Well,Idontwanttotalkmuchaboutobjectorientedcodeinthisbook,sincethatsseverelynot
beginnerfriendly,butthinkofitlikethis.ThereisabuiltinobjectinJavacalledSystem.Insidethat
objectthereisanotherobjectnamedout.Thatobjectnamedoutcontainsamethodcalledprint()
andonecalledprintln().
SowhenyouwriteSystem.out.printlnyouareaskingthecomputertorunthemethodcalled
printlninsidetheobjectnamedoutwhichisinsidetheobjectnamedSystem(whichisitselfpart
ofthebuiltinimportlibraryjava.lang.System).
Becauseofthis,Icancreateavariablenamedout,anditwontbeaproblem:
Stringout;
Eventhoughtheresanobjectnamedoutinexistencesomewhere,itsinsidetheSystemobjectsothe
namesdontconflict.
IfIamlazyanddonthaveanydesiretohavemyownvariablenamedout,thenIcanaskthecomputer
toimportallstaticitemswhichareinsidetheclassjava.lang.Systemintothecurrent
namespace:
importstaticjava.lang.System.*;
SonowIcantypejustout.printlninsteadofSystem.out.println.Woo!
InthisexerciseIalsoomittedallthecurlybracesthatdelimittheblocksofcodethatareinthebodiesof
eachifstatement.BecauseIonlywanttheretobeasinglestatementinsidethebodyofeachif
statement,thisisokay.IfIwantedtheretobemorethanonelineofcodethenIwouldhavetoputthe
curlybracesback.
Anyway,inthepreviousexerciseIwroteabouthowputtingelseinfrontofanifstatementmakesit
defertothepreviousifstatement.Whenthepreviousoneistrueandexecutesthecodeinitsbody,the
currentoneskipsautomatically(andalltherestoftheelseifstatementsinthechainwillskip,too).
Thishastheeffectofmakingitsothatonlythefirsttruevaluetriggerstheifstatementandalltherest
dontrun.Wesometimessaythattheifstatementsaremutuallyexclusive:exactlyoneofthemwill
execute.Neverfewerthanone,nevermorethanone.
Todaysexerciseisanotherexampleofthat.ButthistimeIwanttopointoutthatthemutualexclusion
onlyworksproperlybecauseIputtheifstatementsinthecorrectorder.
Sincethefirstonethatistruewillgoandtheotherswillnot,youneedtomakesurethattheveryfirst
ifstatementinthechainistheonewhichishardesttoachieve.Thenthenexthardest,andsoon,with
theeasiestattheend.InthestudydrillsIwillhaveyouchangetheorderoftheifstatements,andyou
willseehowthiscanmessthingsup.
Also,technically,elsestatementsshouldhavecurlybraces,justlikeifstatementsdo,andbyputting
elseifwithnothinginbetweenwearetakingadvantageofthefactthatthebracesareoptional.This
makesthecodealotmorecompact.Hereiswhatthepreviouscodewouldlooklikeifitwerearranged
thewaythecomputerisinterpretingit.Maybeitwillhelpyoutounderstandthedeferbehaviorofthe
elseinfrontofanif;maybeitwilljustconfuseyou.Hopefullyitwillhelp.
1importjava.util.Scanner;
2importstaticjava.lang.System.*;
3
4publicclassCollegeAdmissionExpanded
5{
6publicstaticvoidmain(String[]args)
7{
8Scannerkeyboard=newScanner(System.in);
9intmath;
10
11out.println("WelcometotheUTAustinCollegeAdmissions
Interface!");
12out.print("PleaseenteryourSATmathscore(200800):");
13math=keyboard.nextInt();
14
15out.print("Admittancestatus:");
16
17if(math>=790)
18{
19out.print("CERTAIN");
20}
21else
22{
23if(math>=710)
24{
25out.print("SAFE");
26}
27else
28{
29if(math>=580)
30{
31out.print("PROBABLE");
32}
33else
34{
35if(math>=500)
36{
37out.print("UNCERTAIN");
38}
39else
40{
41if(math>=390)
42{
43out.print("UNLIKELY");
44}
45else//below390
46{
47out.print("DENIED");
48}
49}
50}
51}
52}
53out.println();
54}
55}
Yeah.Soyoucanseewhyweusuallyjustputelseif.

StudyDrills
1. Intheoriginalcodefile(CollegeAdmission.java),removealltheelsesexceptforthe
lastone.Runitandnoticehowitprintsallthemessages.Thenputtheelsesback.
2. Movelines25and26sotheyappearbetweenlines18and19.Compileitandrunitandnotice
howtheprogramalmostalwaysjustsays"UNLIKELY"becausemostSATscoresaremorethan
390andtheifstatementissohighinthelistthatitstealstheshowmostofthetime.
3. Ifyouwant,typeinthecodeforCollegeAdmissionExpanded.javaandconfirmthatit
worksthesameasthenonexpandedversion.
Exercise21:NestedIfStatements
Yousawaglimpseofthisinthepreviousexercise,butyoucanputjustaboutanythingyoulikeinside
thebodyofanifstatementincludingotherifstatements.Thisiscallednesting,andanif
statementwhichisinsideanotheriscalledanestedif.
Heresanexampleofusingthattodosomethinguseful.
1importjava.util.Scanner;
2
3publicclassGenderTitles
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9Stringtitle;
10
11System.out.print("Firstname:");
12Stringfirst=keyboard.next();
13System.out.print("Lastname:");
14Stringlast=keyboard.next();
15System.out.print("Gender(M/F):");
16Stringgender=keyboard.next();
17System.out.print("Age:");
18intage=keyboard.nextInt();
19
20if(age<20)
21{
22title=first;
23}
24else
25{
26if(gender.equals("F"))
27{
28System.out.print("Areyoumarried,"+first+"?(Y/N):");
29Stringmarried=keyboard.next();
30if(married.equals("Y"))
31{
32title="Mrs.";
33}
34else
35{
36title="Ms.";
37}
38}
39else
40{
41title="Mr.";
42}
43}
44
45System.out.println("\n"+title+""+last);
46
47}
48}

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

Mr.Mitchell

YouhaveprobablyfiguredoutthatIliketomixthingsupalittlebittokeepyouonyourtoes.Didyou
noticewhatIdiddifferentlythistime?
NormallyIdeclareallmyvariablesatthetopoftheprogramandgivethemvalues(orinitializethem)
later.Butyoudontactuallyhavetodeclareavariableuntilyourereadytouseit.Sothistime,I
declaredallmyvariables(excepttitle)onthesamelineIputavalueintothemforthefirsttime.
WhydidntIdeclaretitleonline22,then?Becausethenitwouldntbeinscopelater.Scoperefersto
theplacesinyourprogramwhereavariableisvisible.Thegeneralruleisthatavariableisinscopeonce
itisdeclaredandfromthatpointforwardinthecodeuntiltheblockendsthatitwasdeclaredin.Then
thevariablegoesoutofscopeandcantbeusedanymore.
Letuslookatanexample:online29Idefined(declaredandinitialized)aStringvariablecalled
married.Itisdeclaredinsidethebodyofthefemalegenderifstatement.Thisvariableexistsfromline
29downthroughline38attheclosecurlybraceofthatifstatementsbodyblock.Thevariable
marriedisnotinscopeanywhereelseintheprogram;referringtoitonlines1through28oronlines39
through48wouldgiveacompilererror.
ThisiswhyIhadtodeclaretitletowardsthebeginningoftheprogram.IfIhaddeclareditonline22,
thenthevariablewouldhavegoneoutofscopeonelinelater,whentheclosecurlybraceofthe
youngerthan20blockoccurred.BecauseIneedtitletobevisibleallthewaydownthroughline45,I
needtomakesureIdeclareitinsidetheblockofcodethatendsonline47.
Icouldhavewaiteduntilline19todeclareit,though.
Anyway,theresnotmuchelseinterestingtosayaboutthisexerciseexceptthatitdemonstratesnesting
ifstatementsandelsesinsideofothers.Idohavealittlesurpriseinthestudydrills,though.

StudyDrills
1. Changetheelseonline39toasuitableifstatementinstead,like:
if(gender.equals("M"))
Noticethattheprogramdoesntcompileanymore.Canyoufigureoutwhy?
Itisbecausethevariabletitleisdeclaredonline9butisnotgivenavaluerightaway.Thenonline45,
thevalueoftitleisprintedonthescreen.Thevariablemusthaveavalueatthispoint,orwewillbe
tryingtodisplaythevalueofavariablethatisundefined:ithasnovalue.Thecompilerwantstoprevent
this.

Whenline39wasanelse,thecompilercouldguaranteethatnomatterwhatpaththroughthenested
ifstatementswastaken,titlewouldalwaysgetavalue.Oncewechangedittoaregularifstatement,
thereisnowawaythehumancouldtypesomethingtogetittosneakthroughallthenestedif
statementswithoutgivingtitleavalue.Canyouthinkofone?
(Theycouldtypeanage20orgreaterandaletterdifferentthan"M"or"F"whenpromptedforgender.
Thenneithergenderifstatementwouldbetrue.)
Wecanfixthisbychangingtheifstatementbacktoelse(probablyagoodidea)orbyinitializing
titlerightwhenwedeclareit(probablyagoodideaanyway):
Stringtitle="error";
orsomethinglikethat.Nowtitlehasavaluenomatterwhat,andthecompilerishappy.
Exercise22:MakingDecisionswithaBigSwitch
ifstatementsarenttheonlywaytocomparevariableswithvalueinJava.Thereisalsosomething
calledaswitch.Idontusethemveryoften,butyoushouldbefamiliarwiththemanywayincaseyou
readsomeoneelsescodethatusesone.
1importjava.util.Scanner;
2
3publicclassThirtyDays
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9intmonth,days;
10StringmonthName;
11
12System.out.print("Whichmonth?(112)");
13month=keyboard.nextInt();
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
62System.out.println(days+"dayshath"+monthName);
63
64}
65}

WhatYouShouldSee
Whichmonth?(112)4
30dayshathApril
Aswitchstatementstartswiththekeywordswitchandthensomeparentheses.Insidethe
parenthesesisasinglevariable(oranexpressionthatsimplifiestoasinglevalue).Thentheresanopen
curlybrace.
Insidethebodyoftheswitchstatementareseveralcasestatementsthatbeginwiththekeyword
caseandthenavaluethatthevariableupintheparenthesesmightequal.Thentheresacolon(:).You
dontseecolonsveryofteninJava.
Afterthecase,thevalueandthencolonissomecode.Itcanbeasmanylinesofcodeasyoulike
exceptthatyourenotallowedtodeclareanyvariablesinsidetheswitchstatement.Thenafterallthe
codeisthekeywordbreak.Thebreakmarkstheendofthecase.
Whenaswitchstatementruns,thecomputerfiguresoutthecurrentvalueofthevariableinsidethe
parentheses.Thenitlooksthroughthelistofcases,oneatatime,lookingforamatch.Whenitfindsa
matchitmovesfromtheleftsidewherethecasesaretotherightsideandstartsrunningcodeuntilitis
stoppedbyabreak.
Ifnoneofthecasesmatchandthereisadefaultcase(itsoptional),thenthecodeinthedefault
casewillberuninstead.
Thesecondexamplestartsonline50anddemonstratesthatoncetheswitchstatementfindsacasethat
matches,itreallydoesruncodeontherightsideuntilithitsabreakstatement.Itwillevenfallthrough
fromonecasetoanother.
Wecantakeadvantageofthisfallthroughbehaviortodocleverthingssometimes,likethecodeto
figureoutthenumberofdaysinamonth.SinceSeptember,April,JuneandNovemberallhave30days,
wecanjustputalltheircasesinarowandletitfallthroughforanyofthosetorunthesamething.
Anyway,IwontuseswitchstatementsagaininthisbookbecauseIjustvirtuallyneverfindagood
useforthem,butitdoesexistandatleastIcansaythatyousawit.

StudyDrills
1. Removesomeofthebreakstatementsinthefirstswitchandaddsomeprintln()
statementstoconfirmthatitwillsetmonthNametoonevaluethenanotherthenanotheruntilit
finallygetsstoppedbyabreak.
Exercise23:MoreStringComparisons
Well,youhavelearnedthatyoucantcompareStringswith==;youhavetousethe.equals()
method.ButIthinkyourefinallyreadytoseehowwecancompareStringsforalphabeticalordering.
1importjava.util.Scanner;
2
3publicclassDictionaryOrder
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9Stringname;
10
11System.out.print("Givemethenameofamadeupprogramminglanguage:
");
12name=keyboard.nextLine();
13
14if(name.compareTo("c++")<0)
15System.out.println(name+"comesBEFOREc++");
16if(name.compareTo("c++")==0)
17System.out.println("c++isn'tamadeuplanguage!");
18if(name.compareTo("c++")>0)
19System.out.println(name+"comesAFTERc++");
20
21if(name.compareTo("go")<0)
22System.out.println(name+"comesBEFOREgo");
23if(name.compareTo("go")==0)
24System.out.println("goisn'tamadeuplanguage!");
25if(name.compareTo("go")>0)
26System.out.println(name+"comesAFTERgo");
27
28if(name.compareTo("java")<0)
29System.out.println(name+"comesBEFOREjava");
30if(name.compareTo("java")==0)
31System.out.println("javaisn'tamadeuplanguage!");
32if(name.compareTo("java")>0)
33System.out.println(name+"comesAFTERjava");
34
35if(name.compareTo("lisp")<0)
36System.out.println(name+"comesBEFORElisp");
37if(name.compareTo("lisp")==0)
38System.out.println("lispisn'tamadeuplanguage!");
39if(name.compareTo("lisp")>0)
40System.out.println(name+"comesAFTERlisp");
41
42if(name.compareTo("python")<0)
43System.out.println(name+"comesBEFOREpython");
44if(name.compareTo("python")==0)
45System.out.println("pythonisn'tamadeuplanguage!");
46if(name.compareTo("python")>0)
47System.out.println(name+"comesAFTERpython");
48
49if(name.compareTo("ruby")<0)
50System.out.println(name+"comesBEFOREruby");
51if(name.compareTo("ruby")==0)
52System.out.println("rubyisn'tamadeuplanguage!");
53if(name.compareTo("ruby")>0)
54System.out.println(name+"comesAFTERruby");
55
56if(name.compareTo("visualbasic")<0)
57System.out.println(name+"comesBEFOREvisualbasic");
58if(name.compareTo("visualbasic")==0)
59System.out.println("visualbasicisn'tamadeuplanguage!");
60if(name.compareTo("visualbasic")>0)
61System.out.println(name+"comesAFTERvisualbasic");
62}
63}

WhatYouShouldSee
Givemethenameofamadeupprogramminglanguage:juniper
junipercomesAFTERc++
junipercomesAFTERgo
junipercomesAFTERjava
junipercomesBEFORElisp
junipercomesBEFOREpython
junipercomesBEFOREruby
junipercomesBEFOREvisualbasic
(OfcourseIcouldntresistslippinginsomething.Online12insteadofusingtheScannerobjects
.next()methodtoreadinaString,IusedtheScannerobjects.nextLine()methodtoreadina
String.Thedifferenceisthat.next()willstopreadingifyoutypeaspace,soifyoutyped"visual
basic"itwouldonlyreadin"visual"andleavetherestbehind.Whenyouuse.nextLine()it
readsineverythingyoutypeincludingspacesandtabsupuntilyoupressEnterandputsitallinto
onelongStringandstoresitintothevariablename.)
YoucompareStringstoeachotherusingtheStringobjects.compareTo()method.The
.compareTo()methoddoesntworkthewayyouprobablyexpect,butthereisgeniusinhowit
works.
ThecomparisoninvolvestwoStrings.ThefirstStringistheonetotheleftofthe.compareTo().The
secondStringistheoneintheparentheses.Andthecomparisonsimplifiestoaninteger!Ifwecallthe
firstoneselfandthesecondoneotheritwouldlooklikethis:
intn=self.compareTo(other);
Soselfcomparesitselftoother.Ifselfisidenticaltoother(thesamelengthandeverycharacterthe
same),thennwouldbesetto0.Ifselfcomesbeforeotheralphabetically,thennwouldbesettoa
negativenumber(anumberlessthan0).Andifselfcomesafterotheralphabetically,thennwouldbeset
toapositivenumber(anumbergreaterthan0).
Thegeniuspartisthis:because.compareTo()givesusanintegerinsteadofjustaBooleantrueor
false,weonlyneedthisonemethodtodoallthecomparisons:lessthan,greaterthan,lessthanorequal
to,whatever.
Sinceifselfisequaltootherwewouldgetzeroandsinceifselfislessthanotherwewouldgeta
numberlessthanzero,wecanwrite:
if(self.compareTo(other)<=0)
Iftheresultislessthanzerotheifstatementwouldbetrueandiftheresultisequaltozerotheif
statementwouldbetrue.Sothisiskindoflikewriting
if(self<=other)
exceptthatwhatIjustwrotewontactuallycompileandthe.compareTo()trickwill.Prettycool,
ifyouaskme.
if(self.compareTo(other)<0)//truewhenself<other
if(self.compareTo(other)<=0)//truewhenself<=other
if(self.compareTo(other)>0)//truewhenself>other
if(self.compareTo(other)>=0)//truewhenself>=other
if(self.compareTo(other)==0)//truewhenself==other
if(self.compareTo(other)!=0)//truewhenself!=other
Sothatstheidea.Prettyconfusingforbeginners,andslightlyhardertousebutnotbadatallonceyou
getusedtoit.
Theotherdifficultyhere(andthisisnotjusta.compareTo()thing,ithappenseverywhereincode
unlessyouwritecodetofixit)isthatcapitalizationmatters."Bob"isnotthesamevalueas"bob".
AndwhatsworseisthatbecauseoftheUnicodevalues7oftheletters,"Bob"comesbefore"bob"
alphabetically.Ifyouwanttoavoidthisissue,therearealotofways,butIlikeoneofthesetwo:
if(self.toLowerCase().compareTo(other.toLowerCase())<0)//or
if(self.compareToIgnoreCase(other)<0)
Oryoucanletthehumantypeinwhatevertheywantandconvertittolowercaserightawayandthen
onlycompareittolowercasethingsinyourcode.

StudyDrills
1. Usingthemethodofyourchoice,makethisprogramworkcorrectlyevenifthehumantypesin
wordswiththewrongcapitalization.

7 Computersonlyworkwithnumbersinternally.Lettersarenotnumbers,butthereisabiggianttablethatmapsevery
characterineverylanguageevertooneof1,112,063numbersthatuniquelyidentifiesthatcharacter.TheUTF8Unicode
valueoftheletter"B"is66;thevalueoftheletter"b"is98.
Exercise24:ChoosingNumbersRandomly
Weregoingtospendafewexercisesonsomethingyoudontalwaysseeinprogrammingbooks:howto
havethecomputerchoosearandomnumberwithinacertainrange.Thisisbecauseyoucanwritealot
ofsoftwarewithoutneedingthecomputertorandomlypickanumber.However,havingrandom
numberswillletusmakesomesimpleinteractivegames,andthatiseasilyworththepainofthisslightly
weirdconcept.
1publicclassRandomNumbers
2{
3publicstaticvoidmain(String[]args)
4{
5inta,b,c;
6doublex,y,z;
7
8x=Math.random();
9y=Math.random();
10z=Math.random();
11
12System.out.println("xis"+x);
13System.out.println("yis"+y);
14System.out.println("zis"+z);
15
16x=Math.random()*100;
17y=Math.random()*100;
18z=Math.random()*100;
19
20System.out.println("\nxis"+x);
21System.out.println("yis"+y);
22System.out.println("zis"+z);
23
24a=(int)x;
25b=(int)y;
26c=(int)z;
27
28System.out.println("\nais"+a);
29System.out.println("bis"+b);
30System.out.println("cis"+c);
31
32x=0.9999999999999999;
33a=(int)(x*100);
34
35System.out.println("\nxis"+x);
36System.out.println("ais"+a);
37
38x=Math.random();
39a=0+(int)(x*10);
40b=1+(int)(x*10);
41c=5+(int)(x*10);
42
43System.out.println("\nais"+a);
44System.out.println("bis"+b);
45System.out.println("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:Youroutputwontlookthesameasmine.Thenumbersarerandom,remember?
JavahasabuiltinfunctioncalledMath.random().Everytimeyoucallthefunction,itwillproducea
newrandomdoubleintherange[0,1)(thatis,itmightbeexactly0butwillneverbeexactly1and
willmostlikelybesomethinginbetween.SoifIwrite:
doublex=Math.random();
thenxcouldhaveavalueof0,or0.123544,or0.3,or0.999999999butnever1.0andnever
greaterthan1.Soonlines8through10thefunctionMath.random()iscalledthreetimes,andthe
resultisstoredintothreedifferentvariables.Thesethreevaluesareprintedsoyoucanseewhattheyare.
Unfortunately,Idontoftenwantadoublefrom[0,1).Imagineanumberguessinggamewhereyousay
Iamthinkingofanumberwithdecimalsbetweenzeroandone:trytoguessit!Nofun.Andwecant
controltherangeofthevaluethatMath.random()givesus,sowehavetomushitintoarange
ourselves.
Onlines16through18wepickanewrandomnumber,butwemultiplyitby100beforestoringitintoa
variable.(Thishastheeffectofmovingthedecimaltwoplacevaluestotheright.)Sowecantellthatthe
originalrandomnumberprintedoutonline20was0.5733269918363617becauseitis
57.33269918363617afterbeingmultipliedby100.
Notethatmultiplyingby100stillgivesusaslightchanceofgettingexactly0.Iftheoriginalrandom
numberis0thenmultiplyingitdoesntchangethat.Thenumberswestoreintothevariablescouldbe
somethinglike12.3544,or30.0,or99.9999999butnever100.0andneveranythinggreater
than100.
Onlines24through26weperformwhatiscalledatypecastorjustacast.Thevariablexisa
double:itcanholdnumberswithdecimals.Thevariableaisaninteger:itcanholdwholenumbersonly.
Normallyyourenotallowedtostorethevaluefromadoubleintoanint.AcasttellsthecompilerI
knowthatxisadoubleandthatImtryingtostoreitsvalueintoanintwhichcantholddecimals.But
Idontcare.Whydontyoujustpretendthatthevalueinxisaninteger?Itisokayifyouhavetothrow
awayeverythingafterthedecimalpoint.Justdoit.
Soonline24thecomputermakesacopyofthevaluefromxbuteverythingafterthedecimalpointis
choppedoffandthrownaway(truncated)andthatnewintegervalueisstoredintothevariablea.(The
valueofxisunchanged.)Thevalueisnotrounded;itstruncated.
Theoreticallywhatdoesthisgiveus?Ifxwasoriginally0or12.3544or30.0,or99.9999999,
thenawillbe0or12or30or99butnever100oranythingbiggerthan100.Soa,bandcwillalways
haveintegervaluesfrom0to99.
Onlines32and33Ihaveattemptedtoshowthatcastingfromadoubletoanintegerdoesnotround;the
numbersafterthedecimalpointaretruncated.
Finally,onlines38through41asinglerandomnumberischosen.Inallthreecasesitismultipliedby10
andthencasttoaninteger.Thismeansthatafterthecastwealwayshaveanumberfrom0to9.
Butonline39thatrandomnumberfrom0to9gets0addedtoitbeforestoringitintoa.(Adding0
doesntchangethenumber.)Soawillalwayshaveavaluefrom09.
Online40therandomnumberfrom0to9gets1addedtoitbeforestoringitintob.Thismakes
whateveritisbiggerby1.Ifithadbeena0,itwillnowbea1.Ifithadbeena6,itwillnowbea7.Ifit
hadbeena9(themaximum),itwillnowbea10.Sobwillalwayshaveavaluefrom110.
Online41therandomnumberfrom09gets5addedtoitbeforestoringitintoc.Socwillalwayshave
avaluefrom5to14.(Thisisstilltenvalues.)
Okay,thatsenoughfortoday.

StudyDrills
1. Removethecastfromline24.Trytocompiletheprogram.Whaterrormessagedoyouget?
(Thenputitback.)
2.Runtheprogramseveraltimesandconfirmthata,bandcasprintedoutonlines28through30
alwayshavevaluesfrom0to99.
1. UseyourfingerstocountandconfirmthatifIhaveanumberfrom0to9,therearetenpossible
numbersIcouldhave.Multiplyingarandomnumberbytenandtruncatinggivesyouten
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)(Math.random()*10);
8b=1+(int)(Math.random()*10);
9c=1+(int)(Math.random()*10);
10d=1+(int)(Math.random()*10);
11e=1+(int)(Math.random()*10);
12
13System.out.println(a+"\t"+b+"\t"+c+"\t"+d+"\t"+e);
14
15a=1+(int)(Math.random()*100);
16b=1+(int)(Math.random()*100);
17c=1+(int)(Math.random()*100);
18d=1+(int)(Math.random()*100);
19e=1+(int)(Math.random()*100);
20
21System.out.println(a+"\t"+b+"\t"+c+"\t"+d+"\t"+e);
22
23a=70+(int)(Math.random()*31);//31is10070+1
24b=70+(int)(Math.random()*31);
25c=70+(int)(Math.random()*31);
26d=70+(int)(Math.random()*31);
27e=70+(int)(Math.random()*31);
28
29System.out.println(a+"\t"+b+"\t"+c+"\t"+d+"\t"+e);
30
31low=70;
32high=100;
33
34a=low+(int)(Math.random()*(highlow+1));
35b=low+(int)(Math.random()*(highlow+1));
36c=low+(int)(Math.random()*(highlow+1));
37d=low+(int)(Math.random()*(highlow+1));
38e=low+(int)(Math.random()*(highlow+1));
39
40System.out.println(a+"\t"+b+"\t"+c+"\t"+d+"\t"+e);
41}
42}

WhatYouShouldSee
79333
1053781775
7696998586
9991969983
(Again,youwontseethis.Thenumberswillberandom.)
Onlines7through11wechoosefiverandomnumbers.Eachnumberismultipliedbytenandcasttoan
integertotruncateit(soeachrandomnumberisoneoftennumbers:0through9).Then1isaddedto
each,sothevariablesathrougheeachgetarandomnumberfrom1to10.
Onlines15through19wechoosefiverandomnumbersagain.Eachnumberismultipliedbyone
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)(Math.random()*range);

lowisthesmallestpossiblenumberwewant.rangeishowmanyrandomnumbersshouldbeinthe
range.Ifyouknowyourlowestpossiblenumberandyourhighestpossiblenumberbutnothowmany
numbersthatis,theformulais:
intrange=highlow+1;
IfthelowestrandomnumberIwantis1andthehighestrandomnumberis5,thentherangeisfive.5
minus1is4,thenaddonetoaccountforthefactthatsubtractinggivesyouthedistancebetweentwo
numbers,notthecountofstoppingpointsalongtheway.8
Youcouldevenwritetheformulalikethis:
inta=low+(int)(Math.random()*(highlow+1));
Thiswillhavethecomputerpickarandomnumberfromlowtohigh.Andthisisexactlywhatwedoon
lines34through38.

StudyDrills
1. Changethevaluesoflowandhighonlines31and32tosomethingelse.Compileitandrunthe
programmanytimestoconfirmthatyoualwaysgetrandomnumbersinthatrange.

8 Thereisacommonlogicalerrorinprogrammingthatcanoccurifyouaccidentallycountdistanceinsteadofstops;itis
calledthefencepostproblem.Thenamecomesfromthefollowingbrainteaser:ifIneedtobuildafencefivemeters
longusingabunchofwoodenboardsthatareslightlylongerthanonemetereach,howmanyfencepostswillIneed?You
needfiveboardsbutsixfenceposts.
Exercise26:RepeatingYourselfwiththeWhileLoop
Thisisoneofmyfavoriteexercises,becauseyouaregoingtolearnhowtomakechunksofcoderepeat.
Andifyoucandothat,youwillbeabletowriteallsortsofinterestingthings.
1importjava.util.Scanner;
2
3publicclassEnterPIN
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8intpin,entry;
9
10pin=12345;
11
12System.out.println("WELCOMETOTHEBANKOFJAVA.");
13System.out.print("ENTERYOURPIN:");
14entry=keyboard.nextInt();
15
16while(entry!=pin)
17{
18System.out.println("\nINCORRECTPIN.TRYAGAIN.");
19System.out.print("ENTERYOURPIN:");
20entry=keyboard.nextInt();
21}
22
23System.out.println("\nPINACCEPTED.YOUNOWHAVEACCESSTOYOUR
ACCOUNT.");
24}
25}

WhatYouShouldSee
WELCOMETOTHEBANKOFJAVA.
ENTERYOURPIN:123

INCORRECTPIN.TRYAGAIN.
ENTERYOURPIN:1234

INCORRECTPIN.TRYAGAIN.
ENTERYOURPIN:12345

PINACCEPTED.YOUNOWHAVEACCESSTOYOURACCOUNT.
Online16yougetyourfirstlookatthewhileloop.Awhileloopissimilartoanifstatement.They
bothhaveaconditioninparenthesesthatischeckedtoseeifittrueorfalse.Iftheconditionisfalse,
bothwhileloopsandifstatementswillskipallthecodeinthebody.Andwhentheconditionistrue,
bothwhileloopsandifstatementwillexecuteallofthecodeinsidetheirbodyonetime.
Theonlydifferenceisthatifstatementsthataretruewillexecuteallofthecodeinthecurlybraces
exactlyonce.whileloopsthataretruewillexecuteallofthecodeinthecurlybracesonceandthengo
backupandchecktheconditionagain.Iftheconditionisstilltrue,thecodeinthebodywillallbe
executedagain.Thenitcheckstheconditionagainandrunsthebodyagainiftheconditionisstilltrue.
Infact,youcouldsaythatthewhileloopexecutesallofthecodeinitsbodyoverandoveragainas
longasitsconditionistruewhenchecked.
Eventually,theconditionwillbefalsewhenitischecked.Thenthewhileloopwillskipoverallthe
codeinitsbodyandtherestoftheprogramwillcontinue.Oncetheconditionofawhileloopisfalse,
itdoesntgetcheckedagain.
Loopingissogreatbecausewecanfinallydosomethingmorethanoncewithouthavingtotypethecode
foritmorethanonce!Infact,programmerssometimessayKeepyourcodeD.R.Y:DontRepeat
Yourself.Onceyouknowhowtoprogramprettywellandfinishalloftheexercisesinthisbook,you
willstarttogetsuspiciousifyoufindyourselftyping(orcopyingandpasting)theexactsamecode
morethanonceinaprogram.
Exercise27:ANumberGuessingGame
Nowthatyouknowhowtorepeatsomethingusingawhileloopwearegoingtowriteaprogramthat
anotherhumanmightactuallyenjoyrunning?AreyouasexcitedasIamaboutthis?
1importjava.util.Scanner;
2
3publicclassHighLow
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8intsecret,guess;
9
10secret=1+(int)(Math.random()*100);
11
12System.out.println("I'mthinkingofanumberbetween1100.Tryto
guessit.");
13System.out.print(">");
14guess=keyboard.nextInt();
15
16while(secret!=guess)
17{
18if(guess<secret)
19{
20System.out.println("Sorry,yourguessistoolow.Tryagain."
);
21}
22if(guess>secret)
23{
24System.out.println("Sorry,yourguessistoohigh.Try
again.");
25}
26System.out.print(">");
27guess=keyboard.nextInt();
28}
29
30System.out.println("Youguessedit!Whataretheodds?!?");
31}
32}

WhatYouShouldSee
I'mthinkingofanumberbetween1100.Trytoguessit.
>50
Sorry,yourguessistoohigh.Tryagain.
>25
Sorry,yourguessistoohigh.Tryagain.
>13
Sorry,yourguessistoolow.Tryagain.
>20
Sorry,yourguessistoohigh.Tryagain.
>16
Sorry,yourguessistoohigh.Tryagain.
>18
Sorry,yourguessistoohigh.Tryagain.
>14
Sorry,yourguessistoolow.Tryagain.
>15
Youguessedit!Whataretheodds?!?
Soonline10thecomputerchoosesarandomnumberfrom1to100andstoresitintothevariablesecret.
Weletthehumanmakeaguess.
Line16hasawhileloop.ItsaysAslongasthevalueofthevariablesecretisnotthesameasthe
valueofthevariableguessrunthefollowingchunkofcode.Lines17through28arethebodyofthe
loop.Everytimetheconditionistrue,alltwelveoftheselinesofcodegetexecuted.
Insidethebodyoftheloopwehaveacoupleofifstatements.Wealreadyknowthatthehumansguess
isdifferentfromthesecretnumberorwewouldntbeinsidethewhilelooptobeginwith!Butwe
dontknowiftheguessiswrongbecauseitistooloworbecauseitistoohigh,sotheseifstatements
figurethatoutanddisplaytheappropriateerrormessage.
Thenaftertheerrormessageisdisplayed,online27weallowthemtoguessagain.Thehuman
(hopefully)typesinanumberwhichisthenstoredintothevariableguess,overwritingtheirprevious
guessinthatvariable.
Thentheprogramloopsbackuptoline16andcheckstheconditionagain.Iftheconditionisstilltrue
(theirguessisstillnotequaltothesecretnumber)thenthewholeloopbodywillexecuteagain.Ifthe
conditionisnowfalse(theyguessedit)thenthewholeloopbodywillbeskippedandtheprogramwill
skipdowntoline29.
Iftheloopisover,weknowtheconditionisfalse.Sowedontneedanewifstatementdownhere;itis
safetoprintyouguessedit.
Exercise28:InfiniteLoops
Onethingwhichsometimessurprisesstudentsishoweasyitistomakealoopthatrepeatsforever.
Thesearecalledinfiniteloopsandwesometimesmakethemonpurpose9butusuallytheyarethe
resultofalogicalerror.Heresanexample:
1importjava.util.Scanner;
2
3publicclassKeepGuessing
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8intsecret,guess;
9
10secret=1+(int)(Math.random()*10);
11
12System.out.println("Ihavechosenanumberbetween1and10.Tryto
guessit.");
13System.out.print("Yourguess:");
14guess=keyboard.nextInt();
15
16while(secret!=guess)
17{
18System.out.println("Thatisincorrect.Guessagain.");
19System.out.print("Yourguess:");
20}
21
22System.out.println("That'sright!You'reagoodguesser.");
23}
24}

WhatYouShouldSee
Ihavechosenanumberbetween1and10.Trytoguessit.
Yourguess:4
Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.

9 Forexample,incollegeoneofmyassignmentsinmyNetworkProtocolsclasswastowriteawebserver.Webservers
listentothenetworkforapagerequest.Thentheyfindtherequestedpageandsenditoverthenetworktotherequesting
webbrowser.Andthentheywaitforanotherrequest.Iusedaninfinitelooponpurposeinthatassignmentbecausethe
webserversoftwarewasintendedtostartautomaticallywhenthemachinebooted,runthewholetime,andonlyshut
downwhenthemachinedid.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:Thatisincorrect.Guessagain.
Yourguess:^C
Theprogramactuallydidntstoponitsown;IhadtostopitbypressingCTRLCwhiletheprogram
wasrepeatingandrepeating.
Thiscodehasaninfiniteloopinit.Line16checkstoseeifthevalueofthevariablesecretisdifferent
thanthevalueofthevariableguess.Ifso,itexecutesthebodyoftheloopandifnotitskipsoverthe
loopbodydowntoline21.
Theproblemisthatoncesecretandguessaredifferenttheprogramcanneverreachanotherlineofcode
thatchangeseithervariable,sothelooprepeatslines16through20forever.
Sowhenyouarewritingtheconditionofawhileloop,trytokeepinthebackofyourmind:Ineedto
makesuretheresawayforthisconditiontoeventuallybecomefalse.

StudyDrills
1. Fixthecodesothatitnolongermakesaninfiniteloop.
Exercise29:UsingLoopsforErrorChecking
Sofarinthisbookwehavemostlybeenignoringerrorchecking.Wehaveassumedthatthehumanwill
followdirections,andiftheirlackofdirectionfollowingbreaksourprogram,wejustblametheuserand
dontworryaboutit.
Thisistotallyfinewhenyouarejustlearning.Errorcheckingishard,whichiswhymostbigprograms
havebugsandittakesawholearmyofpeopleworkingreallyhardtomakesurethatsoftwarehasasfew
bugsaspossible.
Butyouarefinallytothepointwhereyoucancodealittlebitoferrorchecking.
1importjava.util.Scanner;
2
3publicclassSafeSquareRoot
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8doublex,y;
9
10System.out.print("Givemeanumber,andIshallfindthesquareroot
ofit.");
11System.out.print("(Nonegatives,please.)");
12x=keyboard.nextDouble();
13
14while(x<0)
15{
16System.out.print("Sorry,Iwon'ttakethesquarerootofa
negative.\nNewnumber:");
17x=keyboard.nextDouble();
18}
19
20y=Math.sqrt(x);
21
22System.out.println("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
couldjustusethebuiltinabsolutevaluefunctionMath.abs(),butImtryingtodemonstrate
errorchecking,okay?
Online12weletthehumantypeinanumber.Wehaveaskedthemnicelytoonlytypeinapositive
number,buttheycantypewhatevertheylike.(TheycouldeventypeMisterMxyzptlk,butour
errorcheckingskillarentadvancedenoughtosurvivethat,yet.)
Soonline14wechecktoseeiftheyfolloweddirections.Ifthevalueinxisnegative(lessthanzero)we
printoutanerrormessageandletthemtryagain.THEN,aftertheyhavetypedtheirnewnumberwego
backuptoline14andcheckiftheconditionisstilltrue.Aretheystillfailingtofollowdirections?Ifso,
displaytheerrormessageagainandgivethemanotherchance.
Computersdontgetimpatientorbored,sothehumanistrappedinthisloopuntiltheycomply.They
couldtypenegativenumberstwobilliontimesandeachtimethecomputerwouldpolitelycomplainand
makethemtypesomethingagain.
Eventually,thehumanwillwiseupandtypeanonnegativenumber.Thentheconditionofthewhile
loopwillbefalse(finally)andthebodyoftheloopwillbeskipped(finally)andexecutionwillpickup
online20wherewecansafelytakethesquarerootofanumberthatweknowispositive.
Realprogramshavestufflikethisallover.Youhavetodoitbecausehumansareunreliableandoften
dounexpectedthings.Whathappenswhenyourtoddlerpullshimselfuptoyourlaptopandstarts
mashingkeyswhileaprogramisrunning?Wewouldliketheprogramtonotcrash.
Oh,anddidyounotice?Ichangedupsomethinginthisprogram.SofareverytimeinthisbookIhave
printedsomethingonthescreen,Ihaveputablankspacebetweentheparenthesesandthequotation
marks,likeso:
System.out.println("Thisisatest.");
IdidthatbecauseIwantedtomakeitclearthatthethinginsidethequotes(technicallyaStringliteral)
wasonething,andtheparentheseswereanother.ButJavadoesntactuallycareaboutthosespaces.
(RememberthatIamfulloflies.)Yourprogramwillstillcompileandworkexactlythesameifyou
leavethespacesout:
System.out.println("Thisisatest.");
Youmighthavenoticedthatonline22IevenleftoutthespacesbetweentheStringliteralsandtheplus
signs.SpacinglikethisdoesntaffectthesyntaxofaJavaprogram,althoughmanycompaniesandother
softwarewritinggroupshavestyleguidelinesthattellyouwhattheRightWaytoformatyourcodeis
ifyouwanttomakeothermembersofthegrouphappy.
Somepeoplegetveryworkedupaboutthis.Theythinkyoushouldalwaysusespacestoindentyour
code,oralwaysputtheopenbraceofacodeblockattheendofthepreviousline:
if(age<16){
allowed=false;
}
likethat.Ithinkforyourowncode,youshouldgiveotherstylesatryanddowhatmakesyouhappy.
Andwhenyoureworkingwithothers,youshouldformatthecodeinawaythatmakesthemhappy.
Thereareeventoolsthatcanchangetheformatofyourcodeautomaticallytofitacertainstyle!(Search
forsourcecodebeautifierorJavaprettyprintertoseesomeexamples.)

StudyDrills
1. InsteadofaninputprotectionloopuseanifstatementandMath.abs()tohandletakingthe
squarerootofnegativenumbers,too.Detectwhenthenumberisnegative,takethesquarerootof
thepositiveversion,andprintalittle"i"nexttotheanswer.
Exercise30:DoWhileloops
InthisexerciseIamgoingtodosomethingInormallydontdo.Iamgoingtoshowyouanotherwayto
makeloopsinJava.Sinceyouhaveonlybeenlookingatwhileloopforfourexercises,showingyoua
differenttypeofloopcanbeconfusing.UsuallyIliketowaituntilstudentshavebeendoingsomething
alongtimebeforeIshowthemanewwaytodothesamething.
Soifyouthinkyouaregoingtobeconfused,feelfreetoskipthisexercise.Itwonthurtyouhardlyat
all,andyoucancomebacktoitwhenyourefeelingmoreconfident.
Anyway,thereareseveralwaystomakealoopinJava.Inadditiontothewhileloop,thereisalsoa
dowhileloop.Theyarevirtuallyidenticalbecausetheybothcheckaconditioninparentheses.Ifthe
conditionistrue,thebodyoftheloopisexecuted.Iftheconditionisfalse,thebodyoftheloopis
skipped(ortheloopingstops).
Sowhatsthedifference?Typeinthecodeandthenwelltalkaboutit.
1importjava.util.Scanner;
2
3publicclassCoinFlip
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9Stringcoin,again;
10intflip,streak=0;
11
12do
13{
14flip=1+(int)(Math.random()*2);
15
16if(flip==1)
17coin="HEADS";
18else
19coin="TAILS";
20
21System.out.println("Youflipacoinanditis..."+coin);
22
23if(flip==1)
24{
25streak++;
26System.out.println("\tThat's"+streak+"inarow....");
27System.out.print("\tWouldyouliketoflipagain(y/n)?");
28again=keyboard.next();
29}
30else
31{
32streak=0;
33again="n";
34}
35}while(again.equals("y"));
36
37System.out.println("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
loopandequivalentcodeusingadowhileloopswillbehaveexactlythesame.Anythingyoucando
withawhileloopyoucoulddowithadowhileloop(andslightlydifferentcode)andviceversa.
SowhywouldthedevelopersofJavabothertomakeadowhileloop?Becausesometimeswhatyoure
checkingintheconditionissomethingyoudontreallyknowuntilyouhavegonethroughthebodyof
theloopatleastonce.
Inthiscase,weareflippingacoinbypickingarandomnumberbetween12andusinganifstatement.
Thenweaskthemiftheywanttoflipagainorstop.Theconditionofourlooprepeatsiftheysaythey
wanttoflipagain.
Ifwehaddonethiswithawhileloop,theconditionwouldlooklikethis:
while(again.equals("y"))
{
Thisisfine,andwouldwork,butthevariableagaindoesntgetavalueuntilline28.Andsoourcode
wouldntcompilebecauseagain(inthewordsoftheJavacompiler)mightnothavebeeninitialized.
Andsowewouldhavetogiveitavalueupbeforetheloopthatdoesntmeananythingandisonlythere
topleasethecompiler.
Thatisannoying,sothedowhileloopallowsustoleaveourconditionthesamebutwaituntiltheendto
checkit.Thisishandy.

StudyDrills
1. Changethecodesothatitusesawhileloopinsteadofadowhileloop.Makesureitcompiles
andworksthesame.
2. Changeitbacktoadowhileloop.(Youmightlookbackatthiscodelaterwhenyouforgethow
towriteadowhileloopandwedontwantyouronlyexampletohavebeenchangedtoawhile
loop.)
Exercise31:AddingValuesOneataTime
Thisexercisewilldemonstratesomethingthatyouhavetodoalot:dealingwithvaluesthatyouonlyget
oneatatime.
IfIaskedyoutoletthehumantypeinthreenumbersandaddthemup,andifIpromisedtheywould
onlyneedtotypeinexactlythreenumbers(nevermore,neverfewer),youwouldprobablywrite
somethinglikethis:
inta,b,c,total;
a=keyboard.nextInt();
b=keyboard.nextInt();
c=keyboard.nextInt();
total=a+b+c;
IfItoldyouthehumanwasgoingtotypeinfivenumbers,yourcodemightlooklikethis:
doublenum1,num2,num3,num4,num5,total;
num1=keyboard.nextDouble();
num2=keyboard.nextDouble();
num3=keyboard.nextDouble();
num4=keyboard.nextDouble();
num5=keyboard.nextDouble();
total=num1+num2+num3+num4+num5;
ButwhatifItoldyoutheywantedtotypeinonehundrednumbers?Ortenthousand?Ormaybethree
andmaybefive,Imnotsure?Thenyouneedadifferentapproach.Youllneedaloop(thatshowwe
repeatthings,afterall).Andyouneedavariablethatwilladdthevaluesoneatatimeastheycome.A
variablethatstartswithnothinginitandaddsvaluesoneatatimeiscalledanaccumulatorvariable,
althoughthatsaprettyoldwordandsoyourfriendswhocodemayneverhavehearditiftheyreunder
theageofforty.
Anyway,thebasicidealookslikethis:
1importjava.util.Scanner;
2
3publicclassRunningTotal
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9intcurrent,total=0;
10
11System.out.print("TypeinabunchofvaluesandI'lladdthemup.");
12System.out.println("I'llstopwhenyoutypeazero.");
13
14do
15{
16System.out.print("Value:");
17current=keyboard.nextInt();
18intnewtotal=current+total;
19total=newtotal;
20System.out.println("Thetotalsofaris:"+total);
21}while(current!=0);
22
23System.out.println("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,wemakesuretostartbyputtingazerointototal.Youllseewhysoon.
Online17thehumangetstotypeinanumber.Thisisinsidethebodyofadowhileloop,whichrunsat
leastoncenomatterwhat,sothiscodealwayshappens.Letspretendtheytype3atfirst.
Online18thefirsthalfofthemagichappens.Wedeclareanewvariablecallednewtotalandsetits
valueequaltothenumberthehumanjusttypedpluswhatevervalueisalreadyinthevariabletotal.
Theresazerointotalatfirst,sothislineofcodeaddszerotocurrentandstoresthatnumberinto
newtotal.
Thenonline19thesecondhalfofthemagichappens:wereplacethevalueintotal(thezero)withthe
currentvalueofnewtotal.Sonowtotalnolongerhasazeroinit;ithasthesamevaluecurrentdid.So
totalwas0,nowitis3.
Thenweprintthesubtotalandonline21checktoseeifcurrentwaszero.Ifnot,thelooprepeatsback
upline14.
Thehumangetstotypeinasecondnumber.Letssayitisa4.Thevariablenewtotalgetsinitializedto
current(4)plustotal(3),sonewtotalis7.Thenonline19wechangetotalsvalueto7.
Theconditionischeckedagain,andtheprocesscontinues.Eventuallythehumantypesa0,that0gets
addedtothetotal(whichdoesnthurtit)andtheconditionisfalsesothedowhileloopstopslooping.
Ishouldmentiontwothingsbeforetheexerciseends:
1.Becausethevariablenewtotalisdeclared(anddefined)online18,thescopeofthatvariableislimited
tothebodyofthedowhileloop.Thatmeansonline21,newtotalisnolongerinscope,soanyattempt
toreferencenewtotalintheconditionofthedowhileloopwouldgiveanerror.Thevariablekeeps
gettingcreatedanddestroyedeachtimethroughtheloop.Thisissortofinefficient.
2.Wecouldhavecodedthiswithoutevenusinganewtotalvariable.SinceJavafiguresoutthefinal
valueoftherighthandsidebeforestoringitintothevariablenamedonthelefthandside,wecould
havecombinedlines18and19intoasingleline:
total=current+total;

Thisworkstotallyfine.(Infact,youhaveseenitbefore.)

StudyDrills
1. Rewritethecodetouseawhileloopinsteadofadowhileloop.Getittocompileandmake
sureitstillworks.Thenchangeitback.
2. Changetheconditionofthedowhileloopsothattheloopstopswhennewtotalisexactly20.
Oh?Itdoesntcompilebecausenewtotalisoutofscope?Changewherenewtotalisdeclaredso
thatthisworks.
Exercise32:AddingValuesforaDiceGame
Pigisasimpledicegamefortwoormoreplayers.(YoucanreadtheWikipediaentryforPigifyou
wantalotmoreinformation.)Thebasicideaistobethefirstonetobankascoreof100points.When
yourolla1,yourturnendsandyougainnopointsthatturn.Anyotherrolladdstoyourscoreforthat
turn,butyouonlykeepthosepointsifyoudecidetohold.Ifyourolla1beforeyouhold,allyour
pointsforthatturnarelost.
YouknowenoughtohandlethecodefortheentiregameofPig,butitisalotatoncecomparedtothe
smallerprogramsyouhavebeenseeing,soIamgoingtobreakitintotwolessons.Todaywewillwrite
onlytheartificialintelligence(A.I.)codeforacomputerplayer.Thiscomputerplayerwillutilizethe
holdat20strategy,whichmeansthecomputerkeepsrollinguntiltheirscorefortheturnaddsupto20
ormore,andthenholdsnomatterwhat.Thisisactuallynotaterriblestrategy,anditiseasyenoughto
code.
1importjava.util.Scanner;
2
3publicclassPigDiceComputer
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9introll,total;
10
11total=0;
12
13do
14{
15roll=1+(int)(Math.random()*6);
16System.out.println("Computerrolleda"+roll+".");
17if(roll==1)
18{
19System.out.println("\tThatendsitsturn.");
20total=0;
21}
22else
23{
24total+=roll;
25System.out.println("\tComputerhas"+total+"pointssofarthis
round.");
26if(total<20)
27{
28System.out.println("\tComputerchoosestorollagain.");
29}
30}
31}while(roll!=1&&total<20);
32
33System.out.println("Computerendstheroundwith"+total+"points.");
34
35}
36}

WhatYouShouldSee
Computerrolleda2.
Computerhas2pointssofarthisround.
Computerchoosestorollagain.
Computerrolleda3.
Computerhas5pointssofarthisround.
Computerchoosestorollagain.
Computerrolleda1.
Thatendsitsturn.
Computerendstheroundwith0points.
Basicallythewholeprogramisinthebodyonebigdowhileloopthattellsthecomputerwhentostop:
eitheritrollsa1oritgetsatotalof20ormore.Aslongastherollisnotoneandthetotalislessthan
20,theconditionwillbetrueandtheloopwillstartoverfromthebeginning(online13).Andwe
chooseadowhileloopbecausewewantthecomputertorollatleastoncenomatterwhat.
Therollismadeonline15:arandomnumberfrom16isagoodsubstituteforrollingadice.
Online17wecheckforrollinga1.Ifso,allpointsarelost.Ifnot(else),weaddthisrolltothe
runningtotal.Noticeweusedplusequals,whichwehaveseenbefore.
Theifstatementonline26isjustsowecangetanicemessagethatthecomputerisgoingtorollagain.
Notterrible,right?Socomebacknextlessonforthefullgame!

StudyDrills
1. Findadice(technicallyitshouldbedie,sincediceispluralandyouonlyneedone)orfind
anapporwebsitetosimulaterollingadie.Getoutasheetofpaperandsomethingtowritewith.
Drawalinedownthemiddleofthepaperandmaketwocolumns.Labeltheleftcolumnroll
andtherightcolumntotal.Puta0inthetotalcolumnandleavetheothercolumnblankat
first.
Thenrollthedieandwritedownthenumberyourolledatthetopoftherollcolumn.Putthe
number(15)inparenthesesnexttotherollvalue,sincethedierolloccursonline15inthe
code.
Thenstepthroughthecodelinebylinejustlikethecomputerwould.Comparethecurrentvalue
ofrollwith1.Iftheyareequal,crossoutthecurrentvalueinthetotalcolumnandput0(20)
there,sincetotalwouldbecomezeroonline20ofthecode.
Keepgoinguntiltheprogramwouldend.Heresanexampleofwhatmytablewouldlooklike
forthesamplerunoftheprogramshownintheWhatYouShouldSeesection.
roll total
0(11)
2(15)
2(24)
3(15)
5(24)
1(15)
0(20)
Exercise33:TheDiceGameCalledPig
InthepreviouslessonwewrotethecomputerA.I.forthedicegamePig.(Rememberthatyoucanread
theWikipediaentryforPigifyouwantalotmoreinformationaboutthisgame.)Inthislessonwewill
havethecodefortheentiregame,withonehumanplayerandonecomputerplayerthattaketurns.
Theentireprogramyouwrotelasttimecorrespondsroughlytolines43through67inthisprogram.The
onlymajordifferenceisthatinsteadofasingletotalvariablewewillhaveaturnTotalvariabletohold
onlythepointsforoneturnandatotal2variablethatholdsthecomputersoverallpointsfromroundto
round.
1importjava.util.Scanner;
2
3publicclassPigDice
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9introll,total1,total2,turnTotal;
10Stringchoice="";
11
12total1=0;
13total2=0;
14
15do
16{
17turnTotal=0;
18System.out.println("Youhave"+total1+"points.");
19
20do
21{
22roll=1+(int)(Math.random()*6);
23System.out.println("\tYourolleda"+roll+".");
24if(roll==1)
25{
26System.out.println("\tThatendsyourturn.");
27turnTotal=0;
28}
29else
30{
31turnTotal+=roll;
32System.out.println("\tYouhave"+turnTotal+"pointssofarthis
round.");
33System.out.print("\tWouldyouliketo\"roll\"againor\"hold\"?");
34choice=keyboard.next();
35}
36}while(roll!=1&&choice.equals("roll"));
37
38total1+=turnTotal;
39System.out.println("\tYouendtheroundwith"+total1+"points.");
40
41if(total1<100)
42{
43turnTotal=0;
44System.out.println("Computerhas"+total2+"points.");
45
46do
47{
48roll=1+(int)(Math.random()*6);
49System.out.println("\tComputerrolleda"+roll+".");
50if(roll==1)
51{
52System.out.println("\tThatendsitsturn.");
53turnTotal=0;
54}
55else
56{
57turnTotal+=roll;
58System.out.println("\tComputerhas"+turnTotal+"pointssofarthis
round.");
59if(turnTotal<20)
60{
61System.out.println("\tComputerchoosestorollagain.");
62}
63}
64}while(roll!=1&&turnTotal<20);
65
66total2+=turnTotal;
67System.out.println("\tComputerendstheroundwith"+total2+"points.");
68}
69
70}while(total1<100&&total2<100);
71
72if(total1>total2)
73{
74System.out.println("Humanitywins!");
75}
76else
77{
78System.out.println("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,whichbeginsonline17.TheturnTotalisthenumber
ofpointsthehumanhasearnedthisroundsofar.Andsinceitsthebeginningoftheround,weshould
startitoutat0.
Line20isthebeginningofadowhileloopthatcontainsthehumansturn.Itendsonline36,andallthe
codebetweenlines20and36willrepeataslongasthehumandoesnotrolla1andaslongasthehuman
keepschoosingtorollagain.
Eachrollforthehumanbeginsjustlikethecomputerdid:bychoosingarandomnumberfrom1to6.
Weprintthisoutonline22.
Nowtwothingscouldhappen:eithertherollis1andthehumanlosesallpointsearnedthisroundor
therollis26andtherollisaddedtotheirturnTotal.Wedisplaytheappropriatemessages,andonlines
33and34wegivethehumanthechoicetochanceitbyrollingagainorplayitsafebyholding.Thenon
line36theconditionofthedowhileloopwillcheckandrepeatbackuptoline20ifappropriate.
Oncetheplayersturnends,weaddtheturnTotal(whichmightbe0)totheplayersoveralltotaland
displaytheircurrentnumberofpoints.
Online41thecomputersturnbegins.However,thecomputerdoesntgetaturnifthehumanhas
alreadyreached100points:thegameisoverinthatcase.Sotopreventthecomputerfromplayingwe
mustwrapthewholecomputersturninabigifstatementsothatitisskippedifthehumanstotal
(total1)isgreaterthanorequalto100.Thisifstatementbeginshereonline41andendsonline68.
Soonline43thecomputersturnbeginsforreal.Thisisbasicallythesameasthepreviousexercise,soI
wontbothertoexplainitagain.Noticethatthecomputerisdecidingwhetherornottorollagainbased
onitsturntotal.
Line70endsthedowhileloopcontainingthewholegame,andlines72through79determineand
displaythewinner.
Hopefullyyouwereabletofollowtheflowofthegamewellenough.Itsprettycomplicated.
Iwouldalsopointouthowimportantitisforaprogramlikethisthateverytimeyouputanopenbrace,
youindenteverythinginsidethefollowingblockonemorelevel.Itwillsaveyoualotofgriefifyoucan
justscanyoureyesvisuallydownfromtheopencurlybraceonline47tothematchingclosecurlybrace
online64toseewhatisinsidethatdowhileloopandwhatisnt.
Exercise34:CallingaFunction
Thepreviousexercisewasprettycomplicated.Sowewillrelaxabitwithtodaysexercise.Wearegoing
tolearnhowtowriteafunction10inJavaandhowtomakeitexecutebycallingit.
1publicclassThereAndBackAgain
2{
3publicstaticvoidmain(String[]args)
4{
5System.out.println("Here.");
6erebor();
7System.out.println("Backfirsttime.");
8erebor();
9System.out.println("Backsecondtime.");
10}
11
12publicstaticvoiderebor()
13{
14System.out.println("There.");
15}
16}

WhatYouShouldSee
Here.
There.
Backfirsttime.
There.
Backsecondtime.
Solines5through9areprettyboring,exceptthatonlines6and8wearereferringtosomethingcalled
ereborthatyouhaventseenbeforeinJava.Doyouknowwhyyouhaventseenit?Becauseitdoesnt
exist!
Skippingdowntolines12through15youwillnoticethatIaddedsomethingtoourprogramthatisnot
insidethebodyofmain().Normallytheclosecurlybraceofpublicstaticvoidmainis
almostattheendofthecode,andtheonlythingafteritistheclosecurlybraceofpublicclass
Whatevs.Butnotthistime!
Lines12through15defineafunctionnamederebor().(Theworderebor()doesntmean
anythinginparticulartoJava.Wecouldhavenameditbilbo()orsmaug()oranythingwelike.)
Thisfunctionhasanopencurlybraceonline13justlikemain()alwayshasanopencurlybrace.And
online15istheendofthefunctionsbody,andtheresaclosecurlybrace.Sothefunctiondefinition
startsonline12andendsonline15.
Whatdoesthefunctiondo?ItprintstheString"There."onthescreen.

10 ThisisoneofthethingswhereImfulloflies.Technically,Javadoesntevenhavefunctions.Itonlyhasmethodsand
thisisamethod,notafunction.
ButthisisonlyamethodbecausethatisallJavahas.Inanyotherprogramminglanguage,whatwehavewrittenherewould
becalledafunctionandnotamethod.Thisisbecausemethodsareanobjectorientedthingandthisprogramisnoteven
remotelyobjectoriented.
Soeventhoughitstechnicallyincorrect,Iamgoingtorefertothissortofthingasafunctionandonlyusethewordmethod
whenImakesomethingthatactuallybehaveslikeamethod.
MyintentionallywrongvocabularywillonlycauseproblemsifyouaretalkingtoapedanticJavaprogrammerbecausethey
mightmakefunofyou.Ifthathappens,showthemthisfootnoteandaskthemhowmanyyearstheyhavebeenteaching
beginnerstocode.Ipromisethatdoingitthiswayisbetterthantryingtoshowyourealmethodsfromthebeginningor
doingthisnowandtryingtodistinguishbetweenmethodsthatactlikefunctionsandmethodsthatbehavelikereal
methods.
Sonowletsgobackuptomain()andlookatthefunctioncallsinsidethebodyofmain().
Online5weprinttheString"Here."onthescreen.Thenonline6youwillseeafunctioncall.This
lineofcodetellsthecomputertojumpdowntothefunctionerebor(),runthroughallthecodeinthe
bodyofthatfunction,andtoreturntoline6oncethathasbeenaccomplished.
Soyouseethatwhenwecalltheerebor()function,theString"There."getsprintedonthescreen
rightaftertheString"Here.".Whenthecomputerrunsline6,executionoftheprogrampausesin
main(),skipsoveralltherestofthecodeinmain(),jumpsdowntoline12,runsallthecodeinthe
bodyofthefunctionerebor()(all1lineofit)andthenonceexecutionhitstheclosecurlybraceon
line15,itreturnsbackuptotheendofline6andunpausestheexecutioninmain().Itrunsline7next.
Online7isdisplaysanothermessageonthescreen,thenonline8thereisanotherfunctioncall.The
functionereboriscalledasecondtime.Itpausesmain()online8,jumpsdownandrunsthroughthe
bodyoferebor(whichprintstheString"There."again),thenreturnsbackuptoline8where
executionofmain()resumes.
Finallyline9printsonelastStringonthescreen.Executionthenproceedstotheclosecurlybraceof
main()whichisonline10.Whenmain()ends,theprogramends.
Thatsprettyimportant,soIwillsayitagain:whenmain()ends,theprogramends.Evenifyouhavea
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)inthisprogram.EverythingthatlookslikeanOisacapitalletterO.Alsonotice
thatlines45and50featureprint()insteadofprintln().
1importstaticjava.lang.System.*;
2
3publicclassOverlyComplexFlag
4{
5publicstaticvoidmain(String[]args)
6{
7printTopHalf();
8
9print48Colons();
10print48Ohs();
11print48Colons();
12print48Ohs();
13print48Colons();
14print48Ohs();
15}
16
17publicstaticvoidprint48Colons()
18{
19out.println("|::::::::::::::::::::::::::::::::::::::::::::::::|");
20}
21
22publicstaticvoidprint48Ohs()
23{
24out.println("|OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO|");
25}
26
27publicstaticvoidprint29Colons()
28{
29out.println("|:::::::::::::::::::::::::::::|");
30}
31
32publicstaticvoidprintPledge()
33{
34out.println("Ipledgeallegiancetotheflag.");
35}
36
37publicstaticvoidprint29Ohs()
38{
39out.println("|OOOOOOOOOOOOOOOOOOOOOOOOOOOOO|");
40}
41
42publicstaticvoidprint6Stars()
43{
44out.print("|******");
45}
46
47publicstaticvoidprint5Stars()
48{
49out.print("|*****");
50}
51
52publicstaticvoidprintSixStarLine()
53{
54print6Stars();
55print29Ohs();
56}
57
58publicstaticvoidprintFiveStarLine()
59{
60print5Stars();
61print29Colons();
62}
63
64publicstaticvoidprintTopHalf()
65{
66out.println("________________________________________________");//
1spacethen48underscores
67printSixStarLine();
68printFiveStarLine();
69printSixStarLine();
70printFiveStarLine();
71printSixStarLine();
72printFiveStarLine();
73printSixStarLine();
74}
75
76}

WhatYouShouldSee
________________________________________________
|******|OOOOOOOOOOOOOOOOOOOOOOOOOOOOO|
|*****|:::::::::::::::::::::::::::::|
|******|OOOOOOOOOOOOOOOOOOOOOOOOOOOOO|
|*****|:::::::::::::::::::::::::::::|
|******|OOOOOOOOOOOOOOOOOOOOOOOOOOOOO|
|*****|:::::::::::::::::::::::::::::|
|******|OOOOOOOOOOOOOOOOOOOOOOOOOOOOO|
|::::::::::::::::::::::::::::::::::::::::::::::::|
|OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO|
|::::::::::::::::::::::::::::::::::::::::::::::::|
|OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO|
|::::::::::::::::::::::::::::::::::::::::::::::::|
|OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO|
Thisexerciseisridiculous.Thereisnogoodreasonthatanyselfrespectingprogrammerwouldever
writethecodetodrawaflagonthescreenlikethis.Itisokayifwritingthisprogramfeltalittlesilly.
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()function.That
function(thankfully)onlydisplayssomethingonthescreensowhentheclosecurlybraceof
print6Stars()comesonline45,itreturnscontrolbacktothesecondline(line55)of
printSixStarLine(),whichthenhasanotherfunctioncall.Thisrunsthroughthebodyofthe
functionprint29Ohs()andcomesbacktoline56.SothenprintSixStarLine()ends,which
returnscontroltotheendofline67.
Atthispoint,Ithinkexplainingallthefunctioncallswillbemoreconfusingthanjustfollowingthe
executionpathonyourown,sohereIwilljustprintallthelinenumbersthatexecute,inorder.Callinga
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,gobackanddoit.This
bookisntcalledLearnJavatheHalfwayisit?Printoutthecode,grabapencil,anddrawlines
wheneverafunctioncallssomewhereelseanddrawalinebackwhenthefunctionreturns.When
youaredoneitshouldlookabitlikeaplateofgraphitespaghetti!
2. Onlines32through35youfindadefinitionforafunctionnamedprintPledge().Butyet
theoutputofthisfunctionnevershowsup.Whynot?Attheendofmain()addafunctioncall
torunthisfunctionsothatitshowsupunderneaththeflag.
(Despitetheevilnessofthisprogram,Iamprettyproudofthatflag.Ifyouusearulertomeasurethe
dimensionsofeverythingyouwillfindthatmyflagisaboutascloseasIthinkyoucanmakeittothe
dimensionsofarealUnitedStatesflag.Iactuallyspentquiteawhilemeasuringandadjusting
everything.)
Exercise36:DisplayingDicewithFunctions
Thelastexerciseusedfunctionsinaprogramwherefunctionsactuallymadethingsworse.Sotodaywe
arereadytolookatasituationwhereusingafunctionactuallymakestheprogrambetter.
YachtisanolddicegamethatwasmodifiedforthecommercialgameYahtzee.Itinvolvesrollingfive
diceatonceandearningpointsforvariouscombinations.TherarestcombinationisTheYacht,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)(Math.random()*6);
11roll2=1+(int)(Math.random()*6);
12roll3=1+(int)(Math.random()*6);
13roll4=1+(int)(Math.random()*6);
14roll5=1+(int)(Math.random()*6);
15System.out.println("\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);
24System.out.println("TheYacht!!");
25}
26
27publicstaticvoidshowDice(introll)
28{
29System.out.println("++");
30if(roll==1)
31{
32System.out.println("||");
33System.out.println("|o|");
34System.out.println("||");
35}
36elseif(roll==2)
37{
38System.out.println("|o|");
39System.out.println("||");
40System.out.println("|o|");
41}
42elseif(roll==3)
43{
44System.out.println("|o|");
45System.out.println("|o|");
46System.out.println("|o|");
47}
48elseif(roll==4)
49{
50System.out.println("|oo|");
51System.out.println("||");
52System.out.println("|oo|");
53}
54elseif(roll==5)
55{
56System.out.println("|oo|");
57System.out.println("|o|");
58System.out.println("|oo|");
59}
60elseif(roll==6)
61{
62System.out.println("|oo|");
63System.out.println("|oo|");
64System.out.println("|oo|");
65}
66System.out.println("++");
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.
Online27youseethebeginningofthedefinitionoftheshowDicefunction.Afterthename(or
identifier)showDicethereisasetofparenthesesandbetweenthemavariableisdeclared!This
variableiscalledaparameter.TheshowDicefunctionhasoneparameter.Thatparameterisan
integer.Itisnamedroll.
ThismeansthatwheneveryouwriteafunctioncallforshowDiceyoucannotjustwritethenameof
thefunctionwithparentheseslikeshowDice().Itwontcompile.Youmustincludeanintegervalue
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,acopyoftheargumentsvalueisstoredintotheparameter.Soifyoucallthefunctionlike
soshowDice(3);thenthefunctioniscalledandthevalue3isstoredintotheparameterroll.Soby
line29theparametervariablerollhasalreadybeendeclaredandinitializedwiththevalue3.
IfwecallthefunctionusingavariablelikeshowDice(roll2);thenthefunctioniscalledanda
copyofwhatevervalueiscurrentlyinroll2willhavebeenstoredintotheparametervariablerollbefore
thebodyofthefunctionisexecuted.
Soonline16theshowDicefunctionisexecuted,androllwillhavebeensetequaltowhatevervalueis
inroll1.
Thenonline17showDiceiscalledagain,butthistimerollwillbesetequaltowhatevervalueisin
roll2.Line18callsshowDicewhilesettingitsparameterequaltothevalueofroll3.Andsoon.
Inthiswaywebasicallyrunthesamechunkofcodefivetimes,butsubstitutingadifferentvariablefor
rolleachtime.Thissavesusalotofcode.
Forcomparison,Ialsowroteasimplifiedtwodiceversionofthisexercisewithoutusingfunctions.
NoticehowIhadtorepeattheexactsamesequenceofifstatementstwice:onceforeachvariable.
Alsonoticethatalthoughdefiningafunctionisalittlebitmoreworkthanjustcopyingandpastingthe
ifstatementsandchangingthevariable,thetwodiceversionislongerthanthefivediceversion.
1publicclassYachtDiceNoFunctions
2{
3publicstaticvoidmain(String[]args)
4{
5introll1,roll2;
6
7do
8{
9roll1=1+(int)(Math.random()*6);
10roll2=1+(int)(Math.random()*6);
11inttotal=roll1+roll2;
12System.out.println("\nYourolleda"+roll1+"anda"+roll2);
13System.out.println("++");
14if(roll1==1)
15{
16System.out.println("||");
17System.out.println("|o|");
18System.out.println("||");
19}
20elseif(roll1==2)
21{
22System.out.println("|o|");
23System.out.println("||");
24System.out.println("|o|");
25}
26elseif(roll1==3)
27{
28System.out.println("|o|");
29System.out.println("|o|");
30System.out.println("|o|");
31}
32elseif(roll1==4)
33{
34System.out.println("|oo|");
35System.out.println("||");
36System.out.println("|oo|");
37}
38elseif(roll1==5)
39{
40System.out.println("|oo|");
41System.out.println("|o|");
42System.out.println("|oo|");
43}
44elseif(roll1==6)
45{
46System.out.println("|oo|");
47System.out.println("|oo|");
48System.out.println("|oo|");
49}
50System.out.println("++");
51
52
53System.out.println("++");
54if(roll2==1)
55{
56System.out.println("||");
57System.out.println("|o|");
58System.out.println("||");
59}
60elseif(roll2==2)
61{
62System.out.println("|o|");
63System.out.println("||");
64System.out.println("|o|");
65}
66elseif(roll2==3)
67{
68System.out.println("|o|");
69System.out.println("|o|");
70System.out.println("|o|");
71}
72elseif(roll2==4)
73{
74System.out.println("|oo|");
75System.out.println("||");
76System.out.println("|oo|");
77}
78elseif(roll2==5)
79{
80System.out.println("|oo|");
81System.out.println("|o|");
82System.out.println("|oo|");
83}
84elseif(roll2==6)
85{
86System.out.println("|oo|");
87System.out.println("|oo|");
88System.out.println("|oo|");
89}
90System.out.println("++");
91
92System.out.println("Thetotalis"+total+"\n");
93}while(roll1!=roll2);
94
95System.out.println("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
Somefunctionshaveparametersandsomedonot.Parametersaretheonlywaytosendvaluesintoa
function.Thereisalsoonlyonewaytogetavalueoutofafunction:thereturnvalue.
Thisexercisegivesanexampleofafunctionthathasthreeparameters(thesidelengthsofatriangle)and
oneoutput:theareaofthattriangleusingHeronsFormula.
1publicclassHeronsFormula
2{
3publicstaticvoidmain(String[]args)
4{
5doublea;
6
7a=triangleArea(3,3,3);
8System.out.println("Atrianglewithsides3,3,3hasanareaof"+a);
9
10a=triangleArea(3,4,5);
11System.out.println("Atrianglewithsides3,4,5hasanareaof"+a);
12
13a=triangleArea(7,8,9);
14System.out.println("Atrianglewithsides7,8,9hasanareaof"+a);
15
16System.out.println("Atrianglewithsides5,12,13hasanareaof"+
triangleArea(5,12,13));
17System.out.println("Atrianglewithsides10,9,11hasanareaof"+
triangleArea(10,9,11));
18System.out.println("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=Math.sqrt(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
YoucanseethatthefunctiontriangleAreahasthreeparameters.Theyareallintegers,andtheyare
nameda,bandc.Asyoualreadyknow,thismeansthatwecannotcallthefunctionwithoutproviding
threeintegervaluesasarguments.
Inadditiontothis,thetriangleAreafunctionreturnsavalue.Noticethatonline21thatitdoesnt
sayvoidbetweenpublicstaticandtriangleArea.Itsaysdouble.Thatmeansthis
functionreturnsavalue,andthetypeofvalueitreturnsisadouble.
Ifinsteadithadthekeywordvoidinthisposition,itmeansthisfunctiondoesnotreturnanyvalue.If
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
returnvalues.Ananalogyishelpful.
Letussaythatwearesittinginmyschoolclassroom.Wehearthesoundofthunder
andIrememberthatIleftmycarwindowsdown.Idontwantraintomaketheinside
ofmycarwet,soIsendyououtintotheparkinglot.
Student,pleasegooutintotheparkinglotandrollupthewindowsofmycar.
Yes,sir,yousay.
Ifyouneedinformationfrommeaboutwhatmycarlookslike,thenthoseare
parameters.Ifyoualreadyknowwhichoneismine,youneednoparameters.
EventuallyyoureturnandsayIcompletedthetask.Thissortoffunctiondoesnot
returnavalue.
rollUpWindows();//ifyoudon'tneedparameters

rollUpWindows("Toyota","Corolla",2008,"blue");//ifyoudoneedparameters
Ineithercase,thefunctionisexecutedandgoesoffanddoesitsthing,butreturnsnovalue.Now,
example#2:
Againweareinmyclassroom.Iamonlinetryingtoupdatemycarinsuranceandthe
webpageisaskingmeformycarslicenseplatenumber.Idontrememberit,soIask
youtogototheparkinglotandgetitforme.
Eventuallyyoureturnandtellmethelicenseplatenumber.Maybeyouwroteitdown
onascrapofpaperormaybeyoumemorizedit.Whenyougiveittome,Icopyit
downmyself.Thissortoffunctionreturnsavalue.
Stringplate;

plate=retrieveLicensePlate();//ifyoudon'tneedparameters

plate=retrieveLicensePlate("Toyota","Corolla",2008,"blue");//ifyoudo
needthem
IfIamrude,youcouldreturntomyclassroomandgivemethevalueandIcouldputmyfingersinmy
earssoIdonthearyouorrefusetowriteitdownmyselfsothatIquicklyforgetit.Ifyoucallafunction
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
c.Itrunsallthecodeonlines23through28withthosevaluesfortheparameters.Bytheend,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=Math.sqrt(s*(sa)*(sb)*(sc));
13System.out.println("Atrianglewithsides3,3,3hasanareaof"+
A);
14
15a=3;
16b=4;
17c=5;
18s=(a+b+c)/2;
19A=Math.sqrt(s*(sa)*(sb)*(sc));
20System.out.println("Atrianglewithsides3,4,5hasanareaof"+
A);
21
22a=7;
23b=8;
24c=9;
25s=(a+b+c)/2;
26A=Math.sqrt(s*(sa)*(sb)*(sc));
27System.out.println("Atrianglewithsides7,8,9hasanareaof"+
A);
28
29a=5;
30b=12;
31c=13;
32s=(a+b+c)/2;
33A=Math.sqrt(s*(sa)*(sb)*(sc));
34System.out.println("Atrianglewithsides5,12,13hasanareaof"+A
);
35
36a=10;
37b=9;
38c=11;
39s=(a+b+c)/2;
40A=Math.sqrt(s*(sa)*(sb)*(sc));
41System.out.println("Atrianglewithsides10,9,11hasanareaof"+A
);
42
43a=8;

11 (ThevariableAitselfdoesnotgetreturned,onlyitsvalue.Infact,rememberthatthescopeofavariableislimitedto
theblockofcodeinsidewhichitisdefined?(YoulearnedthatinExercise21.)Thevariableaisonlyinscopeinsidethe
functionmain,andthevariabless,A,andtheparametervariablesa,bandcareonlyinscopeinsidethefunction
triangleArea.)
44b=15;
45c=17;
46s=(a+b+c)/2;
47A=Math.sqrt(s*(sa)*(sb)*(sc));
48System.out.println("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. Thereisabugintheformulaforbothfiles.When(a+b+c)isanoddnumber,dividingby2
throwsawaythe.5.Fixitsothatinsteadof(a+b+c)/2youhave(a+b+c)/2.0.Howmuch
harderwouldithavebeentofixtheversionthatdidntuseafunction?
3. Addonemoretest:findtheareaofatrianglewithsides9,9,and9.Wasitdifficulttoadd?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
Todaysexercisehasnothingnew.Itismerelyadditionalpracticewithfunctions.Thisprogramhas
threefunctions(fourifyoucountmain)andtheyallhaveparametersandallthreereturnvalues.
1importjava.util.Scanner;
2
3publicclassShapeArea
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9intchoice;
10doublearea=0;
11
12System.out.println("ShapeAreaCalculatorversion0.1(c)2013
MitchellSampleOutput,Inc.");
13
14do
15{
16System.out.println("\n==============\n");
17System.out.println("1)Triangle");
18System.out.println("2)Circle");
19System.out.println("3)Rectangle");
20System.out.println("4)Quit");
21System.out.print(">");
22choice=keyboard.nextInt();
23
24if(choice==1)
25{
26System.out.print("\nBase:");
27intb=keyboard.nextInt();
28System.out.print("Height:");
29inth=keyboard.nextInt();
30area=computeTriangleArea(b,h);
31System.out.println("Theareais"+area);
32}
33elseif(choice==2)
34{
35System.out.print("\nRadius:");
36intr=keyboard.nextInt();
37area=computeCircleArea(r);
38System.out.println("Theareais"+area);
39}
40elseif(choice==3)
41{
42System.out.print("\nLength:");
43intlength=keyboard.nextInt();
44System.out.print("Width:");
45intwidth=keyboard.nextInt();
46System.out.println("Theareais"+
computeRectangleArea(length,width));
47}
48elseif(choice!=4)
49{
50System.out.println("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=Math.PI*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
namedA.Thisvariableislocaltothefunction.EventhoughthereisavariablenamedAdeclaredon
line66,theyarenotthesamevariable.(ItslikehavingtwofriendsnamedMichael.Justbecausethey
havethesamenamedoesntmakethemthesameperson.)
Thevalueofthevariableb(definedonline27)ispassedinastheinitialvalueoftheparameterbasein
thefunctioncallonline30.bisstoredintobasebecausebisfirst,notbecausebasestartswithab.The
computerdoesntcareanythingaboutthat.Onlytheordermatters.
Online61thevalueofAisreturnedtomainandendsupgettingstoredinthevariablecalledarea.
Ididthreestrangethingsintherectangleareafunctionwhosedefinitionbeginsonline71.
First,theformalparametershavethesamenamesastheactualarguments.(Remember,theparameters
arethevariablesdeclaredinthefunctiondefinitiononline71andtheargumentsarethevariablesinthe
parenthesesinthefunctioncallonline46.)Thisisaneatcoincidence,butitdoesntmeananything.Itis
likehavinganactornamedStevenplayingacharacternamedSteven.Thevaluefrommains
versionoflengthgetsstoredintocomputeRectangleAreaslengthvariablebecausetheyareboth
listedfirstintheparenthesesandfornootherreason.
Secondly,Ididnotbothertocreateavariableforthevaluethefunctionisgoingtoreturnonline73.I
simplyreturnedthevalueoftheexpressionlength*width.Thefunctionwillfigureoutwhatthe
valueisandreturnitrightawaywithouteverstoringitintoavariable.
Thirdly,therectangleareavalueisreturnedbacktomainonline46,butIdidntbothertostorethe
returnvalueintoavariable:Ijustprinteditonthescreendirectly.(IalsodidthisinHeronsFormula
butIdidntcallattentiontoit.)Thisistotallyfineandactuallyprettycommon.Wecallfunctionsallthe
timeandwealmostalwaysusethereturnvalueofthefunctionbutwedontalwaysneedtostorethe
returnvalueintoitsownvariable.
Finally,beforewemoveontoanothertopicIshouldmentionthatinJava,functionscanonlyreturna
singlevalue.Insomeotherprogramminglanguagesfunctionscanreturnmorethanonevalue.Butin
Javafunctionscanreturnasinglevalueornovalue(ifthefunctionisvoid)butnevermorethanone.
P.S.Thesefunctionsareabitsilly.IfIwerereallyneedingashapeareacalculator,Iamnotsureifit
wouldbeworthittocreateawholefunctionforanequationthatisonlyonelineofcode.Butthis
exampleisgoodforexplaining,anyway.

StudyDrills
1. Addafunctiontocomputetheareaofasquare.Addittothemenuaswell.
Exercise39:ThirtyDaysRevisitedwithJavadoc
Inthepreviousexercisewewrotesomefunctionsthatmighthavebeenbetteroffomitted.Intodays
exercisewearegoingtoredoapreviousexercise,makingitbetterwithfunctions.
And,becauseIalwayshavetokeeppushing,Ihaveaddedspecialcommentsabovetheclassandabove
eachfunctioncalledJavadoccomments.
1importjava.util.Scanner;
2
3/**
4*Containsfunctionsthatmakeiteasiertoworkwithmonths.
5*/
6publicclassThirtyDaysFunctions
7{
8publicstaticvoidmain(String[]args)
9{
10Scannerkb=newScanner(System.in);
11
12System.out.print("Whichmonth?(112)");
13intmonth=kb.nextInt();
14
15System.out.println(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
improvesthecode.main()isveryshort,becausemostoftheinterestingworkisbeingdoneinthe
functions.
AllthecodeandvariablespertainingtothenameofthemonthisisolatedinthemonthName()
function.AndallthecodetofindthenumberofdaysinamonthiscontainedinsidethemonthDays()
function.
Collectingvariablesandcodeintofunctionslikethisiscalledproceduralprogramminganditis
consideredamajoradvanceoverjusthavingallyourcodeinmain().Itmakesyourcodeeasierto
debugbecauseifyouhaveaproblemwiththenameofthemonth,youknowithastobeinsidethe
monthName()function.
Okay,nowletstalkabouttheJavadoccomments.
javadocisanautomaticdocumentationgeneratingtoolthatisincludedwiththeJavacompiler.You
writedocumentrightinyourcodebydoingaspecialsortofblockcommentaboveclasses,functionsor
variables.
Thecommentbeginswith/**andendswith*/andeverylineinbetweenstartswithanasterisk(*)
whichislineduplikeyouseeintheexercise.
Thefirstlineofthejavadoccommentisaonesentencesummaryofthething(classorfunction).And
thentherearetagslike@authoror@returnthatgivemoredetailaboutwhowrotethecode,what
parametersthefunctionexpectsorwhatvalueitisgoingtoreturn.
Okay,sonowforthemagicpart.Gototheterminalwindowjustlikeyouweregoingtocompileyour
code,andtypethefollowingcommand:
$javadocThirtyDaysFunctions.java
LoadingsourcefileThirtyDaysFunctions.java...
ConstructingJavadocinformation...
StandardDocletversion1.7.0_21
Buildingtreeforallthepackagesandclasses...
Generating/ThirtyDaysFunctions.html...
Generating/packageframe.html...
Generating/packagesummary.html...
Generating/packagetree.html...
Generating/constantvalues.html...
Buildingindexforallthepackagesandclasses...
Generating/overviewtree.html...
Generating/indexall.html...
Generating/deprecatedlist.html...
Buildingindexforallclasses...
Generating/allclassesframe.html...
Generating/allclassesnoframe.html...
Generating/index.html...
Generating/helpdoc.html...
$
ThenifyoulookinthefolderwhereThirtyDaysFunctions.javaislocated,youwillseealotof
newfiles.(MaybeIshouldhavewarnedyoufirst.)Openthefilecalledindex.htmlintheweb
browserofyourchoice.
Thisisjavadocdocumentation,andthereisalotofinformationthere.Youcanfindthecommentyou
putfortheclassnearthetop,andthecommentsforthefunctionsareinthesectioncalledMethod
Summary.
ThedetailsabouttheparametersandreturntypesaredownbelowinthesectioncalledMethodDetail.

StudyDrills
1. LookatthejavadocdocumentationforoneofthebuiltinJavaclasses:java.util.Scanner.Notice
howsimilaritlookstowhatthejavadoctoolgenerated?AlltheofficialJavadocumentationis
createdusingthejavadoctool,solearninghowtoreaditwillbeanimportantpartofbecoming
anexpertJavaprogrammer.Dontworrytoomuchaboutthedetailsrightnow,though.Justtry
togetafeelforhowitlooks.
IntheupperleftisalistofallthepackagesofcodethatareincludedaspartofJavaandbelow
thatontheleftisalistofalltheclasses/librariesyoucouldimporttosaveyoufromhavingto
writecode.AbigpartofwhatprofessionalJavaprogrammersdoiswritecodetogluetogether
existingJavalibraries.
Thisisprobablyoverwhelmingrightnow.Thatsfinebecauseyouhavejuststarted.Hopefully
nooneexpectsyoutounderstandmuchaboutthisyet.Infact,mostprogrammersonlyknow
aboutafractionofthebuiltinJavalibraries,andtheysearchontheInternetandreadthe
documentationwhentheyneedtodosomethingnew,justlikeyoudo!
Exercise40:ImportingStandardLibraries
InthelastexerciseyougotaterrifyinglookatallofthebuiltinmodulesthatareavailableinJava.
TodaywewilllookatasimpleprogramthattookmeabouthalfanhourtowritebecauseIspentalot
oftimesearchingtheInternetandimportingthingsandtryingthingsthatdidntwork.
Thiscodeworks,though.Itallowsthehumantoenterapassword(oranything,really)andthenprints
outtheSHA256messagedigestofthatpassword.
Whenyouaretypinginthiscode,dontforgettoputthethrowsExceptionattheendofline7.
1importjava.util.Scanner;
2importjava.security.MessageDigest;
3importjavax.xml.bind.DatatypeConverter;
4
5publicclassPasswordDigest
6{
7publicstaticvoidmain(String[]args)throwsException
8{
9Scannerkeyboard=newScanner(System.in);
10
11Stringpw,hash;
12
13MessageDigestdigest=MessageDigest.getInstance("SHA256");
14
15System.out.print("Password:");
16pw=keyboard.nextLine();
17
18digest.update(pw.getBytes("UTF8"));
19hash=DatatypeConverter.printHexBinary(digest.digest());
20
21System.out.println(hash);
22}
23}

WhatYouShouldSee
Password:password
5E884898DA28047151D0E56F8DC6292773603D0D6AABBDD62A11EF721D1542D8
That64characterlongstringistheSHA256digestoftheStringpassword.Thatmessagedigestwill
alwaysbethesameforthatinput.
Ifyoutypeinadifferentpassword,youllgetadifferentdigest,ofcourse:
Password:Thisisareallylongpasswordandnoonewilleverguessit.
A113B65D8BA8DB72D631D97B7A3698E82CDB9D1F52456C8957312CB91EC02B10
Backintheearlydaysofprogramming,whenmachinesfirststartedhavingusernamesandpassword,it
wasprettyobviousthatyouwouldntwanttostorethepasswordsthemselvesinadatabase.Instead,they
wouldstoresomesortofcryptographichashofthepassword.
Cryptographichasheshavetwousefulproperties:
1. Theyareconsistent.Agiveninputwillalwaysproduceexactlythesameoutput.
2. Theyareoneway.Youcaneasilycomputetheoutputforagiveninput,butfiguringoutthe
inputthatgaveyouacertainoutputisveryhardorimpossible.
SHA256isaverygoodcryptographichashfunction,anditproducesadigestforagiveninput(or
message)thatisalwaysexactly256bitslong.Hereinsteadoftryingtodealwithbitswehaveprinted
outthebase64representationofthosebits,whichendsupbeing64characterslongwhereeach
characterisahexadecimaldigit.
Backinthe1970s,tochangeyourpasswordonacertainmachineyouwouldtypeyourpasswordandthe
machinewouldstoreyourusernameandthehashofyournewpasswordinafile.
Thenwhenyouwantedtologintothemachinelater,itwouldmakeyoutypeinyourusernameand
password.Itwouldfindtheusernameinthepassworddatabasefileandfindthestoredhashofyour
password.Thenitwouldfindthehashofwhateverpasswordyoujusttyped.Ifthestoredhashandthe
computedhashmatch,thenyoumusthavetypedinthecorrectpasswordandyouwouldbeallowed
accesstothemachine.
Thisisacleverscheme.Itisalsomuchbetterthaneverstoringpasswordsdirectlyinadatabase.
However,nowadayscomputersarewaytoofastandhavewaytoomuchstoragespaceforthistobe
enoughsecurity.SincemachinescancomputetheSHA256ofapasswordveryquickly,itdoesnttake
longforadeterminedhackertofigureoutwhatyourpasswordwas.
(Ifyoureallywanttosecurelystorepasswordsinadatabase,youshouldbeusing
bcrypt,whichismadeforsuchthings.UnfortunatelybcryptisntbuiltintoJava,so
youwillneedtodownloadabcryptlibrarymadebysomeoneelse.)
Okay,enoughaboutsecurepasswords,letuswalkthroughthiscode.Youmightwanttohavethe
javadocdocumentationforthesetwolibrariesopen.
java.security.MessageDigest
javax.xml.bind.DatatypeConverter
Onlines2and3weimportthetwolibrarieswewillbeusingtodothehardpartsofthisexercise.
Online13wecreateavariableoftypeMessageDigest(whichnowexistsbecauseweimported
java.security.MessageDigest.Ourvariableisnameddigest,althoughIcouldhavecalledit
somethingelse.Andthevalueofthevariablecomesfromthereturnvalueofthemethod
MessageDigest.getInstance().WepassinaStringasanargumenttothismethod,whichis
whichdigestwewant.Inthiscaseweareusing"SHA256",but"SHA1"and"MD5"wouldhave
alsoworked.Youcanreadaboutthisstuffinthejavadocdocumentation.
Lines15and16arehopefullyboring.NoticethatIusednextLine()insteadofjustnext()toread
inthepassword,whichallowsthehumantotypeinmorethanoneword.
Online18wecallthegetBytes()methodoftheStringclass,withanargumentof"UTF8".This
convertstheStringvaluetoarawlistofbytesinUTF8formatwhichwepassdirectlyasanargumentto
theupdate()methodoftheMessageDigestobjectnameddigest.IlearnedaboutthegetBytes()
methodbyreadingthejavadocdocumentationfortheStringclass!
java.lang.String
Online19wecallthedigest()methodoftheMessageDigestobjectnameddigest.Thisgivesusa
rawlistofbytesandisntsuitableforprintingonthescreen,sowepassthatrawlistofbytesdirectlyas
aparametertotheprintHexBinary()methodoftheDatatypeConverterclass.ThisreturnsaString,
whichwestoreintothevariablehash.
Wethendisplaythehashvalueonthescreen.Whew!
Ifthisexercisefreakedyououtalittlebit,dontworry.Ifyoucanmakeitthroughthefirst39exercises
inthebook,thenyoucouldlearntodothissortofthing,too.Youhavetolearnhowtoreadjavadoc
documentationtolearnwhatsortoftoolsotherpeoplehavealreadywrittenforyouandhowtoconnect
themtogethertogetwhatyouwant.Itjusttakesalotofpractice!Rememberthatwritingthisexercise
thefirsttimetookmemorethanhalfanhour,andIvebeenprogrammingsincethe1980sandstarted
codinginJavain1996!
StudyDrills
1. Lookatthejavadocdocumentationforallthemethodsusedinthisexercise:getInstance,
getBytes,update,digest,andprintHexBinary.Lookatwhatargumentstheyexpectandlookat
thetypesofvaluestheywillreturn.
2. RemovethethrowsExceptionfromtheendofline7.Trytocompileit.(Thenputitback.)
Youwilllearnatinybitaboutexceptionsinthenextexercise.
Exercise41:ProgramsthatWritetoFiles
Wearegoingtotakeabreakfromfocusingonfunctionsnowforabitandlearnsomethingeasy.Weare
goingtocreateaprogramthatcanputinformationintoatextfileinsteadofonlybeingabletoprint
thingsonthescreen.
Whenyouaretypinginthiscode,dontmissthethrowsExceptionattheendofline6.(Andin
thisexercise,Illactuallyexplainwhatthatmeans.)
1importjava.io.FileWriter;
2importjava.io.PrintWriter;
3
4publicclassLetterRevisited
5{
6publicstaticvoidmain(String[]args)throwsException
7{
8PrintWriterfileout;
9
10fileout=newPrintWriter(newFileWriter("letter.txt"));
11
12fileout.println("++");
13fileout.println("|####|");
14fileout.println("|####|");
15fileout.println("|####|");
16fileout.println("||");
17fileout.println("||");
18fileout.println("|BillGates|");
19fileout.println("|1MicrosoftWay|");
20fileout.println("|Redmond,WA98104|");
21fileout.println("||");
22fileout.println("++");
23fileout.close();
24}
25}

WhatYouShouldSee

Thatsright.Whenyourunyourprogram,itwillappeartodonothing.Butifyouwroteitcorrectly,it
shouldhavecreatedafilecalledletter.txtinthesamefolderyourcodeisin.Youcanviewthis
fileusingthesametexteditoryouareusingtowriteyourcode.
IfforsomereasonyouareusingtheversionofNotepadthatcamewithWindows95,itwilllookalittle
somethinglikethis:

(Imadethatscreenshotalongtimeago,okay?Ivebeendoingthisalongtime,remember.WhenIfirst
gavethisassignmenttostudents,Windows95wasthenewestversionofWindows.Infact,Iguessthe
zipcodechangedatsomepoint.)
Onlines1and2therearetwonewimportstatements,oneforeachoftheJavaclassesthatwillmake
thiseasy.
Online8wedeclareavariable.ThevariableisoftypePrintWriterandIhavechosentonameit
fileout(althoughthevariablesnamedoesntmatter).
Online10wegivethePrintWritervariableavalue:thereferencetoanewPrintWriterobject.Creating
thePrintWriterobjectrequiresanargument,though.TheargumentwegiveitisanewFileWriter
object,whichitselfiscreatedwiththefilenameasanargument.
ItispossibletowritetoatextfileusingonlyaFileWriterobjectandwithoutusinganyPrintWriter
atall.However,PrintWritersaremucheasiertoworkwith,asyoucantellbylookingattherestofthe
code.SoinsteadofworkingwiththeFileWriterobjectdirectly,wewraptheFileWriterobjectwitha
PrintWriterobjectandjustworkthroughthePrintWriterobject.
(Itisokayifyoudidntunderstandthelasttwoparagraphs.Youdontneedto
understandthemtowritetofiles.)
ThegoodnewsisthatoncethePrintWriterobjectissetup,everythingelseiseasy.Becauseyouhave
secretlybeenworkingwithPrintWriterssincetheverybeginning!ThisisbecauseSystem.outisa
PrintWriter!
Soonline12youcanseethatwritingtothefilelooksverysimilartoprintingonthescreen.Butthe
String(+)willnotbeprintedonthescreen.Itwillbestoredasthefirstlineofthefile
letter.txt!
Ifafilenamedletter.txtalreadyexistsinthatfolder,itscontentswillbeoverwrittenwithout
warning.Ifthefiledoesnotexist,itwillbecreated.
Theonlyotherimportantlineintheexerciseisline23.Thisactuallysavesthecontentsofthefileand
closesitsoyourprogramcantwritetoitanymore.Ifyouremovethisline,yourprogramwillmost
likelycreateafilecalledletter.txt,butthefilewillbeempty.
Okay,beforeIendtheexercise,IwanttobrieflydiscussthrowsException.Thisisnotsomething
wedomuchinRealProgramming,andexplainingitproperlyisbeyondthescopeofthisbook,butIdo
wanttotouchonit.
Intheoriginalversionoftheexercise,whenyouputthrowsExceptionafterthefirstlineofa
function,itmeansIhavewrittencodeinthisfunctionthatmightnotwork,andifitfailsitwillblowup
(bythrowinganexception).
InthiscasethethingthatmightnotworkisthelinenewFileWriter("letter.txt")
becauseittriestoopenafileforwritinginthecurrentfolder.Thiscouldfailifthereisalreadyafile
calledletter.txtandthefileisreadonly.Ormaybethewholefolderisreadonly.Ortheressome
otherreasontheprogramcantgetwritepermissiontothefile.
Soinsteadofjustblowinguptheprogramwearesupposedtodetecttheexceptionandhandleit.Like
so:
1importjava.io.FileWriter;
2importjava.io.PrintWriter;
3importjava.io.IOException;
4
5publicclassLetterRevisitedException
6{
7publicstaticvoidmain(String[]args)
8{
9PrintWriterfileout;
10
11try
12{
13fileout=newPrintWriter(newFileWriter("letter.txt"));
14}
15catch(IOExceptionerr)
16{
17System.out.println("Sorry,Ican'twritetothefile'letter.txt'.");
18System.out.println("Maybethefileexistsandisreadonly?");
19fileout=null;
20System.exit(1);
21}
22
23fileout.println("++");
24fileout.println("|####|");
25fileout.println("|####|");
26fileout.println("|####|");
27fileout.println("||");
28fileout.println("||");
29fileout.println("|BillGates|");
30fileout.println("|1MicrosoftWay|");
31fileout.println("|Redmond,WA98104|");
32fileout.println("||");
33fileout.println("++");
34fileout.close();
35}
36}

Thetryblockmeansthiscodemaythrowanexception,butattemptit.Ifeverythinggoeswell(if
thereisnoexceptionthrown)thenthecatchblockisskipped.Ifthereisanexceptionthrown,the
catchblockgetsexecuted,andtheexceptionthatwasthrowngetspassedinasaparameter.(Ihave
namedtheexceptionparametererr,thoughitcouldbenamedanything.)
InsidethecatchblockIprintoutasuitableerrormessageandthenendtheprogrambycallingthe
builtinfunctionSystem.exit().Ifyoupassanargumentof0toSystem.exit(),theprogram
willend,butthezeromeanseverythingisfine.Anargumentof1meansthisprogramisending,and
itisbecausesomethingwentwrong.
SoIwontusetryandcatchanymoreinthisbook,butatleastnowyouknowwhatyouareavoiding
byputtingthrowsException.
Exercise42:GettingDatafromaFile
Aprogramthatcanputinformationintoafileisonlypartofthestory.Sointhisexerciseyouwilllearn
howtoreadinformationthatisalreadyinatextfile.
Ifyoutypeupthiscodeandcompileitandrun,itwillblowup.Thisisbecauseitistryingtoreadfroma
textfilecallednameandnumbers.txt,whichmustbeinthesamefolderasyourcode.You
probablydonthaveafilelikethis!
Sobeforeyouevenwritethecode,letusmakeatextfilecontainingaStringandthreeintegers.Myfile
lookslikethis:

(ThisisaslightlynewerversionofNotepad.Happynow?)
Okay,tothecode!
1importjava.util.Scanner;
2importjava.io.File;
3
4publicclassGettingFromFile
5{
6publicstaticvoidmain(String[]args)throwsException
7{
8ScannerfileIn=newScanner(newFile("nameandnumbers.txt"));
9
10inta,b,c,sum;
11Stringname;
12
13System.out.print("Gettingnameandthreenumbersfromfile...");
14name=fileIn.nextLine();
15a=fileIn.nextInt();
16b=fileIn.nextInt();
17c=fileIn.nextInt();
18fileIn.close();
19
20System.out.println("done.");
21System.out.println("Yournameis"+name);
22sum=a+b+c;
23System.out.println(a+"+"+b+"+"+c+"="+sum);
24}
25}
WhatYouShouldSee
Gettingnameandthreenumbersfromfile...done.
YournameisSamanthaShowalter
5+6+7=18
DidyouknowthattheScannerobjectdoesnthavetogetinputfromthehumanatthekeyboard?Itcan
readdatafromtextfiles,too!
WejustcreatetheScannerobjectslightlydifferently:insteadofSystem.inastheargument,weuse
newFile("blah.txt").Thiswillopenthetextfilereadonly.TheScannerobject(whichIhave
chosentocallfileIn)willbeattachedtothefilelikeastrawstuckintoajuicebox.(Thejuiceboxisthe
textfile,andtheScannerobjectisthestraw.)
Line14looksprettyuninteresting.ItpausestheprogramandreadsinaStringfromtheScanner
object,whichgetsitfromthefile.ThisStringfromthefileisstoredintothevariable.
Lines15through17aresimple,too.Exceptwhatisreadfromthefileisconvertedtoanintegerbefore
puttingitinthevariables.
Whatifthenextthinginthefileisntaninteger?Thenyourprogramwillblowup.Andnowyoucant
blamethehumananymore:youcreatedthisfile.Itisyourjobtomakesureyouknowwhatvaluesarein
it,andinwhatorder.
Online18thefileisclosed,whichmeansyourScannerobjectisntconnectedtoitanymore.
Wasthiseasierthanyouexpectedittobe?Hopefullyso.

StudyDrills
1. Openthetextfileandchangethenameornumbers.Saveit.Thenrunyourprogramagain(you
donthavetocompileitagain;thecodehasntchangedanditdoesntopenthefileuntilitis
run.)
Exercise43:SavingaHighScore
Nowthatyouknowhowtogetinformationfromfilesandhowtoputinformationinfiles,wecancreate
agamethatsavesthehighscore!
Thisisthecoinflippinggamefromafewexercisesago,butnowthehighscoreissavedfromruntorun.
1importjava.util.Scanner;
2importjava.io.File;
3importjava.io.FileWriter;
4importjava.io.PrintWriter;
5
6publicclassCoinFlipSaved
7{
8publicstaticvoidmain(String[]args)throwsException
9{
10Scannerkeyboard=newScanner(System.in);
11
12Stringcoin,again,bestName,saveFile="coinflipscore.txt";
13intflip,streak=0,best;
14
15Filein=newFile(saveFile);
16if(in.createNewFile())
17{
18System.out.println("Savegamefiledoesn'texist.Created.");
19best=1;
20bestName="";
21}
22else
23{
24Scannerinput=newScanner(in);
25bestName=input.next();
26best=input.nextInt();
27input.close();
28System.out.println("Highscoreis"+best+"flipsinarowby"
+bestName);
29}
30
31
32do
33{
34flip=1+(int)(Math.random()*2);
35
36if(flip==1)
37coin="HEADS";
38else
39coin="TAILS";
40
41System.out.println("Youflipacoinanditis..."+coin);
42
43if(flip==1)
44{
45streak++;
46System.out.println("\tThat's"+streak+"inarow....");
47System.out.print("\tWouldyouliketoflipagain(y/n)?");
48again=keyboard.next();
49}
50else
51{
52streak=0;
53again="n";
54}
55}while(again.equals("y"));
56
57System.out.println("Finalscore:"+streak);
58
59if(streak>best)
60{
61System.out.println("That'sanewhighscore!");
62System.out.print("Yourname:");
63bestName=keyboard.next();
64best=streak;
65}
66elseif(streak==best)
67{
68System.out.println("Thattiesthehighscore.Cool.");
69}
70else
71{
72System.out.println("You'llhavetodobetterthan"+streak+"
ifyouwantahighscore.");
73}
74
75//Savethisnameandhighscoretothefile.
76PrintWriterout=newPrintWriter(newFileWriter(saveFile));
77out.println(bestName);
78out.println(best);
79out.close();
80}
81}

WhatYouShouldSee
Savegamefiledoesn'texist.Created.
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,soIcheated.Ittookmequiteafewtriestogetastreakofthreeinarow.)
Online15wecreateaFileobjectusingthefilenamecoinflipscore.txt.Wecandothis
evenifthefiledoesntexist.
Online16thereisanifstatement,andintheconditionIcallthecreateNewFile()methodofthe
Fileobject.Thiswillchecktoseeifthefileexists.Ifso,itwilldonothingandreturntheBooleanvalue
false.Ifthefiledoesnotexist,itwillcreatethefileemptyandreturnthevaluetrue.
Whentheifstatementistrue,then,itmeansthesavegamefiledidntexist.Wesaysoandputsuitable
initialvaluesintothevariablesbestandbestName.Ifnot,thentheresalreadyafilethere,soweusea
Scannerobjecttogettheexistingnameandhighscoreoutofthefile.Cool,eh?
Lines32through57aretheexistingcoinflipgame.Ididntchangeanyofthiscodeatall.
Online59weneedtofigureoutiftheybeatthehighscore.Ifso,weprintoutamessagetothateffect
andletthementertheirname.
Iftheytiedthehighscore,wesayso,buttheydontgetanyfameforthat.
Andonline70theelsewillruniftheydidntbeatortiethehighscore.Sowetauntthem,ofcourse.
Onlines75through79wesavethecurrenthighscorealongwiththenameofthehighscorertothefile.
Thismightbeanewscore,oritmightbethepreviousvaluewereadatthebeginningoftheprogram.

StudyDrills
1. Changetheprogramsothatitonlysavestothehighscorefileifithaschanged.
2. Hackthehighscorefilebyopeningitinatexteditorandmanuallychangingit.Impressyour
friendswithyouramazingluckystreak!
Exercise44:CountingwithaForLoop
Asyouhaveseeninpreviousexercises,whileloopsanddowhileloopscanbeusedtotomake
somethinghappenmorethanonce.
Butbothkindsofloopsaredesignedtokeepgoingaslongassomethingistrue.Ifweknowinadvance
howmanytimeswewanttodosomething,Javahasaspecialkindofloopdesignedjustformakinga
variablechangevalues:theforloop.
1importjava.util.Scanner;
2
3publicclassCountingFor
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9intn;
10Stringmessage;
11
12System.out.println("Typeinamessage,andI'lldisplayitfive
times.");
13System.out.print("Message:");
14message=keyboard.nextLine();
15
16for(n=1;n<=5;n++)
17{
18System.out.println(n+"."+message);
19}
20
21System.out.println("\nNowI'lldisplayittentimesandcountby5s."
);
22for(n=5;n<=50;n+=5)
23{
24System.out.println(n+"."+message);
25}
26
27System.out.println("\nFinally,threetimescountingbackward.");
28for(n=3;n>0;n=1)
29{
30System.out.println(n+"."+message);
31}
32
33}
34}

WhatYouShouldSee
Typeinamessage,andI'lldisplayitfivetimes.
Message:Howdy,y'all!
1.Howdy,y'all!
2.Howdy,y'all!
3.Howdy,y'all!
4.Howdy,y'all!
5.Howdy,y'all!

NowI'lldisplayittentimesandcountby5s.
5.Howdy,y'all!
10.Howdy,y'all!
15.Howdy,y'all!
20.Howdy,y'all!
25.Howdy,y'all!
30.Howdy,y'all!
35.Howdy,y'all!
40.Howdy,y'all!
45.Howdy,y'all!
50.Howdy,y'all!

Finally,threetimescountingbackward.
3.Howdy,y'all!
2.Howdy,y'all!
1.Howdy,y'all!
Line16demonstratesaverybasicforloop.Everyforloophasthreepartswithsemicolonsbetween.
Thefirstpart(n=1)onlyhappensoncenomatterhowmanytimesthelooprepeats.Ithappensatthe
verybeginningoftheloopandusuallysetsastartingvalueforsomevariablethatisgoingtobeusedto
controltheloop.Inthiscase,ourloopcontrolvariableisnanditwillstartwithavalueof1.
Thesecondpart(n<=5)isacondition,justliketheconditionofawhileordowhileloop.Thefor
loopisapretestloopjustlikeawhileloop,whichmeansthatthisconditionistestedbeforetheloop
startslooping.Iftheconditionistrue,theloopbodywillbeexecutedonetime.Iftheconditionisfalse,
theloopbodywillbeskippedandtheloopisover.
Thethirdpart(n++)runsaftereachiterationoftheloop,justbeforeitcheckstheconditionagain.
Rememberthat++addsonetoavariable.
Soifweunrollthisloop,thesearethestatementsthatwillhappenandtheirorder:
n=1;
//checkif(n<=5),whichistrue
System.out.println(1+"."+message);
n++;//sonownis2
//checkif(n<=5),whichistrue
System.out.println(2+"."+message);
n++;//sonownis3
//checkif(n<=5),whichistrue
System.out.println(3+"."+message);
n++;//sonownis4
//checkif(n<=5),whichistrue
System.out.println(4+"."+message);
n++;//sonownis5
//checkif(n<=5),whichistrue
System.out.println(5+"."+message);
n++;//sonownis6
//checkif(n<=6),whichisfalse.Theloopstops
Noticethatthefirstpartonlyhappenedonce,andthatthethirdparthappenedexactlyasmanytimesas
theloopbodydid.
Online22thereisanotherforloop.Theloopcontrolvariableisstilln.(Noticethattheloopcontrol
variableappearsinallthreepartsoftheloop.Thisisalmostalwaysthecase.)
Thefirstpart(theinitializationexpression)setstheloopcontrolvariabletostartat5.Thenthesecond
partcheckstoseeifnislessthanorequalto50.Ifso,thebodyisexecutedonetimeandthenthethird
partisexecuted.Thethirdpartadds5totheloopcontrolvariable,andthentheconditionischecked
again.Ifitisstilltrue,thelooprepeats.Onceitisfalse,theloopstops.
Online28thereisonefinalforloop.Thistimetheloopcontrolvariablestartsat3andtheloop
repeatsaslongasnisgreaterthanzero.Andaftereachiterationoftheloopbodythethirdpart(the
updateexpression)subtracts1fromtheloopcontrolvariable.
Sowhenshouldyouuseaforloopversusawhileloop?
forloopsarebestwhenweknowinadvancehowmanytimeswewanttodosomething.
Dothistentimes.
Dothisfivetimes.
Pickarandomnumber,anddoitthatmanytimes.
Takethislistofitems,anddoitonetimeforeachiteminthelist.
Ontheotherhand,whileanddowhileloopsarebestforrepeatingaslongassomethingistrue:
Keepgoingaslongastheyhaventguessedit.
Keepgoingaslongasyouhaventgotdoubles.
Keepgoingaslongastheykeeptypinginanegativenumber.
Keepgoingaslongastheyhaventtypedinazero.

StudyDrills
1. Deletethefirstpart(theinitializationexpression)fromthethirdloop.Ifyouremoveit
correctly,itwillstillcompile.Whathappenswhenyourunit?
Exercise45:CaesarCipher(LoopingThroughaString)
TheCaesarcipherisaverysimpleformofcryptographynamedafterJuliusCaesar,whouseditto
protecthisprivateletters.Inthecipher,eachletterisshiftedupordowninthealphabetbyacertain
amount.Forexample,iftheshiftis2,thenallAsinthemessagearereplacedwithC,Bisreplacedwith
D,andsoon.
1importjava.util.Scanner;
2
3publicclassCaesarCipher
4{
5/**
6*Returnsthecharactershiftedbythegivennumberofletters.
7*/
8publicstaticcharshiftLetter(charc,intn)
9{
10intch=c;
11
12if(!Character.isLetter(c))
13returnc;
14
15ch=ch+n;
16if(Character.isUpperCase(c)&&ch>'Z'||Character.isLowerCase(c)&&ch>'z')
17ch=26;
18if(Character.isUpperCase(c)&&ch<'A'||Character.isLowerCase(c)&&ch<'a')
19ch+=26;
20
21return(char)ch;
22}
23
24publicstaticvoidmain(String[]args)
25{
26Scannerkeyboard=newScanner(System.in);
27Stringplaintext,cipher="";
28intshift;
29
30System.out.print("Message:");
31plaintext=keyboard.nextLine();
32System.out.print("Shift(026):");
33shift=keyboard.nextInt();
34
35for(inti=0;i<plaintext.length();i++)
36{
37cipher+=shiftLetter(plaintext.charAt(i),shift);
38}
39System.out.println(cipher);
40
41}
42}

WhatYouShouldSee
Message:Thisisatest.XyZaBcDeF
Shift(026):2
Vjkukucvguv.ZaBcDeFgH
Didyouknowthatmain()doesnthavetobethefirstfunctionintheclass?Well,itdoesnt.Functions
canappearinanyorder.
Alsoinadditiontoint,double,StringandbooleanthereisabasicvariabletypeIhavent
mentioned:char.AcharvariablecanholdcharacterslikeStringsdo,butitcanonlyholdone
characteratatime.Stringliteralsinthecodeareenclosedindoublequoteslike"Axe",whilechar
literalsinthecodeareinsinglequoteslike'A'.
Startingonline8thereisafunctioncalledshiftLetter().Ithastwoparameters:cisthecharacter
toshiftandnisthenumberofspacestoshiftit.Thisfunctionreturnsachar.So
shiftLetter('A',2)wouldreturnthecharacter'C'.
Wedontwanttotrytoshiftanythingthatisntaletter,soonline10weusethebuiltinCharacterclass
totellus.
Thenwearegoingtobedoingalittlemathwiththecharacter,sowestorethecharactersUnicodevalue
intoanintonline13tomakethiseasier.Thenonline15weaddthedesiredoffsettothecharacter.
Thiswouldbeit,exceptthatwewanttheoffsettowraparound,solines16through19makesurethat
thefinalvalueisstillaletter.Thenfinallyonline21wetakethevalueofch,castittoachar,and
returnit.
Inmain(),lines27through34areprettyboring.BeforeIcanexplaintheforloop,though,Ineedto
explaintwoStringclassmethods:charAt()andlength().
IfyouhaveaStringyoucangetasinglecharoutofitusingthecharAt()method.Likeso:
Strings="Howdy";
charc=s.charAt(2);
//Nowc=='w'
//s.length()is5
charAt()iszerobased,sos.charAt(0)getsthefirstcharacteroutofaStrings.Andif
s.length()tellsyouhowmanycharactersthereareins,thens.charAt(s.length()1)
getsthefinalcharacter.
Nowwecanunderstandtheforlooponline36.Theinitializationexpressiondeclaresandaloop
controlvariableiandsetsitequalto0.Theconditiongoesaslongasiislessthanthenumberof
charactersinthemessage.Andtheupdateexpressionwilladd1toieachtime.
Online38,alotofthingsarehappening.WeusethecharAtmethodtopulloutonlytheithcharacter
ofthemessage.ThatcharacterandtheshiftvaluearepassedasargumentstotheshiftLetter()
function,whichreturnstheshiftedletter.Andfinallythatshiftedletteristackedontotheendofthe
Stringcipher.
Bythetimetheloopends,ithasgonethrougheachletterofthemessageoneatatimeandbuiltupa
newmessagefromtheshiftedversionsoftheletters.
Maybethatwastoomuchatonce.Letmeknow.

StudyDrills
1. Makeanewversionofthisexercisethatgetsthemessagefromatextfileinsteadandcreatesan
encryptedfilewiththeciphertextinsteadofjustprintingitonthescreen.
Exercise46:NestedForLoops
Inprogramming,thetermnestedusuallymeanstoputsomethinginsidethesamething.Nested
loopswouldbetwoloopswithoneinsidetheotherone.Ifyoudoitright,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{
10System.out.println(c+""+n);
11}
12}
13
14System.out.println("\n");
15
16//thisis#2I'llcallit"AB"
17for(inta=1;a<=3;a++)
18{
19for(intb=1;b<=3;b++)
20{
21System.out.print("("+a+","+b+")");
22}
23//*Youwilladdalineofcodehere.
24}
25
26System.out.println("\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
outside.Howdoestheoutputchange?
3. Lookatthesecondsetofnestedloops(AB).Changetheprint()statementtoprintln().
Howdoestheoutputchange?(Thenchangeitbacktoprint().)
4. AddaSystem.out.println()statementaftertheclosebraceoftheinnerloop(theb
loop),butstillinsidetheouterloop.Howdoestheoutputchange?
Exercise47:GeneratingandFilteringValues
Nestedforloopsaresometimeshandybecausetheyareverycompactandcanmakesomevariables
changethroughalotofdifferentcombinationsofvalues.
Manyyearsago,astudentposedthefollowingmathproblemtome:
FarmerBrownwantstospendexactly$100.00andwantstopurchaseexactly100
animals.Ifsheepcost$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{
13System.out.print(s+"sheep,");
14System.out.print(g+"goats,and");
15System.out.println(c+"chickens.");
16}
17}
18}
19}
20}
21}

WhatYouShouldSee
4sheep,4goats,and92chickens.
Thisprogramisneatbecauseitisveryshort.Butanobserversittinginsidetheinnermostloop(justin
frontoftheifstatementonline11willseeonemilliondifferentcombinationsofs,gandcflowby.
Thefirstcombinationattemptedwillbe1sheep,1goat,1chicken.Thatwillbepluggedintothemath
equationsintheifstatement.Theywontbetrue,andnothingwillbeprinted.
Thenthenextcombinationwillbe1sheep,1goatand2chickens.Whichwillalsofail.Then1sheep,1
goat,3chickens.Andsoonupto1sheep,1goatand100chickenswhentheinnerlooprunsitslast
iteration.
Thentheg++online7willexecute,theconditiononline7willchecktomakesuregisstilllessthanor
equalto100(whichitis)andthebodyofthemiddleforloopwillexecuteagain.
Thiswillcausetheinitializationexpressionoftheinnermostlooptorunagain,whichresetscto1.So
thenextcombinationofvariablethatwillbetestedintheifstatementis1sheep,2goatsand1chicken.
Then1sheep,2goats,2chickens,then1sheep,2goats,3chickens.Etcetera.
Bytheendall100*100*100combinationshavebeentestedand999,999ofthemfailed.Butbecause
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)
9System.out.println(s+"sheep,"+g+"goats,and"+c+"
chickens.");
10}
11}

Thisisperfectlylegalandbehavesidenticallytothepreviousversion.Comparethattohowmuchcode
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{
16System.out.print(s+"sheep,");
17System.out.print(g+"goats,and");
18System.out.println(c+"chickens.");
19}
20c++;
21}
22g++;
23}
24s++;
25}
26}
27}
Thewhileloopversionisalsomorefragilebecauseitwouldbeeasytoaccidentallyforgettoreseta
variableto1ortoincrementitattheendoftheloopbody.Doingthiswithwhileloopsmightbeeasier
togettocompilebutitismorelikelytohavesubtlelogicalerrorsthatcompilebutdontworkas
intended.

StudyDrills
1. Ourcodeworks,butitisnotasefficientasitcouldbe.(Forexample,thereisnoreasontomake
thesheeplooptry11or12ormoresheepbecausewecantaffordthem.Seeifyoucanchange
theloopboundstomakethecombinationslesswasteful.
Exercise48:ArraysManyValuesinaSingleVariable
Inthisexerciseyouwilllearntwonewthings.Thefirstoneissuperimportantandthesecondoneisjust
kindofneat.
InJava,anarrayisatypeofvariablewithonename(identifier)butcontainingmorethanone
variable.Inmyopinion,yourenotaRealProgrammeruntilyoucanworkwitharrays.So,thatsgood
news.Yourealmostthere!
1publicclassArrayIntro
2{
3publicstaticvoidmain(String[]args)
4{
5String[]planets={"Mercury","Venus","Earth","Mars","Jupiter",
"Saturn","Uranus","Neptune"};
6
7for(Stringp:planets)
8{
9System.out.println(p+"\t"+p.toUpperCase());
10}
11}
12}

WhatYouShouldSee
MercuryMERCURY
VenusVENUS
EarthEARTH
MarsMARS
JupiterJUPITER
SaturnSATURN
UranusURANUS
NeptuneNEPTUNE
Online5wedeclareanddefineavariablenamedplanets.ItisnotjustaString:noticethesquare
brackets.ThisvariableisanarrayofStrings.Thatmeansthatthisonevariableholdsalleightofthose
Stringsandtheyareseparatedintodistinctslotssowecanaccessthemoneatatime.
Thecurlybracesonthislineareusedforadifferentpurposethanusual.Allthesevaluesareinquotes
becausetheyareStrings.Therearecommasbetweeneachvalue,thenthewholeinitializerlistisincurly
braces.Andtheresasemicolonattheend.
Thesecondnewthinginthisexerciseisanewkindofforloop.(Thisissometimescalledaforeach
loop,sinceitworksabitlikealoopinanotherprogramminglanguagewherethekeywordactuallyis
foreachinsteadoffor.)
Online7youwillseethisforeachloopinaction.Youreaditoutloudlikethis:foreachStringpin
thearrayplanets.
SoinsidethebodyofthisforeachlooptheStringvariablepwilltakeonacopyofthevalueofeach
valueintheStringarrayplanets.Thatis,thefirsttimethroughtheloop,pwillcontainacopyofthefirst
valueinthearray("Mercury").Thenthesecondtimethroughtheloop,pwillcontainacopyofthe
secondvalueinthearray("Venus").Andsoon,untilallthevaluesinthearrayhavebeenseen.Then
theloopwillautomaticallystop.
Insidethebodyoftheloop(online9)wearejustprintingoutthecurrentvalueofpandanuppercase
versionofp.Justforfun,Iguess.
Thisnewkindofforlooponlyworkswithcompoundvariableslikethis:variablesthathaveonename
butcontainmultiplevalues.ArraysarenttheonlysortofcompoundvariableinJava,butwewontbe
lookingatanyoftheothersinthisbook.
Arraysareabigdeal,sothatsenoughforthisexercise.Iwanttomakeabsolutelysureyouunderstand
whatishappeninginthisassignmentbeforethrowingmoreonyourplate.
Exercise49:FindingThingsinanArray
Morewitharrays!Inthisexercisewewillexaminehowtofindaparticularvalue.Thetechniqueweare
usinghereissometimescalledalinearsearchbecauseitstartswiththefirstslotofthearrayandlooks
there,thenmovestothesecondslot,thenthethirdandsoondowntheline.
1importjava.util.Scanner;
2
3publicclassArrayLinearSearch
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
8
9int[]orderNumbers={12345,54321,78753,101010,8675309,31415,
271828};
10inttoFind;
11
12System.out.println("Thereare"+orderNumbers.length+"ordersin
thedatabase.");
13
14System.out.print("Orders:");
15for(intnum:orderNumbers)
16{
17System.out.print(num+"");
18}
19System.out.println();
20
21System.out.print("Whichordertofind?");
22toFind=keyboard.nextInt();
23
24for(intnum:orderNumbers)
25{
26if(num==toFind)
27{
28System.out.println(num+"found.");
29}
30}
31}
32}

WhatYouShouldSee
Thereare7ordersinthedatabase.
Orders:123455432178753101010867530931415271828
Whichordertofind?78753
78753found.
ThistimethearrayisnamedorderNumbersanditisanarrayofintegers.Ithassevenslots.12345is
thefirstslot,and271828isinthelastslotofthearray.Eachofthesevenslotscanholdaninteger.
WhenwecreateanarrayJavagivesusabuiltinvariablewhichtellsusthecapacityofthearray.This
variableisreadonly(youcanretrieveitsvaluebutnotchangeit)andiscalled.length.Inthiscase,
sincethearrayorderNumbershassevenslots,thevariableorderNumbers.lengthisequalto7.
Thisisusedonline12.
Online15wehaveaforeachlooptodisplayalltheordernumbersonthescreen.Foreachinteger
numinthearrayorderNumbers.Soinsidethebodyofthisloop,numwilltakeoneachvaluein
thearrayoneatatimeanddisplaythemall.
Online22weletthehumantypeinanordernumber.Thenweusethelooptoletnumtakeoneach
ordernumberandcomparethemtotoFindoneatatime.Whenwehaveamatch,wesayso.
(Youhavetoimaginethatwehavehundredsorthousandsofordersinthedatabase
insteadofjustsevenandthatweprintoutmorethanjusttheordernumberwhenwe
findamatch.Wellbegettingtheresoonenough.)

StudyDrills
1. Wecreatedanintcallednuminsidebothforeachloops.Couldwehavejustdeclaredthe
variableonceuponline10andthenremovedtheintfrombothloops?Tryitandsee.
2. Trytochangethecodesothatiftheordernumberisnotfound,itprintsoutasinglemessage
sayingso.Thisistricky.Evenifyouarentsuccessful,giveitagoodeffortbeforemovingonto
thenextexercise.
Exercise50:SayingSomethingIsNOTinanArray
Inlife,thereisagenerallackofsymmetrybetweencertaintypesofstatements.
Awhitecrowexists.
Thisstatementiseasyenoughtoprove.Startlookingatcrows.Onceyoufindawhiteone,stop.Done.
Nowhitecrowsexist.
Thisstatementismuchhardertoprovebecausetoproveitwehavetogatherupeverythingintheworld
thatqualifiesasacrow.Ifwehavelookedatthemallandnotfoundanywhitecrows,onlythencanwe
safelysaythatnoneexist.
Hopefullyyoutriedthestudydrillinyesterdaysexercise.
1importjava.util.Scanner;
2
3publicclassItemNotFound
4{
5publicstaticvoidmain(String[]args)
6{
7Scannerkeyboard=newScanner(System.in);
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
17System.out.print("PopQuiz!NameanymortalherofromGreekmythology:");
18guess=keyboard.next();
19
20found=false;
21for(Stringhero:heroes)
22{
23if(guess.equals(hero))
24{
25System.out.println("That'scorrect!");
26found=true;
27}
28}
29
30if(found==false)
31{
32System.out.println("No,"+guess+"wasn'taGreekmortalhero.");
33}
34}
35}

WhatYouShouldSee
PopQuiz!NameanymortalherofromGreekmythology:Hercules
No,Herculeswasn'taGreekmortalhero.
Moststudentswanttosolvethisproblembyputtinganotherifstatement(oranelse)insidetheloop
tosaynotfound.Butthiscannotwork.IfIwanttoknowifsomethingisfound,itisokaytosaysoas
soonasIfindit.ButifIwanttoknowifsomethingwasneverfound,youhavetowaituntiltheloopis
overbeforeyouknowforsure.
SointhiscaseIuseatechniquecalledaflag.Aflagisavariablethatstartswithonevalue.Thevalue
ischangedifsomethinghappens.Thenlaterintheprogramyoucanusethevalueoftheflagtoseeifthe
thinghappenedornot.
MyflagvariableisaBooleancalledfound,whichissettofalseonline20.Ifamatchisfound,we
saysoandchangetheflagtotrueonline26.Noticethatinsidetheloopthereisnocodethatcan
changetheflagtofalse,soonceithasbeenflippedtotrueitwillstaythatway.
Thenonline30,aftertheloopisdone,youcanexaminetheflag.Ifitisstillfalse,thenweknowthe
ifstatementinsidetheloopwasnevertrueandthereforeweneverfoundwhatwewerelookingfor.
Exercise51:ArraysWithoutForeachLoops
Asyoumightnoticedbynow,arraysandforeachloopsaredesignedtoworktogetherwell.Butthereare
situationswherewhatwehavebeendoingwontwork.
Aforeachloopcantiteratethroughanarraybackward;itcanonlygoforward.
Aforeachloopcantbeusedtochangethevaluesintheslotsofthearray.Theforeachloop
variableisareadonlycopyofwhatsinthearrayandchangingitdoesntchangethearray.
Inaddition,wehaveonlybeenputtingvaluesintoanarrayusinganinitializerlist(thecurlybraces
thing),whichhasitsownlimitations:
Aninitializerlistonlyworkswhenthearrayisbeingdeclared;youcantuseitelsewhereinthe
code.
Aninitializerlistisbestsuitedforrelativelysmallarrays,ifyouhave1000valuesinthearray,
aninitializerlistwillbenofun.
Initializerlistsdonthelpusifwewantthevaluesinthearraytocomefromafileorsomeother
placewedonthavewhenwearetypingthecode.
Sothereisanotherwaytostorevaluesinanarrayandaccessthem.Infact,itismorecommonthanwhat
youhavebeendoing.Usingsquarebracketsandaslotnumber,wecanaccesstheslotsofanarray
individually.
1publicclassArraySlotAccess
2{
3publicstaticvoidmain(String[]args)
4{
5int[]arr=newint[3];
6inti;
7
8arr[0]=0;
9arr[1]=0;
10arr[2]=0;
11
12System.out.println("Arraycontains:"+arr[0]+""+arr[1]+""+
arr[2]);
13
14//Filleachslotofthisarraywitharandomnumber1100
15arr[0]=1+(int)(Math.random()*100);
16arr[1]=1+(int)(Math.random()*100);
17arr[2]=1+(int)(Math.random()*100);
18
19//Displaythemagain.
20System.out.println("Arraycontains:"+arr[0]+""+arr[1]+""+
arr[2]);
21
22//Thisisabitsilly,buttrytounderstandit.
23i=0;
24arr[i]=1+(int)(Math.random()*100);
25i=1;
26arr[i]=1+(int)(Math.random()*100);
27i=2;
28arr[i]=1+(int)(Math.random()*100);
29
30//Displaythemagain.
31System.out.print("Arraycontains:");
32i=0;
33System.out.print(arr[i]+"");
34i=1;
35System.out.print(arr[i]+"");
36i=2;
37System.out.print(arr[i]+"");
38System.out.println();
39
40//Thisisevenmoresillybutitworks.Canyouguesswherethisis
headed?
41i=0;
42arr[i]=1+(int)(Math.random()*100);
43i++;
44arr[i]=1+(int)(Math.random()*100);
45i++;
46arr[i]=1+(int)(Math.random()*100);
47i++;
48
49//Displaythemagain.
50System.out.print("Arraycontains:");
51i=0;
52System.out.print(arr[i]+"");
53i++;
54System.out.print(arr[i]+"");
55i++;
56System.out.print(arr[i]+"");
57i++;
58System.out.println();
59
60//Ah!Let'sjustusearegular'for'loop!
61for(i=0;i<arr.length;i++)
62{
63arr[i]=1+(int)(Math.random()*100);
64}
65
66//Displaythemagain.
67System.out.print("Arraycontains:");
68for(i=0;i<arr.length;i++)
69{
70System.out.print(arr[i]+"");
71}
72System.out.println();
73}
74}

WhatYouShouldSee
Arraycontains:000
Arraycontains:984918
Arraycontains:83771
Arraycontains:627432
Arraycontains:401754
Online5wearecreatinganarrayofintegerswithoutusinganinitializerlist.The[3]meansthatthe
arrayhasacapacityof3.Sincewedidntprovidevalues,everyslotinthearraystartsoutwithavalueof
0storedinit.Onceanarrayhasbeencreated,itscapacitycantbechanged.
Onlines8through10thereisasurprise.Thearrayhas3slots,buttheslotnumbersare0based.(The
numberthatreferstoanarrayslotiscalledanindex.Collectivelytheseoughttobecalledindices
(INNduhSEEZ)butmostpeoplejustsayindexes.)
Sothefirstslotinanarrayisindex0.Thisarraycanholdthreevalues,sothelastindexis2.Thereis
nothingyoucandoaboutthisexceptgetusedtoit.Soarr.lengthis3,butthereisnotaslotwith
index3.Thiswillprobablybeasourceofbugsforyouatfirst,buteventuallyyouwilllearn.
Anyway,lines8through10storethevalue0intoallthreeslotsinthearray.(Whichisthevaluethat
wasalreadyinthem,sothiscodedoesntdoanythinguseful.)
Online12weprintoutallthreecurrentvaluesinthearraysoyoucanseethattheyreallzero.
Onlines15through17weputrandomnumbersintoeachslotofthearray.Andprintthemoutagainon
line20.
Startingonline22Ihavedonesomethingsilly.Trytowithholdjudgmentuntiltheendoftheexercise.
Forgettingaboutwhyyoumightwanttodoit,doyouseethatline24isessentiallyidenticaltoline15?
Line24storesarandomnumberintoaspotinthearray.Whichspot?Theindexdependsonthecurrent
valueofi.Andiiscurrently0.Sowearestoringtherandomnumberintotheslotwithindex0.Okay?
Soonline25wechangethevalueofifrom0to1.Thenonline26westorearandomvalueintheslot
indexedbythevalueofi,soindex1.Clear?Weird,butlegal.
Ihaveusedsimilarshenanigansonlines31through38todisplayallthevaluesonthescreenagain.
Now,thisisclearlyobjectivelyworsethanwhatIwasdoingonline20.Imean,ittookme8linesof
codetodowhatIhadbeendoinginoneline.(Staywithme.)
Onlines40through47wedosomethingthatmightevenbeworsethanlines22through28.Lines41
and42arethesame,butinsteadofputtinga1directlyintoionline43,Ijustsayincreasethevalueof
iby1.Soihadcontaineda0;itcontainsa1afterline43isdone.
Prettymuchtheonlyadvantagetothisapproachisthatatleastcopyandpasteiseasier.Lines42and43
areliterallyidenticaltolines44and45.Andthesameforlines46and47.Imean,likebyteforbytethe
same.
Wedisplaytheminasimilarsillyfashiononlines50through58.
Butthenmaybeitoccurstoyou.WhywouldIbothertotypetheexactsamelinesthreetimesinarow
whenIcouldjust.Youknowathingthatallowsyoutorepeatachunkofcodewhilemakingasingle
variableincreasebyoneeachtime,right?
Thatsright:aforloopisjustthething.Notsosillyafterall,amI?
Lines61through64arethesameaslines41through47exceptthatwelettheforloophandlethe
repeatingandthechangingoftheindex.Theinitializationexpression(thefirstpart)oftheforloopsets
itostartat0,whichhappenstobethesmallestlegalindexforanarray.Theconditionsaysrepeatthis
aslongasiislessthanarr.length(whichis3).Andnotethatthatislessthan,notlessthanor
equalto,whichwouldbetoofar.Theupdateexpression(thethirdpart)justadds1toieachtime.
Lines67through72displaythevaluesonthescreen.
Heresthething:thissortofcodeonlines61through72mightseemalittlebitcomplex,butworking
witharraysinJavayouendupwritingcodelikethisallthetime.Icannoteventellyouhowmanytimes
Ihavewrittenaforloopjustlikethatforworkingwithanarray.
Infact,ifyourquestionisHowdoI________anarray?(Fillintheblankwithanytaskyoulike.)The
answerisWithaforloop.Prettymuchguaranteed.

StudyDrills
1. Atthetopofthecode,changeitsothearrayhasacapacityof1000insteadof3.Dontchange
anyothercodeandrecompileandrunitagain.Guesswhat?Thoseforloopsatthebottom
mighthavebeenalittlemoreworktowriteandtounderstand,butoncewrittentheyworkjustas
wellfor1000valuesasfor3.Andthatsprettycool.
Exercise52:LowestTemperature
Beforewemoveonfromarrays,thisexercisewillpulltogetherfunctions,loops,arraysandreading
fromfilestodosomething(hopefully)interesting!
IhavecreatedatextfilecontainingtheaveragedailytemperatureinAustin,TexasfromJanuary1,1995
throughJune23,2013.Thereareafewdatapointsmissing,sothereareatotalof6717temperaturesin
thefile.Youcanseethenumbershere:
http://learnjavathehardway.org/txt/avgdailytempsatx.txt

ThevaluesareindegreesFahrenheit.Thisexercisewillreadallthevaluesfromthefile(directlyoffthe
Internet,even)intoanarrayofdoublesandthenusealooptofindthelowesttemperatureinthatentire
171/2yearrange.Soundinteresting?Letsgo.
1importjava.net.URL;
2importjava.util.Scanner;
3
4publicclassLowestTemperature
5{
6publicstaticvoidmain(String[]args)throwsException
7{
8double[]temps=
arrayFromUrl("http://learnjavathehardway.org/txt/avgdailytempsatx.txt");
9
10System.out.println(temps.length+"temperaturesindatabase.");
11
12doublelowest=9999.99;
13
14for(inti=0;i<temps.length;i++)
15{
16if(temps[i]<lowest)
17{
18lowest=temps[i];
19}
20}
21
22System.out.print("Thelowestaveragedailytemperaturewas");
23System.out.println(lowest+"F("+fToC(lowest)+"C)");
24}
25
26publicstaticdouble[]arrayFromUrl(Stringurl)throwsException
27{
28Scannerfin=newScanner((newURL(url)).openStream());
29intcount=fin.nextInt();
30
31double[]dubs=newdouble[count];
32
33for(inti=0;i<dubs.length;i++)
34dubs[i]=fin.nextDouble();
35fin.close();
36
37returndubs;
38}
39
40publicstaticdoublefToC(doublef)
41{
42return(f32)*5/9;
43}
44
45}
WhatYouShouldSee
6717temperaturesindatabase.
Thelowestaveragedailytemperaturewas22.1F(5.499999999999999C)
(IfyouhavetorunthisprogramonamachinewithoutInternetaccess,thenthecodewontwork.Since
youknowhowtoreadfromatextfilealready,youcouldmodifyityourselftoreadfromalocalfile(a
fileinthesamefolderasyourcodeinsteadofontheInternet).ButifyouarelazyIhavelistedan
alternateversiondownbelow.)
Well,rightoffthebatIhavethrownacurveball.Online8wedeclareanarrayofdoublesnamed
temps,butinsteadofjustdoingthenormalthingandsettingitscapacitylikethis:
double[]temps=newdouble[6717];
Iinitializethearraywithanarraythatisthereturnvaluefromafunction!Soletslookdownatthe
functionbeforeweproceed.
Online26thefunctiondefinitionbegins.ThefunctioniscalledarrayFromUrl()andithasone
parameter:aString.Anditreturnswhat?Itreturnsnotadoublebutdouble[](anarrayof
doubles).
Online28wecreateaScannerobjecttoreaddatafromafile,butinsteadofgettingthedatafromafile,
wegettheinformationfromaURL.OneofthenicethingsaboutJavaisthatthisisonlyatinychange.
Now,IdoatrickwithmytextfilethatIlearnedmanyyearsago.AtthetimeIamwritingthischapter,
myfilecontains6717temperatures.ButmaybeyouarereadingthisayearlaterandIwanttoupdatethe
filetoaddmoretemperatures.Sothefirstlineofthefileisjustanumber:6717.ThenafterthatIhave
6717linesoftemperatures,oneperline.
Online29inthiscodeIreadthecountfromthefirstthinginthefile.AndIusethatcounttodecidehow
bigmyarrayshouldbeonline31.SosixmonthsfromnowifIdecidetoaddmoretemperaturestothe
file,allIhavetodoischangethefirstlineofmyfiletomatchandthiscodewillstillwork.Notabad
trick,eh?
Online31wedefineanarrayofdoubleswithcountslots.(Currently6717.)
Online33theresaforloopthatiteratesthrougheachslotinthearray,andonline34wereada
doublefromthefileeachtime(fin.nextDouble())andstoreitintothenextindexedslotin
array.
Thenwhentheloopends,Iclose()thefile.Thenonline37thearrayisreturnedfromthefunction
andthatarrayiswhatisstoredintothearraytempsbackonline8ofmain().
Online10weprintoutthecurrentlengthofthearraytomakesurenothingwentwrongwiththe
reading.
Online12wecreateavariablethatwilleventuallyholdthelowesttemperatureinthewholearray.At
firstweputareallylargevalueinthere,though.
Line14isanotherforloopthatisgoingtogiveusallthelegalindexesinthearray.Inthiscase,since
thearrayhas6717valuesinit,theindexeswillrunfrom0to6716.
Line16comparesthevaluewearecurrentlylookingatinthearray(dependingonthecurrentvalueof
i).Ifthatvalueislessthanwhateverisinlowest,thenwehaveanewrecord!Online18wereplacewhat
usedtobeinlowestwiththisnewsmallervalue.
Andtheloopcontinuesuntilallthevaluesinthearrayhavebeencompared.Whentheloopends,the
variablelowestnowactuallydoescontainthesmallestvalue.
Thereisasmallfunctiondownonlines40through43toconvertatemperaturefromdegreesFahrenheit
todegreesCelsius.Soonline23wedisplaythelowesttemperatureasitcamefromthefileandalso
convertedtoCelsius.
Youmaybethinkingthat22.1F(5.5C)isnotaverycoldtemperature.Well,thatsTexasforyou.Also
rememberthatthetemperaturesarentthelowesttemperatureoftheday,theyaretheaverageof24
hourlytemperaturesamplesforeachday.

StudyDrills
1. Changethecodetodisplayboththelowestaveragedailytemperatureandandthehighest.
2. Trytofindanothertemperaturefileonlineforacityclosertowhereyouliveandchangeyour
codetoreadfromitinstead!
(Imentioneditabove,butthisisthemodifiedcodetoreadthetemperaturedatafromalocalfileincase
youcantrunyourJavaprogramonamachinewithInternetaccess.)
1importjava.io.File;
2importjava.util.Scanner;
3
4publicclassLowestTemperatureLocal
5{
6publicstaticvoidmain(String[]args)throwsException
7{
8double[]temps;
9doublelowest=9999.99;
10
11//Readvaluesfromfile
12Scannerfin=newScanner(newFile("avgdailytempsatx.txt"));
13temps=newdouble[fin.nextInt()];
14
15System.out.println(temps.length+"temperaturesindatabase.");
16
17for(inti=0;i<temps.length;i++)
18temps[i]=fin.nextDouble();
19fin.close();
20
21for(inti=0;i<temps.length;i++)
22if(temps[i]<lowest)
23lowest=temps[i];
24
25System.out.print("Thelowestaveragedailytemperaturewas");
26System.out.println(lowest+"F("+fToC(lowest)+"C)");
27}
28
29publicstaticdoublefToC(doublef){return(f32)*5/9;}
30}
Exercise53:MailingAddresses(Records)
TodaysexerciseisaboutwhatIcallrecords.IntheprogramminglanguagesCandC++theyare
calledstructs.Anarrayisabunchofdifferentvaluesinonevariablewherethevaluesareallthesame
typeandtheyaredistinguishedbyindex(slotnumber).Arecordisafewdifferentvaluesinonevariable
butthevaluescanbedifferenttypesandtheyaredistinguishedbyname(usuallycalledafield).12
TypethefollowingcodeintoasinglefilenamedMailingAddresses.java.(Thelinethatsays
classAddressiscorrectbutyoucantnameyourfileAddress.javaoritwontwork.)
1classAddress
2{
3Stringstreet;
4Stringcity;
5Stringstate;
6intzip;
7}
8
9publicclassMailingAddresses
10{
11publicstaticvoidmain(String[]args)
12{
13Addressuno,dos,tres;
14
15uno=newAddress();
16uno.street="191MarigoldLane";
17uno.city="Miami";
18uno.state="FL";
19uno.zip=33179;
20
21dos=newAddress();
22dos.street="3029LoshLane";
23dos.city="Crafton";
24dos.state="PA";
25dos.zip=15205;
26
27tres=newAddress();
28tres.street="2693HannahStreet";
29tres.city="Hickory";
30tres.state="NC";
31tres.zip=28601;
32
33System.out.println(uno.street+"\n"+uno.city+","+uno.state+"
"+uno.zip+"\n");
34System.out.println(dos.street+"\n"+dos.city+","+dos.state+"
"+dos.zip+"\n");
35System.out.println(tres.street+"\n"+tres.city+","+tres.state
+""+tres.zip+"\n");
36}
37}

WhatYouShouldSee
191MarigoldLane

12 Theresonlyoneproblemwillallofthis:Javadoesntactuallyhaverecords.Itturnsoutthatifyoumakeanestedclass
withnomethodsandonlypublicvariablesitworksjustlikeastructevenifitisnttheJavaWay.
IdontcareifitistheJavaWayornot.IhavebeenteachingstudentsalongtimeandIfirmlybelievethatyoucant
understandobjectorientedprogrammingverywellifyoudontfirstunderstandrecords.SoIamgoingtofakethemina
waythatworksperfectlyfineandwouldbeverynicecodeinlotsofdifferentprogramminglanguages.
SomediehardobjectorientedJavaheadisgoingtostumbleacrossthisexerciseandsendmeannastyemailthatIamDoing
ItWrongandwhyamIfillingthesepoorkidsheadswithlies?Oh,well.
Miami,FL33179

3029LoshLane
Crafton,PA15205

2693HannahStreet
Hickory,NC28601

Souponlines1through7wehavedefinedarecordcalledAddress.
(Iknowitsaysclass,notrecord.IfIcoulddosomethingaboutthisIpromiseIwould.Youshould
callthisarecordanyway,orastructifyoureallywant.Ifyoucallitaclassitwillconfuseany
JavaprogrammerthatlovesobjectorientedprogrammingandifyoucallitastructatleasttheCand
C++programmerswillunderstandyou.)
Ourrecordhasfourfields.ThefirstfieldisaStringnamedstreet.ThesecondfieldisaStringcalled
city.Andsoon.
Thenonline9ourrealclassstarts.
Online13wedeclarethreevariablesnameduno,dosandtres.Thesevariablesarenotintegersor
Strings;theyarerecords.OftypeAddress.Eachonehasfourfieldsinit.
Online15wehavetostoreanAddressobjectinthevariablebecauserememberweonlydeclaredthe
variablesandtheyhaventbeeninitializedyet.
OncethatistakencareofyouwillseethatwecanstoretheString"191MarigoldLane"intothe
streetfieldoftheAddressrecordnameduno,andthatsexactlywhatwedoonline16.
Line17storestheString"Miami"intothecityfieldoftherecorduno.
ImnotgoingtobothertoexplainwhatishappeningfortherestoftheprogrambecauseIthinkitis
prettyclear.Iguesstheonlythingworthmentioningisthatalthoughthreeofthefieldsintherecordare
Strings,thezipfieldisaninteger.Thefieldsofarecordcanbewhatevertypeyouwant.

StudyDrills
1. CreateafourthAddressvariableonline13andchangethecodetoputyourmailingaddressinit.
Dontforgettoprintitoutatthebottom.

FrequentlyAskedQuestions
Wheredidyougettheseaddresses?
Imadethemup.Imfairlycertainthosestreetsdontexistinthosecities.IfbysomemiracleImadeupa
realaddress,letmeknowandIllchangeit.
Exercise54:RecordsfromaFile
Thisexercisewillshowyouhowtoreadvaluesintoarecordfromatextfile.Thereisalsoanexample
ofaloopthatreadsintheentirefile,nomatterhowlongitis.
IfyourunthisprogramonamachinethatisntconnectedtotheInternet,thiscodewontworkas
written,althoughthechangeisverysmall.Thecodeaccessesthisfile,whichyoucandownloadifyou
needto.
http://learnjavathehardway.org/txt/s01e01cast.txt

TypethefollowingcodeintoasinglefilenamedActorList.java.(Thelinethatsaysclass
ActoriscorrectbutyoucantnameyourfileActor.javaoritwontwork.)
1importjava.util.Scanner;
2
3classActor
4{
5Stringname;
6Stringrole;
7Stringbirthdate;
8}
9
10publicclassActorList
11{
12publicstaticvoidmain(String[]args)throwsException
13{
14Stringurl="http://learnjavathehardway.org/txt/s01e01cast.txt";
15//ScannerinFile=newScanner(newjava.io.File("s01e01cast.txt"));
16ScannerinFile=newScanner((newjava.net.URL(url)).openStream());
17
18while(inFile.hasNext())
19{
20Actora=getActor(inFile);
21System.out.print(a.name+"wasbornon"+a.birthdate);
22System.out.println("andplayedtheroleof"+a.role);
23}
24inFile.close();
25}
26
27publicstaticActorgetActor(Scannerinput)
28{
29Actora=newActor();
30a.name=input.nextLine();
31a.role=input.nextLine();
32a.birthdate=input.nextLine();
33
34returna;
35}
36}

WhatYouShouldSee
SeanBeanwasbornon19590417andplayedtheroleofEddard'Ned'Stark
MarkAddywasbornon19640114andplayedtheroleofRobertBaratheon
NikolajCosterWaldauwasbornon19700727andplayedtheroleofJaime
Lannister
MichelleFairleywasbornon1964andplayedtheroleofCatelynStark
ThistimeourrecordiscalledActorandhasthreefields,allofwhichareStrings.
Online16wecreateaScannerobjectthatisconnectedtotheInternetaddressoftheinputtextfile.Did
younoticethatIdidntimportjava.net.URLatthetop?Youonlyneedtoimportaclassifyouwant
tobeabletotypetheshortversionoftheclassname.
Inthiscase,ifIhadimportedjava.net.URLatthetopofthecode,Icouldhavejustwritten:
ScannerinFile=newScanner((newURL(url)).openStream());
//insteadof
ScannerinFile=newScanner((newjava.net.URL(url)).openStream());
SometimesifIamgoingtobeusingaclassonlyonce,Idratherjustusethefullnameinmycode
insteadofbotheringtoimportit.Iusedthesametrickonline15;insteadofimportingjava.io.File
Ijustusedthefullclassnamehere.
(IfyourmachinedoesnthaveInternetaccess,removethetwoslashesatthebeginningofline15sothat
itisnolongeracommentandthenaddtwoslashesatthebeginningonline16tomakeitacomment.
ThentheprogramwillreadthefilelocallyinsteadofovertheInternet.)
WhetheryouopenthefilefromtheInternetoryourownmachine,afterline17wehaveaScannerobject
namedinFilewhichisconnectedtoatextfile.
Alotofthetimewhenwearereadingfromatextfile,wedontknowinadvancehowlongitisgoingto
be.InthelowesttemperatureexerciseIshowedyouonetrickfordealingwiththis:storingthenumber
ofitemsasthefirstlineofthefile.ButamorecommontechniqueistheoneIhaveusedhere:justusea
loopthatrepeatsuntilwereachtheendofthefile.
The.hasNext()methodoftheScannerobjectwillreturntrueifthereismoredatathathasntbeen
readinyet.Anditreturnsfalseifthereisnomoredata.Soonline18wecreateawhileloopthat
repeatsaslongas.hasNext()continuestoreturntrue.
Beforewelookatline20letusskipdowntolines27through35whereIhavecreatedafunctionthat
willreadallthedataforasingleActorrecordfromthefile.
ThefunctioniscalledgetActor.Ithasoneparameter:aScannerobject!Thatsright,youpassinan
alreadyopenScannerobjecttothefunctionanditreadsfromit.AndthegetActorfunctionreturnsan
Actor.Itreturnsanentirerecord.
IfwearegoingtoreturnanActorobjectfromthefunctionweneedavariableoftypeActorto
return,sowedefineoneonline29.Ijustcalleditabecauseinsidethefunctionwedontknowanything
aboutthepurposeofthisvariable.Youshouldgivegoodnamestovariablesbutinasituationlikethisa
short,meaninglessnamelikeaisperfectlyfine.
Lines30through32readthreelinesfromthetextfileandstorethemintothethreefieldsoftherecord.
Thenthefunctionhasdoneitsjobandwereturntherecordbackuptoline20inmain().
WhymustwecreateanActorvariablenamedahereinmain()andalsodowninthefunction?
Becauseofvariablescope.Avariableisonlyinscope(akavisible)withintheblockinwhichitwas
declared.Period.Itdoesntmatterifthevariableisreturnedfromafunctionornotbecauseremember
itisnotthevariableitselfwhichisreturnedbutacopyofthevalueofthevariable.
ThereisanActorvariablecalledadeclared(anddefined)online20inmain(),butthatvariable
goesoutofscopewhentheclosecurlybraceoccursonline23.ThereisadifferentActorvariable
calledadeclared(anddefined)online29inthegetActor()function,butitgoesoutofscopewhen
theclosecurlybraceoccursonline35.
Okay,backtoline20.ThevariableagetsitsvaluefromthereturnvalueofthefunctiongetActor().
WepassintheopenScannerobjectinFileastheargumenttothefunctionanditreturnstousanActor
objectwithallitsfieldsfilledin.
(WhyistheargumentcalledinFileandtheparameternamedinput?Becausetheyarenotthesame
variable.Theparameterinputisdeclaredonline27andgetsacopyofthevaluefromtheargument
inFile.Theyaretwodifferentvariablesthathavethesamevalue.)
Afterallthat,lines21and22areprettyboring:theysimplydisplaythevaluesofallthefieldsofthe
record.Online23thelooprepeatsbackuptochecktheconditionagain:nowthatwehavereadanother
recordfromthefile,doesthefilestillhavemore?Ifso,keeplooping.Ifnot,skipdowntoline24where
weclosethefile.
Noticethatbothinthefunctionandinthewhileloopinmain()thevariableaonlyholdsonerecord
atatime.Wereadalltherecordsfromthefileandprintthemalloutonthescreen,butwhenthe
programisfinishingitslasttimethroughtheloop,thevariableaonlyholdsthemostrecentrecord.All
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<db.length;i++)
31{
32System.out.println("Name:"+db[i].name);
33System.out.println("\tCredithours:"+db[i].credits);
34System.out.println("\tGPA:"+db[i].gpa+"\n");
35}
36
37intmax=0;
38for(inti=1;i<db.length;i++)
39if(db[i].gpa>db[max].gpa)
40max=i;
41
42System.out.println(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
ofwhatever.Infact,sincethisbookisalmostover,maybeIshouldexplainthatpublicstatic
voidmainbusiness.Atleastpartially.
publicstaticvoidmain(String[]args)
Thislinedeclaresafunctionnamedmain.Thatfunctionrequiresoneparameter:an
arrayofStringsnamedargs(whichisshortforarguments).Thefunctiondoesnt
returnanyvalue;itisvoid.
Anyway.
Line12declaresdbasavariablethatcanholdanarrayofStudents.Theresnoarrayyet,justa
variablethatcanpotentiallyholdone.Justlikewhenwesay
intn;
theresnointegeryet.Thevariablencanpotentiallyholdaninteger,buttheresnonumberinityet.n
isdeclaredbutundefined.Inthesameway,onceline12hasfinishedexecuting,dbisavariablethat
couldrefertoanarrayofStudents,butisstillundefined.
Fortunatelywedonthavetowaitlong;line13initializesdbbycreatinganactualarrayofStudentswith
threeslots.Atthispointdbisdefined,db.lengthis3anddbhasthreelegalindexes:0,1and2.
Okay,atthispoint,dbisanarrayofStudentrecords.Exceptthatitisnt.dbisanarrayofStudent
variables,eachofwhichcanpotentiallyholdaStudentrecord,butnoneofwhichdo.Allthreeslotsin
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
db.name error thewholearraydoesnthaveasinglenamefield

Soline16storesavalueintothenamefieldofthefirstrecordinthearray.Lines17and18storevalues
intotheremainingfieldsinthatrecord.Lines20through28createthenfilltheothertworecordsinthe
array
Onlines30though34weusealooptodisplayallthevaluesonthescreen.
Thenlines37through42findthestudentwiththehighestGPA.Thisisworthexplaininginmoredetail.
Online37anintcalledmaxisdefined.ButmaxisnotgoingtoholdthevalueofthehighestGPA;itis
goingtoholdonlyitsindex.
SowhenIput0intomaxImeanAsthispointinthecode,asfarasIknow,thehighestscoringstudent
isinslot0.Thisisprobablynottrue,butsincewehaventlookedatanyofthevaluesinthedatabase
yetitisasgoodastartingplaceasany.
Thenonline38wesetupthelooptolookthrougheachslotofthearray.Notice,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,maxcontainstheindexoftherecordwiththehighestGPA.Whichis
exactlywhatwedisplayonline42.

StudyDrills
1. Changethearraytohaveacapacityof4insteadof3.Changenothingelseandcompileandrun
theprogram.Doyouunderstandwhytheprogramblowsup?
2. Nowaddsomemorecodetoputvaluesintothefieldsforyournewstudent.Givethisnew
studentahigherGPAthanDaveandconfirmthatthecodecorrectlylabelsthemashavingthe
highestGPA.
3. Changethecodesothatitfindsthepersonwiththefewestcreditsinsteadofthepersonwiththe
highestGPA.
Exercise56:ArrayofRecordsfromaFile(Temperatures
Revisited)
ThisexercisepopulatesanarrayofrecordsfromafileontheInternet.Bynowyoushouldknowifyou
needtodownloadacopyofthisfileorifyourcomputercanjustopenitfromtheInternet.
http://learnjavathehardway.org/txt/avgdailytempswithdatesatx.txt

UnlikealltheotherfilesyouhaveusedsofarinthisbookthisdatafileisexactlythewayIdownloaded
itfromtheUniversityofDaytonsaveragedailytemperaturearchive.Thismeansthreethings:
1. Thereisnonumberinthefirstlineofthefiletellingushowmanyrecordsthereare.
2. Inadditiontothetemperatureeachrecordalsohasthemonth,dayandyearforthesample.
3. Thereisbaddatainthefile.Inparticular,Weuse99asanodataflagwhendataarenot
available.
Sosomedayshaveatemperatureof99.Wewillhavetohandlethisinthecode.
1importjava.util.Scanner;
2
3classTemperatureSample
4{
5intmonth,day,year;
6doubletemperature;
7}
8
9publicclassTemperaturesByDate
10{
11publicstaticvoidmain(String[]args)throwsException
12{
13Stringurl=
"http://learnjavathehardway.org/txt/avgdailytempswithdatesatx.txt";
14ScannerinFile=newScanner((newjava.net.URL(url)).openStream());
15
16TemperatureSample[]tempDB=newTemperatureSample[10000];
17intnumRecords,i=0;
18
19while(inFile.hasNextInt()&&i<tempDB.length)
20{
21TemperatureSamplee=newTemperatureSample();
22e.month=inFile.nextInt();
23e.day=inFile.nextInt();
24e.year=inFile.nextInt();
25e.temperature=inFile.nextDouble();
26if(e.temperature==99)
27continue;
28tempDB[i]=e;
29i++;
30}
31inFile.close();
32numRecords=i;
33
34System.out.println(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);
49System.out.println("Averagedailytemperatureover"+count+"days
inNovember:"+avg);
50}
51
52publicstaticdoubleroundToOneDecimal(doubled)
53{
54returnMath.round(d*10)/10.0;
55}
56}

WhatYouShouldSee
6717dailytemperaturesloaded.
Averagedailytemperatureover540daysinNovember:59.7
Lines3through7declareourrecord,whichwillstoreasingleaveragedailytemperaturevalue(a
double)butalsohasfieldsforthemonth,dayandyear.
Line16definesanarrayofrecords.Wehaveaproblem,though.Wecantdefineanarraywithout
providingacapacityandwedontknowthecapacityweneeduntilweseehowmanyrecordsareinthe
file.Therearethreepossiblesolutionstothisproblem:
1. Dontuseanarray.Usesomethingelselikeanarraythatcanautomaticallygrowasyouadd
entries.Thisisactuallyprobablytherightsolution,butthatsomethingelseisbeyondthescope
ofthisbook.
2. Readthefiletwice.Doitoncejusttocountthenumberofrecordsandthencreatethearraywith
theperfectsize.Thenreaditagaintoslurpallthevaluesintothearray.Thisworksbutitsslow.
3. Dontworryaboutmakingthearraytherightsize.Justmakeitbigenough.Thencounthow
manyrecordsyouactuallyhavewhilereadingtheminandusethatcountinsteadofthearrays
capacityforanyloops.Thisisnotperfect,butitworksanditseasy.Writingsoftwaresometimes
requirescompromise,andthisisoneofthem.
Soline16declaresthearrayanddefinesittohavetenthousandslots:bigenough.
Online19westartalooptoreadallthevaluesfromthefile.Weareusinganindexvariableitokeep
trackofwhichslotinthearrayneedstobefillednext.Soourloopkeepsgoingaslongasthefilehas
moreintegersinitandwehaventrunoutofcapacityinourarray.
Justbecausewetookashortcutbymakingourarraybigenoughdoesntmeanwearegoingtobe
stupidaboutit.Ifthefileendedupbiggerthanourarrayscapacitywewanttostopreadingthefiletoo
earlyratherthanblowuptheprogramwithanArrayIndexOutOfBoundsexception.
Line21definesaTemperatureSamplerecordnamede.Lines22through25loadthenextfewvalues
fromthefileintotheappropriatefieldsofthatrecord.
But!Rememberthattherearemissingvaluesinourfile.Somedayshaveatemperaturereadingof
99,soweputinanifstatementonline26todetectthatbeforeweputthemintoourdatabase.
Thenonline27thereissomethingnew:theJavakeywordcontinue.continueisonlylegalinside
thebodyofaloop.Anditmeansskiptherestofthelinesofcodeinthebodyoftheloopandjustgo
backuptothetopforthenextiteration.
Thiseffectivelythrowsawaythecurrent(invalid)recordbecauseitskipslines28and29,whichstore
thecurrentrecordinthenextavailableslotinthearrayandthenincrementtheindex.
Somepeopledontliketousecontinueandwouldwriteitlikethis:
if(e.temperature!=99)
{
tempDB[i]=e;
i++;
}
Andthatsperfectlyfine,too.Onlyputthisentryintothearraywhenthetemperatureisnot99.I
preferusingcontinuebecausethecodefeelscleanertomebutreasonablepeopledisagree.Do
whichevermakesthemostsensetoyou.
Oncetheloopisdoneonline31wemakesuretoclosethefileandthenstorethefinalindexinto
numRecordssowecanuseitinsteadoftempDB.lengthforanyloops.Afterall,wemadethearray
biggerthanweneededandthelast3283slots(inthisexample)areempty.Notonlyisloopingonlyupto
numRecordsslightlymoreefficient,wecanavoidexamininganyinvalidrecordsthatway.
Online34wedisplaythenumberofrecordsonthescreen,whichcanhelpyoutoseeifanythingwent
wrongwhilereading.
Lines36through45loopthroughallourrecords.Anyrecordwithamonthfieldof11(November)gets
addedtoarunningtotal,andwealsocountthetotalnumberofmatchingrecordswhileweareatit.
Thenwhenthatloopisover,wecangettheaveragedailytemperatureofallNovemberdaysinthe
databasebydividingthesumbythecount.
Now,myfirstversionofthisprogramhadanoverallaveragetemperatureof59.662962962963.Not
onlydoesthislookbadbutitsnotcorrect:alltheinputtemperatureswereonlyaccuratetoatenthofa
degree.Sodisplayingaresultwithadozensignificantfigureslooksmoreaccuratethanitreallyis.
Soonlines52through55youwillfindatinylittlefunctiontoroundtoonedecimalplace.Javadoesnt
haveabuiltinfunctionforthisasfarasIknow,butitdoeshaveabuiltinfunctiontoroundtothe
nearestwholenumber:Math.round().SoImultiplythenumberbyten,rounditandthendivideby
tenagain.MaybetheresabetterwaytodothatbutIlikeit.
Line48passestheaveragetemperatureastheargumenttomyfunctionandthentakestherounded
returnvalueandstoresthatasthenewvalueofavg.

StudyDrills
1. VisittheUniversityofDaytonstemperaturearchiveanddownloadafilewithtemperaturedata
foracitynearyou!Makeyourcodereaddatafromthatfileinstead.
2. Changethecodetofindoutotherthings,likethehighesttemperatureinFebruaryorwhatever
suitsyourfancy.
3. TryprintinganentireTemperatureSamplerecordonthescreen.Somethinglikethis:
TemperatureSamplets=tempDB[0];
System.out.println(ts);
Noticethatisntprintinganintegerlikets.yearoradoublelikets.temperature;itisattempting
todisplayawholerecordonthescreen.Compileandrunthefile.Whatgetsdisplayedonthescreen?
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)(Math.random()*deck.length);
21Cardpicked=deck[chosen];
22
23System.out.println("Youpickeda"+picked+"outofthedeck.");
24System.out.println("InBlackjackyourcardisworth"+picked.value+"
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();
41c.suit=s;
42c.name=names[v];
43if(v==14)
44c.value=11;
45elseif(v>10)
46c.value=10;
47else
48c.value=v;
49
50deck[i]=c;
51i++;
52}
53}
54returndeck;
55}
56
57publicstaticvoiddisplayDeck(Card[]deck)
58{
59for(Cardc:deck)
60System.out.println(c.value+"\t"+c);
61}
62}
WhatYouShouldSee
Youpickedasevenofheartsoutofthedeck.
InBlackjackyourcardisworth7points.
Ofcourse,eventhoughthisisalmostthefinalexercise,Icantresistsneakinginsomemorenewthings
in.Youwanttolearnsomethingnew,dontyou?
Firstofall,Isnuckafunctionintotherecord.(Actually,becausethisfunctionisinsideaclassitisnta
functionbutamethod.)
ThismethodisnamedtoString.IthasnoparametersandreturnsaString.Inthebodyofthismethod
wecreateaStringbyconcatenatingthenamefield,thesuitfield,andtheword"of".Themethod
doesntneedanyparametersbecauseithasaccesstothefieldsoftherecord.(Infact,thatiswhatmakes
itamethodandnotafunction.)
Otherwise,theCardrecordishopefullywhatyouwouldexpect:ithasfieldsforthevalueofthecard
(211),thesuitnameandthenameofthecarditself.
Onlines17though24youcanseethemain(),whichisreallyshort.Line17declaresanarrayofcards
andinitializesitusingthereturnvalueofthebuildDeck()function.
Line18iscommentedout,butwhenIwaswritingthisprogramoriginallyIusedthedisplayDeck()
functiontomakesurethatbuildDeck()wasworkingcorrectly.
Line20choosesarandomnumberbetween0anddeck.length1.Youmightnoticethatthisis
exactlytherangeoflegalindexesintothearray,andthatisnotacoincidence.
Infact,youcouldalsosaythatline20choosesarandomindexintothearrayorthatline20choosesa
slotofthearrayrandomly.
Thenonline21wedeclareanewCardvariablecalledpickedandgiveitavaluefromthe
randomlychosenslotofthearray.
Line23looksprettyboringbutthereisactuallymagichappening.Whattypeofvariableispicked?Itis
aCard.Normallywhenyoutrytoprintanentirerecordonthescreenlikethis,Javadoesntknowwhich
fieldsyouwantprintedorinwhatordersoitjustprintsgarbageonthescreen.(Yousawthatinthe
StudyDrillforthepreviousexercise,right?)
ButifyouprovideamethodcalledtoString()insideyourrecord,whichreturnsaStringandhas
noparameters,theninasituationlikethisJavawillcallthatmethodbehindthescenes.Itwilltakethe
returnvalueandprintthatoutinsteadofgarbage.
Soline23willprintonthescreentheresultofrunningthepickedcardstoString()method.
Bycontrast,line24reallyisboring.Itprintsoutthevaluefieldofthechosencard.
BeforewegettobuildDeck(),whichisthemostcomplexpartofthisexercise,letusskipdownto
thedisplayDeck()function.displayDeck()expectsyoutopassinanarrayofCardsasan
argument.
Thenonline59weseesomethingwehaventseenforafewexercises:aforeachloop.Thissaysfor
eachCardcinthedeckAndsincethereisonlyonelineofcodeinthebodyofthisforloop,I
omittedthecurlybraces.
Line60displaysthevalueofthecurrentcard,atab,andthentheresultofcallingthetoString()
methodonbehalfofCardc.
Okay,letustacklethisbuildDeck()function.buildDeck()doesntneedanyparametersbecause
itjustcreatesthedeckoutofnothing.Itdoesreturnavalue,though:anarrayofCards.
Onlines29through31wecreatetwoarraysofStrings.Thefirstone(online29)containsthenamesof
thesuits.Thesecondonecontainsthenamesofthecards.
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).
Line36isanotherforeachloop.Thevariablesisgoingtobesetequalto"clubs",then
"diamonds",then"hearts"andthenfinally"spades".
Line38isanotherforloopbutthisoneisnested.Rememberthatmeansthatthisloopisgoingtomake
vgofrom2through14beforetheouterloopeverchangessfrom"clubs".
Line40definesaCardnamedc.Online41wesetthesuitfieldofthiscardtowhatevervalueis
currentlyins("clubs",atfirst).
Dependingonwhichtimethroughtheloopthisis,vwillbesomevaluebetween2and14,soonline42
weusevasanindexintothenamesarray.Thatis,whenvis5wegointothesixth(!)slotofthearray,
wherewewillfindtheString"five".Weputacopyofthisvalueintothenamefieldofthecurrent
card.
Lines43through48storeanintegerfrom2to11intothevaluefieldofthecurrentcard.Weneededv
togofrom214forourlookuptable,butnowthatthatisalreadydone,weneedtomakesurethatno
cardgetsavalueof1214.
Cardnumber14istheace,soweuse11forthecardvalue.Thencardnumbers11,12and13arethe
facecards,sotheyallhave10fortheircardvalues.Andanyothercardvalueisfineasis.
Finallywestorethiscardintothenextavailableslotofthedeck(indexedwithi)andmakeibiggerby1.
Whenthenestedloopsfinishedwehavesuccessfullycreatedall52cardsinastandarddeckandgiven
themcardvaluesthatmatchhowtheyareusedinBlackjack.UncommentthecalltodisplayDeck()
online18ifyouwanttobesure.
ThelastthingthatbuildDeck()needstodoisreturnthenowfullarrayofCardssoitcanbe
storedintothedeckvariableonline17ofmain().

StudyDrills
1. AddafunctioncalledshuffleDeck().Itshouldtakeinanarrayofcardsasaparameterand
returnanarrayofcards.Onewaytoshuffleistochoosetworandomnumbersfrom051and
swapthecardsinthoseslots.Thenputthatcodeinaloopthatrepeats1000timesorso.Thisis
abittrickytogetright.
Exercise58:FinalProjectTextAdventureGame
Ifyouhavedonealltheexercisesuptothispoint,thenyoushouldbereadyforthisfinalproject.Itis
longerthananyotherexercisethatyouhavedone,butitisntmuchmoredifficultthanthelastfew.
Yourfinalexerciseisatextbasedadventuregameengine.ByengineImeanthatthecodedoesntknow
anythingabouttheadventureitself;thegameisdetermined100%bywhatisinthefile.Changethefile
andyouchangethegameplay.
Sostartbydownloadingacopyofthegamedatafileandsavingitintothesamefolderasyouaregoing
toputyourcode.
http://learnjavathehardway.org/txt/textadventurerooms.txt

Then,bettergetstartedtyping.Thisisalongone,butIthinkitwillbeworthit.
1importjava.util.Scanner;
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(System.in);
18
19//initializeroomsfromfile
20Room[]rooms=loadRoomsFromFile("textadventurerooms.txt");
21
22//showAllRooms(rooms);//fordebugging
23
24//Okay,solet'splaythegame!
25intcurrentRoom=0;
26Stringans;
27while(currentRoom>=0)
28{
29Roomcur=rooms[currentRoom];
30System.out.print(cur.description);
31System.out.print(">");
32ans=keyboard.nextLine();
33
34//Seeifwhattheytypedmatchesanyofourexitnames
35booleanfound=false;
36for(inti=0;i<cur.numExits;i++)
37{
38if(cur.exits[i].equals(ans))
39{
40found=true;
41//ifso,changeournextroomtothatexit'sroomnumber
42currentRoom=cur.destinations[i];
43}
44}
45if(!found)
46System.out.println("Sorry,Idon'tunderstand.");
47}
48
49}
50
51publicstaticRoom[]loadRoomsFromFile(Stringfilename)
52{
53Scannerfile=null;
54try
55{
56file=newScanner(newjava.io.File(filename));
57}
58catch(java.io.IOExceptione)
59{
60System.err.println("Sorry,Ican'treadfromthefile'"+
filename+"'.");
61System.exit(1);
62}
63
64intnumRooms=file.nextInt();
65Room[]rooms=newRoom[numRooms];
66
67//initializeroomsfromfile
68introomNum=0;
69while(file.hasNext())
70{
71Roomr=getRoom(file);
72if(r.roomNumber!=roomNum)
73{
74System.err.println("Readingroom#"+r.roomNumber+",but
"+roomNum+"wasexpected.");
75System.exit(2);
76}
77rooms[roomNum]=r;
78roomNum++;
79}
80file.close();
81
82returnrooms;
83}
84
85publicstaticvoidshowAllRooms(Room[]rooms)
86{
87for(Roomr:rooms)
88{
89StringexitString="";
90for(inti=0;i<r.numExits;i++)
91exitString+="\t"+r.exits[i]+"("+r.destinations[i]+
")";
92System.out.println(r.roomNumber+")"+r.roomName+"\n"+
exitString);
93}
94}
95
96publicstaticRoomgetRoom(Scannerf)
97{
98//anyroomsleftinthefile?
99if(!f.hasNextInt())
100returnnull;
101
102Roomr=newRoom();
103Stringline;
104
105//readintheroom#forerrorcheckinglater
106r.roomNumber=f.nextInt();
107f.nextLine();//skip"\n"afterroom#
108
109r.roomName=f.nextLine();
110
111//readintheroom'sdescription
112r.description="";
113while(true)
114{
115line=f.nextLine();
116if(line.equals("%%"))
117break;
118r.description+=line+"\n";
119}
120
121//finally,we'llreadintheexits
122inti=0;
123while(true)
124{
125line=f.nextLine();
126if(line.equals("%%"))
127break;
128String[]parts=line.split(":");
129r.exits[i]=parts[0];
130r.destinations[i]=Integer.parseInt(parts[1]);
131i++;
132}
133r.numExits=i;
134
135//shouldbedone;returntheRoom
136returnr;
137}
138
139}

WhatYouShouldSee
Thisistheparlor.
It'sabeautifulroom.

Therelookstobeakitchentothe"north".
Andthere'sashadowycorridortothe"east".
>north
Thereisalongcountertopwithdirtydisheseverywhere.Offtooneside
thereis,asyou'dexpect,arefrigerator.Youmayopenthe"refrigerator"
or"goback".
>goback
Thisistheparlor.
It'sabeautifulroom.

Therelookstobeakitchentothe"north".
Andthere'sashadowycorridortothe"east".
>east
Thecorridorhasledtoadarkroom.Themomentyoustepinside,thedoor
slamsshutbehindyou.Thereisnohandleontheinteriorofthedoor.

Thereisnoescaping.Type"quit"todie.
>quit
BeforeIstarttalkingaboutthecode,letmetakeamomenttotalkabouttheadventuregamefile
format.
Thegameconsistsofseveralrooms.Eachroomhasaroomnumberandaroomname;theseareonly
usedforthegameengineandarenevershowntotheplayer.
Eachroomalsohasadescriptionandoneormoreexits,whichisapathtoanotherroom.
Theadventuregamefilestartswithanumber:thetotalnumberoflocations(rooms)inthegame.After
thatarerecordsforeachroom.Heresanexample:
1
KITCHEN
Thereisalongcountertopwithdirtydisheseverywhere.Offtooneside
thereis,asyou'dexpect,arefrigerator.Youmayopenthe"refrigerator"
or"goback".
%%
fridge:3
refrigerator:3
goback:0
back:0
%%
Thefirstlineofthisrecordistheroomnumber,sothisisroomnumber1.Thesecondlineoftherecord
istheroomname,whichweonlyusefordebugging.
Startingwiththethirdlineoftherecordisthedescriptionoftheroom,whichcontinuesuntilthereisa
linewithnothingbut%%onit.Blanklinesareallowedinthedescription.
Afterthefirstdoublepercentthereisalistofexits.Eachlinehasthenameoftheexit(whattheplayer
willtypetotakethatroute)followedbyacolon,followedbytheroomnumberwherethatexitleads.
Forexample,inthisroomiftheplayertypes"fridge"thenthegameenginewillmovethemfrom
thisroom(room#1)intoroom#3.Andiftheytype"goback"thentheywilltraveltoroom#0
instead.YoumaynoticethatinordertomakeiteasierfortheplayertodecidewhattotypeIhave
duplicateexitsinthelist.Eithertheword"fridge"or"refrigerator"willtakethemtoroom
#3.
Thelistofexitsendswithanotherlinecontainingonly%%.Andthatstheendoftherecord.
Okay,nowletsturntothecode.Lines3through11declaretherecordforoneroom.Youcanseewe
havefieldsforeverythingintheadventuregamefile.Theonlythingyoumightnothaveguessedisthat
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
more.Sowewillusethistostopthegame:whentheplayerdies(orwins)wewillsetcurrentRoom
equalto1.
Thearrayroomscontainsalistofallthelocationsinthegame.Thenumberoftheroomcontainingthe
playerisstoredinthevariablecurrentRoom.Sorooms[currentRoom]istheentirerecordforthe
um,currentroom.Inline29westoreacopyofthisroomintotheRoomvariablecur.(Ionlydothis
becauseImlazyandwanttotypethingslikecur.descriptioninsteadof
rooms[currentRoom].description.)
Speakingofwhich,line30printsoutthedescriptionofthecurrentroom,whichisstoredinthe
descriptionfield.
Onlines31and32weprintoutalittlepromptandlettheplayerenterinaStringforwheretheywantto
go.
Lines36through44searchthroughthisroomsarrayofexitslookingtoseeifanyofthemmatchwhat
theplayertyped.Rememberthattheexitsarrayhasacapacityof10,butthereareprobablynotthat
manyexitsactuallypresentinthisroom.SointheforloopwecountuptothevalueofthenumExits
fieldinsteadof10.
Ifwefindanexitthatmatchestheplayerscommand,wesetourflagtotrue(soweknowifweshould
complainiftheyenduptypingsomethingthatsnotinourlist).Thensincethewordsintheexitsarray
lineupwiththeroomnumbersinthedestinationsarray,wepulltheroomnumberoutofthe
correspondingslotofthedestinationsarrayandmakethatournewroomnumber.Thisway,whenthe
maingamelooprepeatsagain,wewillhaveautomaticallytraveledtothenewroom.
Online45wecheckourflag.Ifitsstillfalse,itmeansthehumantypedsomethingweneverfoundin
thelistofexits.Wecanpolitelycomplain.BecausecurrentRoomhasntchanged,loopingaroundagain
inthemaingameloopwilljustprintoutthedescriptionagainfortheroomtheywerealreadyin.
Andthatstheendofthemaingameloopandtheendofmain().Allthatsleftistoactuallyfillupthe
arrayofroomsfromtheadventuregamefile.
Line51isthebeginningoftheloadRoomsFromFile()function,whichtakesthefilenametoopen
asaparameterandreturnsanarrayofRooms.
(IdecidedthatIdidntwanttohavethrowsExceptionanywhereinthisfile,sotheresatrycatch
blockhere.Itopensthefile.
Ifwemakeitdowntoline64itmeansthefilewasopenedsuccessfully.Wereadinthefirstlineofthe
filetotellushowmanyroomsthereare.Thenline65definesanarrayofRoomrecordswiththe
appropriatecapacity.
Online68ImadeavariablecalledroomNum,whichhasadualpurpose.Firstofall:itistheindexfor
thenextavailableslotintheroomarray.Butsecondly,itisusedtodoublecheckthattheroomnumber
(fromthefile)andtheslotnumberoftheroomarethesame.Ifnot,theresprobablysomesortoferror
inthegamesdatafile.Ifwedetectsuchanerror(online72),wecomplainandendtheprogram.
(System.exit()endstheprogram,evenfrominsideafunctioncall.)
Line69isthebeginningofthereadallroomsloop.Itkeepsgoingaslongasthereisstuffinthefile
wehaventseenyet.Theresapotentialerrorhere:ifthenumberofroomsatthetopofyourdatafileis
alie,thenthisloopcouldgotoofarinthearrayandblowup.(Forexample,ifthefirstlineofthefile
saysyouonlyhave7roomsbutthenyouhave8roomrecordsthenthisloopwillrepeattoomany
times.)
Online71wegetreadasingleroomrecordusingthegetRoom()functionIllexplainlater.
Lines72through76aretheroomnumbersanitycheckIalreadymentioned,andthenline77juststores
thisnewroomintothenextavailableslotintheroomsarray.Andline78incrementstheroomindex.
Afterthatloopisover,alltheroomshavebeenreadinfromthefileandstoredeachintotheirownslot
ofthearray.Soonline82wecanreturnthearrayofroomsbackuptoline20ofmain().
Lines85through94aretheshowAllRooms()functionthatIusefordebugging.Itjustdisplaysall
theroomsinthearrayonthescreen,andforeachroomitalsoshowsalltheexitsandwheretheylead.
OurfinalfunctionisgetRoom(),whichexpectsaScannerobjecttobepassedinasaparameterand
whichreturnsasingleRoomobject.
Onlines99and100thereisasimplesanitycheckincasethereisamalformatteddatafile.Ifthenext
thinginthefileisnotaninteger,thenjustreturnnull(thevalueofanuninitializedobject).Puttinga
returnupherewillreturnfromthefunctionrightawaywithoutbotheringtorunanyoftheremaining
code.
Online102theemptyroomobjectisdefined.Line103createsaStringcalledline,whichIusefora
coupleofdifferentthings.
Line106readsintheroomnumberfromthefile.Theroomnumberisthefirstpartoftheroomrecord.
TherestofthisfunctionisgoingtouseonlytheScannerobjectsnextLine()method,anda
nextLine()afteranextInt()usuallydoesntworkbecauseitreadsonlytheendofthelineafter
theintegerthatwasjustread.
Soline107callsthenextLine()methodbutdoesntbothertostoreitsreturnvalueanywhere
becauseitdoesntreadanythingworthsaving.
Line109readsintheroomnamefromthefile.Weonlyusethisfordebugging.
Online112westartbysettingthisroomsdescriptionfieldtoanemptyString.Thisissowecanaddon
toitwithoutgettinganerror.(Justlikewewouldsetatotalvariableto0beforeaddingtoitinaloop.)
Okay.SoIlikewritinginfiniteloops.Sueme.Line113isthebeginningofaninfiniteloop.Thisis
becausewedontknowhowmanylinesaregoingtobeintheroomsdescription;itjustgoeshowever
longuntilweseealineconsistingofnothingbut%%.Thereareotherwaystodothis,butIlikethe
writeaninfiniteloopandthenbreakoutofitwhenyouseewhatyourelookingforapproach.Like
Ivesaidbefore,reasonablepeopledisagree.
Oncewereinsidetheinfiniteloop,wereadalineofdescriptionintothelinevariable.Then,online
116wechecktoseeifwhatwejustreadwas%%.Ifso,wedontwanttoaddittothedescriptionsowe
breakoutoftheloop.breakissortofliketheoppositeofcontinue;continueskipsbackupto
theconditionofaloopandbreakjustskipstotheendandstopslooping.
Ifwerestillaroundtoseeline118,itmeansthatwereadinalineofdescriptionanditwasnt%%.So
weuse+=toaddthatline(anda\n)totheendofwhateverwasalreadyinthedescriptionfield.And
thelooprepeats.(Nomatterwhat.)
Eventuallywehopefullyhita%%andtheloopstopslooping.
Line122definesi,whichIusefortheindexofwhichslotintheexitsanddestinationsarrayswere
goingtoputsomethinginnext.Andthenstartingonline123theresanotherinfiniteloop.Iuseavery
similarapproachtoreadinalltheexits.
Line125readsinthewholeline,whichmeansthatlinecontainssomethinglike"refrigerator:3".
(Ifitsnotsomethinglikethatbutisactually%%,lines126and127stoplooping.)
Sonowweneedtosplitthislineintotwoparts.Fortunatelyforus,theStringclasshasabuiltin
methodcalledsplit().
line.split(":")searchesthroughtheStringlineandbreaksitupeverytimeitseesa:(colon).
AndthenitreturnsanarrayofStrings.Forexample,iflinecontainedthisXisXaXtestthen
line.split("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),Javasstandardlibrarycomestotherescue.Thereisabuiltinfunctionto
convertaStringtoaninteger:Integer.parseInt().Weusethisonline130.
Recallthatiistheindexoftheslotintheexitsarraywhereweneedtostorethenextvalue.Soline129
storesparts[0](thenameoftheexit)intotheappropriateslotoftheexitsarray.Andline130
convertsparts[1](theroomnumbertomoveto)fromaStringtoanintandstoresthatinthesame
slotofthedestinationsarray.Thenline131incrementstheexitindexforthenextgoaround.
Eventuallywewillhita%%andthisloop,too,willstoplooping.Thereisapotentialbughere,however.
Theexitsarrayonlyhastenslots.Ifthedatafilehasaroomwithmorethantenexits,thisloopwilljust
keepongoingpasttheendofthearrayandblowuptheprogram.Sodontdothat.
Aftertheloopends,thenourindexiwillcontainthetruenumberofroomsthatwereadin.Sowestore
thatintothenumExitsfieldofthecurrentroomonline133.
Andthatshouldbeit.Allthefieldsintheroomhavebeengivenvalues,andwereturnthisRoom
objecttoline71oftheloadRoomsFromFile()function.

StudyDrills
1. Writeyourowntextadventure.Ifyouthinkitturnsoutprettygood,emailittome!
2. Addasavegamefeature,sothattheplayercantypesomethingtostopthegame,andthegame
willstoretheircurrentroomnumbertoatextfileandthenloaditbackupwhenthegamebegins
again.

Вам также может понравиться