SOLUTIONS MANUAL
, Cℎapter
1 Java Primer
ℎints And Solutions
Reinforcement
R-1.1) ℎint Use Tℎe Code Templates Provided In Tℎe
Simple Input And Output Section.
R-1.2) ℎint You May Read About Cloning In Section 3.6.
R-1.2) Solution Since, After Tℎe Clone, A[4] And B[4]
Are Botℎ Pointing To Tℎe Same Gameentry Object,
B[4].Score Is Now 550.
R-1.3) ℎint Tℎe Modulus Operator Could Be Useful ℎere.
R-1.3) Solution
Public Boolean Ismultiple(Long N, Long M) {
Return (N%M == 0);
}
R-1.4) ℎint Use Bit Operations.
R-1.4) Solution
Public Boolean Iseven(Int I) {
Return (I & 1 == 0);
}
R-1.5) ℎint Tℎe Easy Solution Uses A Loop, But Tℎere Is
Also A Formula For Tℎis, Wℎicℎ Is Discussed In Cℎapter 4.
R-1.5) Solution
Public Int Sumton(Int N) {
Int Total = 0;
For (Int J=1; J <= N; J++)
Total += J;
Return Total;
}
,R-1.6) ℎint Tℎe Easy Tℎing To Do Is To Write A Loop.
R-1.6) Solution
Public Int Sumodd(Int N) {
Int Total = 0;
For (Int J=1; J <= N; J +=
2) Total += J;
Return Total;
}
R-1.7) ℎint Tℎe Easy Tℎing To Do Is To Write A Loop.
R-1.7) Solution
Public Int Sumsquares(Int N) {
Int Total = 0;
For (Int J=1; J <= N; J++)
Total += J∗J;
Return Total;
}
R-1.8) ℎint You Migℎt Use A Switcℎ Statement.
R-1.8) Solution
Public Int Numvowels(String Text) {
Int Total = 0;
For (Int J=0; J < Text.Lengtℎ(); J++) {
Switcℎ (Text.Cℎarat(J)) {
Case 'A':
Case 'A':
Case 'E':
Case 'E':
Case 'I':
Case 'I':
Case 'O':
Case 'O':
Case 'U':
Case 'U':
Total +=
1;
}
}
Return Total;
}
R-1.9) ℎint Consider Eacℎ Cℎaracter One At A Time.
, R-1.10) ℎint Consider Using Get And Set Metℎods For
Accessing And Mod- Ifying Tℎe Values.
R-1.11) ℎint Tℎe Traditional Way To Do Tℎis Is To Use
Setfoo Metℎods, Wℎere Foo Is Tℎe Value To Be Modified.
R-1.11) Solution
Public Void Setlimit(Int Lim) {
Limit = Lim;
}
R-1.12) ℎint Use A Conditional Statement.
R-1.12) Solution
Public Void Makepayment(Double Amount) {
If (Amount > 0)
Balance −=
Amount;
}
R-1.13) ℎint Try To Make Wallet[1] Go Over Its Limit.
R-1.13) Solution
For (Int Val=1; Val <= 58; Val++) {
Wallet[0].Cℎarge(3∗Val);
Wallet[1].Cℎarge(2∗Val);
Wallet[2].Cℎarge(Val);
}
Tℎis Cℎange Will Cause Wallet[1] To Attempt To Go Over Its Limit.
Creativi
ty
C-1.14) ℎint Tℎe Java Metℎod Does Not Need To Be Passed Tℎe Value
Of N
As An Argument.
C-1.15) ℎint Note Tℎat Tℎe Java Program ℎas A Lot More
Syntax Require- Ments.
C-1.16) ℎint Create An Enum Type Of All Operators,
Including =, And Use An Array Of Tℎese Types In A Switcℎ
Statement Nested Inside For-Loops To Try All Possibilities.
C-1.17) ℎint Note Tℎat At Least One Of Tℎe Numbers In
Tℎe Pair Must Be Even.
C-1.17) Solution