Data Structures and
Algorithms in Java, 6e
Michael Goodrich,
Roberto Tamassia (All
Chapters)
, Chapter
1 Java Primer
J
Hints and Solutions
J J
Reinforcement
R-
1.1)J HintJUseJ theJ codeJ templatesJ providedJ inJ theJ SimpleJ InputJ andJOut
putJsection.
R-1.2)JHintJYouJmayJreadJaboutJcloningJinJSectionJ3.6.
R-
1.2)JSolutionJSince,JafterJtheJclone,JA[4]JandJB[4]JareJbothJpointingJtoJtheJs
ameJGameEntryJobject,JB[4].scoreJisJnowJ550.
R-1.3)JHintJTheJmodulusJoperatorJcouldJbeJusefulJhere.
R-1.3)JSolution
publicJbooleanJisMultiple(longJn,JlongJm)J{
returnJ(n%mJ==J0);
}
R-1.4)JHintJUseJbitJoperations.
R-1.4)JSolution
publicJbooleanJisEven(intJi)J{
returnJ (iJ &J 1J ==J 0);
}
R-
1.5)JHintJTheJeasyJsolutionJusesJaJloop,JbutJthereJisJalsoJaJformulaJforJthis,J
whichJisJdiscussedJinJChapterJ4.
R-1.5)JSolution
publicJintJsumToN(intJn)J{
intJ totalJ=J 0;
forJ(intJj=1;JjJ<=Jn;Jj++)JtotalJ
+=Jj;
returnJ total;
}
,2 ChapterJ1.J JavaJPrimer
R-1.6)JHintJTheJeasyJthingJtoJdoJisJtoJwriteJaJloop.
R-1.6)JSolution
publicJintJsumOdd(intJn)J{
intJ totalJ=J 0;
forJ(intJj=1;JjJ<=Jn;JjJ+=J2)Jto
talJ+=Jj;
returnJ total;
}
R-1.7)JHintJTheJeasyJthingJtoJdoJisJtoJwriteJaJloop.
R-1.7)JSolution
publicJintJsumSquares(intJn)J{
intJ totalJ=J 0;
forJ(intJj=1;JjJ<=Jn;Jj++)Jtotal
J+=Jj∗j;
returnJ total;
}
R-1.8)JHintJYouJmightJuseJaJswitchJstatement.
R-1.8)JSolution
publicJintJnumVowels(StringJtext)J{
intJ totalJ=J 0;
forJ(intJj=0;JjJ<Jtext.length();Jj++)J{
switchJ(text.charAt(j))J{
caseJ'a':
caseJ'A':
caseJ'e':
caseJ'E':
caseJ'i':
caseJ'I':
caseJ'o':
caseJ'O':
caseJ'u':
caseJ'U':Jtota
lJ+=J1;
}
}
returnJ total;
}
R-1.9)JHintJConsiderJeachJcharacterJoneJatJaJtime.
, 3
R-1.10)JHintJConsiderJusingJgetJandJsetJmethodsJforJaccessingJandJmod-
JifyingJtheJvalues.
R-
1.11)J HintJTheJtraditionalJ wayJ toJ doJ thisJ isJ toJuseJ setFooJ methods,Jwher
eJFooJisJtheJvalueJtoJbeJmodified.
R-1.11)JSolution
publicJvoidJsetLimit(intJlim)J{
limitJ=J lim;
}
R-1.12)JHintJUseJaJconditionalJstatement.
R-1.12)JSolution
publicJvoidJmakePayment(doubleJamount)J{
ifJ(amountJ>J0)Jbalance
J− =Jamount;
}
R-1.13)JHintJTryJtoJmakeJwallet[1]JgoJoverJitsJlimit.
R-1.13)JSolution
forJ(intJval=1;JvalJ<=J58;Jval++)J{Jwallet[0].
charge(3∗val);Jwallet[1].charge(2∗val);Jwa
llet[2].charge(val);
}
ThisJchangeJwillJcauseJwallet[1]JtoJattemptJtoJgoJoverJitsJlimit.
Creativity
C-1.14)JHintJTheJJavaJmethodJdoesJnotJneedJtoJbeJpassedJtheJvalueJofJn
asJanJargument.
C-1.15)JHintJNoteJthatJtheJJavaJprogramJhasJaJlotJmoreJsyntaxJrequire-
Jments.
C-
1.16)JHintJCreateJanJenumJtypeJofJallJoperators,JincludingJ=,JandJuseJanJar
rayJofJtheseJtypesJinJaJswitchJstatementJnestedJinsideJfor-
loopsJtoJtryJallJpossibilities.
C-
1.17)JHintJNoteJthatJatJleastJoneJofJtheJnumbersJinJtheJpairJmustJbeJeven.
C-1.17)JSolution