M M M
ata Structures and Alg
M M M
orithms in Java, 6e Mic
M M M M
hael Goodrich, Robert
M M
o Tamassia (All Chapte
M M M
rs)
, Chapter
1 Java Primer
M
Hints and Solutions
M M
Reinforcement
R-
1.1)M HintMUseM theM codeM templatesM providedM inM theM SimpleM InputM
andMOutputMsection.
R-1.2)MHintMYouMmayMreadMaboutMcloningMinMSectionM3.6.
R-
1.2)MSolutionMSince,MafterMtheMclone,MA[4]MandMB[4]MareMbothMpointin
gMtoMtheMsameMGameEntryMobject,MB[4].scoreMisMnowM550.
R-1.3)MHintMTheMmodulusMoperatorMcouldMbeMusefulMhere.
R-1.3)MSolution
publicMbooleanMisMultiple(longMn,MlongMm)M{
returnM(n%mM==M0);
}
R-1.4)MHintMUseMbitMoperations.
R-1.4)MSolution
publicMbooleanMisEven(intMi)M{
returnM (iM &M 1M ==M 0);
}
R-
1.5)MHintMTheMeasyMsolutionMusesMaMloop,MbutMthereMisMalsoMaMformul
aMforMthis,MwhichMisMdiscussedMinMChapterM4.
R-1.5)MSolution
publicMintMsumToN(intMn)M{
intM totalM=M 0;
forM(intMj=1;MjM<=Mn;Mj++)Mt
otalM+=Mj;
returnM total;
}
,2 ChapterM1.M JavaMPrim
er
R-1.6)MHintMTheMeasyMthingMtoMdoMisMtoMwriteMaMloop.
R-1.6)MSolution
publicMintMsumOdd(intMn)M{
intM totalM=M 0;
forM(intMj=1;MjM<=Mn;MjM+=M
2)MtotalM+=Mj;
returnM total;
}
R-1.7)MHintMTheMeasyMthingMtoMdoMisMtoMwriteMaMloop.
R-1.7)MSolution
publicMintMsumSquares(intMn)M{
intM totalM=M 0;
forM(intMj=1;MjM<=Mn;Mj++)Mt
otalM+=Mj∗j;
returnM total;
}
R-1.8)MHintMYouMmightMuseMaMswitchMstatement.
R-1.8)MSolution
publicMintMnumVowels(StringMtext)M{
intM totalM=M 0;
forM(intMj=0;MjM<Mtext.length();Mj++)M{
switchM(text.charAt(j))M{
caseM'a':
caseM'A':
caseM'e':
caseM'E':
caseM'i':
caseM'I':
caseM'o':
caseM'O':
caseM'u':
caseM'U':Mtot
alM+=M1;
}
}
returnM total;
}
R-1.9)MHintMConsiderMeachMcharacterMoneMatMaMtime.
, 3
R-
1.10)MHintMConsiderMusingMgetMandMsetMmethodsMforMaccessingMandM
mod-MifyingMtheMvalues.
R-
1.11)M HintMTheMtraditionalM wayM toM doM thisM isM toMuseM setFooM meth
ods,MwhereMFooMisMtheMvalueMtoMbeMmodified.
R-1.11)MSolution
publicMvoidMsetLimit(intMlim)M{
limitM=M lim;
}
R-1.12)MHintMUseMaMconditionalMstatement.
R-1.12)MSolution
publicMvoidMmakePayment(doubleMamount)M{
ifM(amountM>M0)Mbala
nceM− =Mamount;
}
R-1.13)MHintMTryMtoMmakeMwallet[1]MgoMoverMitsMlimit.
R-1.13)MSolution
forM(intMval=1;MvalM<=M58;Mval++)M{Mwallet
[0].charge(3∗val);Mwallet[1].charge(2∗val)
;Mwallet[2].charge(val);
}
ThisMchangeMwillMcauseMwallet[1]MtoMattemptMtoMgoMoverMitsMlimit.
Creativity
C-1.14)MHintMTheMJavaMmethodMdoesMnotMneedMtoMbeMpassedMtheMvalueMofMn
asManMargument.
C-
1.15)MHintMNoteMthatMtheMJavaMprogramMhasMaMlotMmoreMsyntaxMrequ
ire-Mments.
C-
1.16)MHintMCreateManMenumMtypeMofMallMoperators,MincludingM=,Mand
MuseManMarrayMofMtheseMtypesMinMaMswitchMstatementMnestedMinsideMfor
-loopsMtoMtryMallMpossibilities.
C-
1.17)MHintMNoteMthatMatMleastMoneMofMtheMnumbersMinMtheMpairMmust
MbeMeven.
C-1.17)MSolution