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 and
mOutputmsection.
R-1.2)mHintmYoummaymreadmaboutmcloningminmSectionm3.6.
R-
1.2)mSolutionmSince,maftermthemclone,mA[4]mandmB[4]marembothmpointingmt
omthemsamemGameEntrymobject,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,mbutmtheremismalsomamformulamfo
rmthis,mwhichmismdiscussedminmChapterm4.
R-1.5)mSolution
publicmintmsumToN(intmn)m{
intm totalm=m 0;
form(intmj=1;mjm<=mn;mj++)mt
otalm+=mj;
returnm total;
}
,2 Chapter 1. Java Primer
R-1.6)mHintmThemeasymthingmtomdomismtomwritemamloop.
R-1.6)mSolution
publicmintmsumOdd(intmn)m{
intm totalm=m 0;
form(intmj=1;mjm<=mn;mjm+=m2
)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)mHintmConsidermusingmgetmandmsetmmethodsmformaccessingmandmmod-
mifyingmthemvalues.
R-
1.11)m HintmThemtraditionalm waym tom dom thism ism tomusem setFoom methods,
mwheremFoomismthemvaluemtombemmodified.
R-1.11)mSolution
publicmvoidmsetLimit(intmlim)m{
limitm=mlim;
}
R-1.12)mHintmUsemamconditionalmstatement.
R-1.12)mSolution
publicmvoidmmakePayment(doublemamount)m{
ifm(amountm>m0)mbalan
cem−=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)mHintmNotemthatmthemJavamprogrammhasmamlotmmoremsyntaxmrequire-
mments.
C-
1.16)mHintmCreatemanmenummtypemofmallmoperators,mincludingm=,mandmuse
manmarraymofmthesemtypesminmamswitchmstatementmnestedminsidemfor-
loopsmtomtrymallmpossibilities.
C-
1.17)mHintmNotemthatmatmleastmonemofmthemnumbersminmthempairmmustmbem
even.
C-1.17)mSolution