M M M
Data Structures and Al
M M M
gorithms in Java, 6eMi
M M M M
chael Goodrich, Rober
M M
to Tamassia (AllChapt
M M M
ers)
, Chapter
1 Java Primer
M
HintsMandMSolutions
Reinforcement
R-
1.1)M HintM UseM theM codeM templatesM providedM inM theM SimpleM Input
M andMOutputMsection.
R-1.2)MHintMYouMmayMreadMaboutMcloningMinMSectionM3.6.
R-
1.2)MSolutionMSince,MafterMtheMclone,MA[4]MandMB[4]MareMbothMpointi
ngMtoMtheMsameMGameEntryMobject,MB[4].scoreMisMnowM550.
R-1.3)MHintMTheMmodulusMoperatorMcouldMbeMusefulMhere.
R-1.3)MSolution
publicM booleanM isMultiple(longM n,MlongM m)M {
returnM(n%mM==M0);
}
R-1.4)MHintMUseMbitMoperations.
R-1.4)MSolution
publicMbooleanMisEven(intMi)M{
returnM (iM&M1M==M0);
}
R-
1.5)MHintMTheMeasyMsolutionMusesMaMloop,MbutMthereMisMalsoMaMform
ulaMforMthis,MwhichMisMdiscussedMinMChapterM4.
R-1.5)MSolution
publicMintMsumToN(intMn)M{
intMtotalM=M0;
forM(intMj=1;MjM<=Mn;Mj+
+)MtotalM+=Mj;
returnMtotal;
}
,2 ChapterM1.M JavaMPri
mer
R-1.6)MHintMTheMeasyMthingMtoMdoMisMtoMwriteMaMloop.
R-1.6)MSolution
publicMintMsumOdd(intMn)M{
intMtotalM=M0;
forM(intMj=1;MjM<=Mn;MjM+=
M2)MtotalM+=Mj;
returnMtotal;
}
R-1.7)MHintMTheMeasyMthingMtoMdoMisMtoMwriteMaMloop.
R-1.7)MSolution
publicMintMsumSquares(intMn)M{
intMtotalM=M0;
forM(intMj=1;MjM<=Mn;Mj+
+)MtotalM+=Mj∗j;
returnMtotal;
}
R-1.8)MHintMYouMmightMuseMaMswitchMstatement.
R-1.8)MSolution
publicMintMnumVowels(StringMtext)M{
intMtotalM=M0;
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;
}
}
returnMtotal;
}
R-1.9)MHintMConsiderMeachMcharacterMoneMatMaMtime.
, 3
R-
1.10)MHintMConsiderMusingMgetMandMsetMmethodsMforMaccessingMandM
mod-MifyingMtheMvalues.
R-
1.11)M HintM TheM traditionalM wayM toM doM thisM isM toM useM setFooM method
s,MwhereMFooMisMtheMvalueMtoMbeMmodified.
R-1.11)MSolution
publicMvoidMsetLimit(intMlim)M{
limitM=Mlim;
}
R-1.12)MHintMUseMaMconditionalMstatement.
R-1.12)MSolution
publicMvoidMmakePayment(doubleMamount)M{
ifM(amountM>M0)Mbal
anceM−=Mamount;
}
R-1.13)M HintM TryMtoM makeM wallet[1]MgoM overM itsM limit.
R-1.13)MSolution
forM(intMval=1;MvalM<=M58;Mval++
)M{Mwallet[0].charge(3∗val);Mwall
et[1].charge(2∗val);Mwallet[2].c
harge(val);
}
ThisM changeM willM causeM wallet[1]MtoM attemptM toM goM overM itsM limit.
Creativity
C-1.14)MHintMTheMJavaMmethodMdoesMnotMneedMtoMbeMpassedMtheMvalueMofMn
asManMargument.
C-
1.15)MHintMNoteMthatMtheMJavaMprogramMhasMaMlotMmoreMsyntaxMre
quire-Mments.
C-
1.16)MHintMCreateManMenumMtypeMofMallMoperators,MincludingM=,Ma
ndMuseManMarrayMofMtheseMtypesMinMaMswitchMstatementMnestedMinsid
eMfor-loopsMtoMtryMallMpossibilities.
C-
1.17)MHintMNoteMthatMatMleastMoneMofMtheMnumbersMinMtheMpairMm
ustMbeMeven.
C-1.17)MSolution