Vous êtes sur la page 1sur 26

S 78

Lewis/Loftus/Cocking, 3/e: Chapter 5


Solutions

Chapter 5: Enhancing Classes


Solutions
Multiple Choice
Solutions

True/False
Solutions

1.

1.

2.

2.

3.

3.

4.

4.

5.

5.

6.

6.

7.

7.

8.

8.

9.

9.

10. d

10. T

Short Answer Solutions


5.1 Whatisoutputbythefollowingcode?
Strings1 = hello ;
String s2 = s1;
s2=s2+there;
System.out.println(s1);
System.out.println(s2);
hello
hellothere

5.2 DiscusshowJavapassesparameterstoamethod.Isthistechniquethesameforprimitivetypesandobjects?
Explain.
Javapassesallparametersbyvalue.Thismeansthatthecurrentvalueofthe
actualparameteriscopiedintotheformalparameterinthemethodheader.This
techniqueisconsistentbetweenprimitivetypesandobjectsbecauseobject
referencesratherthanobjectsthemselvesarepassed.Whenanobject(actually,
anobjectreference)ispassed,thecurrentvalueofthereferenceiscopiedinto
thecorrespondingformalparameterinthemethodheader.

5.3

Explainwhyastaticmethodcannotrefertoaninstancevariable.
Astaticmethodisinvokedthroughaclassratherthanthroughanobjectofthe
class.Noobjectoftheclassneedstobeinstantiatedinordertoinvokea
staticmethod.Ifnoobjectisinstantiated,noinstancevariableexists.
Hence,astaticmethodcannotrefertoaninstancevariable.

5.4 Canaclassimplementtwointerfacesthateachcontainthesamemethodsignature?Explain.
Yes,aclasscanimplementtwointerfaceseachofwhichcontainsthesamemethod
signature.Theclasswhichimplementsaninterfaceprovidesmethod
implementationsforeachoftheabstractmethodsdefinedintheinterface.In

2011 Pearson Education

S 79

Lewis/Loftus/Cocking, 3/e: Chapter 5


Solutions

satisfyingtherequirementsforamethodofoneinterface,itsimultaneously
satisfiestherequirementsforamethodwiththesamesignatureinanother
interface.

5.5 CreateaninterfacecalledVisiblethatincludestwomethods:makeVisibleandmakeInvisible.Both
methodsshouldtakenoparametersandshouldreturnabooleanresult.Describehowaclassmightimplement
thisinterface.
publicinterfaceVisible
{
publicbooleanmakeVisible();
publicbooleanmakeInvisible();
}
AclassimplementingVisiblewouldbeginwith
publicclassIconimplementsVisible
andwouldcontainatleasttwomethods(makeVisibleandmakeInvisible),which
takenoparametersandreturnabooleanvalueindicatingthesuccessofthe
method.

5.6
CreateaninterfacecalledVCRwithmethodsthatrepresentwhatavideocassetterecorderdoes(play,stop,
etc.).Definethemethodsignaturesanywayyouwant.Describehowaclassmightimplementthisinterface.
publicinterfaceVCR
{
publicvoidplay();
publicvoidpause();
publicvoidstop();
publicvoidrewind();
publicvoidfastforward();
}
AclassimplementingVCRwouldincludeimplementsVCRintheclassheaderand
wouldimplementeachofthefivemethodsfromtheVCRinterface.Themethods
wouldbehaveasindictedbytheirname.Forexample,fastforwardcausestheVCR
tostartfastforwarding.Thiskeepsgoinguntilthestopmethodiscalledor
anothermethodsuchasplayorrewindiscalled.

5.7
GiventheNum andParameterTester classeslistedearlierinthechapter,whatistheresultofexecutingthe
followinglinesofcode?
ParameterTestermyTester=newParameterTester();
intanInteger=27;
NumaNum=newNum(38);
NumanotherNum=newNum(49);
myTester.changeValues(anInteger,aNum,anotherNum);
System.out.println(anInteger:+anInteger);
System.out.println(aNum:+aNum);
System.out.println(anotherNum:+anotherNum);
Beforechangingthevalues:
f1f2f3
273849
Afterchangingthevalues:
f1f2f3
999888777
anInteger:27
aNum:888

2011 Pearson Education

Lewis/Loftus/Cocking, 3/e: Chapter 5 Solutions


80
anotherNum:49

Programming Project Solutions


5.1 PigLatin2
//********************************************************************
//PigLatin2.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.1
//********************************************************************
importjava.util.Scanner;
publicclassPigLatin2
{
//
//ReadssentencesandtranslatesthemintoPigLatin.
//
publicstaticvoidmain(String[]args)
{
Stringsentence,result,another;
Scannerscan=newScanner(System.in);
do
{
System.out.println();
System.out.println("Enterasentence(nopunctuation):");
sentence=scan.nextLine();
System.out.println();
result=PigLatinTranslator2.translate(sentence);
System.out.println("ThatsentenceinPigLatinis:");
System.out.println(result);
System.out.println();
System.out.print("Translateanothersentence(y/n)?");
another=scan.nextLine();
}
while(another.equalsIgnoreCase("y"));
}
}
5.1 PigLatinTranslator2
//********************************************************************
//PigLatinTranslator2.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.1
//********************************************************************
importjava.util.StringTokenizer;
publicclassPigLatinTranslator2
{
//
//TranslatesasentenceofwordsintoPigLatin.
//
publicstaticStringtranslate(Stringsentence)
2011 Pearson Education

S 81

Lewis/Loftus/Cocking, 3/e: Chapter 5


Solutions

{
Stringresult="";
sentence=sentence.toLowerCase();
StringTokenizertokenizer=newStringTokenizer(sentence);
while(tokenizer.hasMoreTokens())
{
result+=translateWord(tokenizer.nextToken());
result+="";
}
returnresult;
}
//
//TranslatesonewordintoPigLatin.Ifthewordbeginswitha
//vowel,thesuffix"yay"isappendedtotheword.Otherwise,
//thefirstletterortwoaremovedtotheendoftheword,
//and"ay"isappended.
//
privatestaticStringtranslateWord(Stringword)
{
Stringresult="";
if(beginsWithVowel(word))
result=word+"yay";
else
if(beginsWithPrefix(word))
result=word.substring(2)+word.substring(0,2)+"ay";
else
result=word.substring(1)+word.charAt(0)+"ay";
returnresult;
}
//
//Determinesifthespecifiedwordbeginswithavowel.
//
privatestaticbooleanbeginsWithVowel(Stringword)
{
Stringvowels="aeiouAEIOU";
charletter=word.charAt(0);
return(vowels.indexOf(letter)!=1);
}
//
//Determinesifthespecifiedwordbeginswithaparticular
//twocharacterprefix.
//
privatestaticbooleanbeginsWithPrefix(Stringstr)
{
return(str.startsWith("bl")||str.startsWith("pl")||
str.startsWith("br")||str.startsWith("pr")||
str.startsWith("ch")||str.startsWith("sh")||
str.startsWith("cl")||str.startsWith("sl")||
str.startsWith("cr")||str.startsWith("sp")||
str.startsWith("dr")||str.startsWith("sr")||
str.startsWith("fl")||str.startsWith("st")||
2011 Pearson Education

Lewis/Loftus/Cocking, 3/e: Chapter 5 Solutions


82

str.startsWith("fr")||str.startsWith("th")||
str.startsWith("gl")||str.startsWith("tr")||
str.startsWith("gr")||str.startsWith("wh")||
str.startsWith("kl")||str.startsWith("wr")||
str.startsWith("ph"));
}
}
5.2 Rational
//********************************************************************
//Rational.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.2
//
//Representsonerationalnumberwithanumeratoranddenominator.
//********************************************************************
publicclassRationalimplementsComparable
{
privateintnumerator,denominator;
privatefinaldoubleTOLERANCE=0.0001;
//
//Setsuptherationalnumberbyensuringanonzerodenominator
//andmakingonlythenumeratorsigned.
//
publicRational(intnumer,intdenom)
{
if(denom==0)
denom=1;
//Makethenumerator"store"thesign
if(denom<0)
{
numer=numer*1;
denom=denom*1;
}
numerator=numer;
denominator=denom;
reduce();
}
//
//Returnsthenumeratorofthisrationalnumber.
//
publicintgetNumerator()
{
returnnumerator;
}
//
//Returnsthedenominatorofthisrationalnumber.
//
publicintgetDenominator()
{
returndenominator;
}
//
2011 Pearson Education

S 83

Lewis/Loftus/Cocking, 3/e: Chapter 5


Solutions

//Returnsthereciprocalofthisrationalnumber.
//
publicRationalreciprocal()
{
returnnewRational(denominator,numerator);
}
//
//Addsthisrationalnumbertotheonepassedasaparameter.
//Acommondenominatorisfoundbymultiplyingtheindividual
//denominators.
//
publicRationaladd(Rationalop2)
{
intcommonDenominator=denominator*op2.getDenominator();
intnumerator1=numerator*op2.getDenominator();
intnumerator2=op2.getNumerator()*denominator;
intsum=numerator1+numerator2;
returnnewRational(sum,commonDenominator);
}
//
//Subtractstherationalnumberpassedasaparameterfromthis
//rationalnumber.
//
publicRationalsubtract(Rationalop2)
{
intcommonDenominator=denominator*op2.getDenominator();
intnumerator1=numerator*op2.getDenominator();
intnumerator2=op2.getNumerator()*denominator;
intdifference=numerator1numerator2;
returnnewRational(difference,commonDenominator);
}
//
//Multipliesthisrationalnumberbytheonepassedasa
//parameter.
//
publicRationalmultiply(Rationalop2)
{
intnumer=numerator*op2.getNumerator();
intdenom=denominator*op2.getDenominator();
returnnewRational(numer,denom);
}
//
//Dividesthisrationalnumberbytheonepassedasaparameter
//bymultiplyingbythereciprocalofthesecondrational.
//
publicRationaldivide(Rationalop2)
{
returnmultiply(op2.reciprocal());
}
//
//Determinesifthisrationalnumberisequaltotheonepassed
//asaparameter.Assumestheyarebothreduced.
//
2011 Pearson Education

Lewis/Loftus/Cocking, 3/e: Chapter 5 Solutions


84

publicbooleanequals(Rationalop2)
{
return(numerator==op2.getNumerator()&&
denominator==op2.getDenominator());
}
//
//Returnsthisrationalnumberasastring.
//
publicStringtoString()
{
Stringresult;
if(numerator==0)
result="0";
else
if(denominator==1)
result=numerator+"";
else
result=numerator+"/"+denominator;
returnresult;
}
//
//ImplementsmethodfromComparableinterace.
//
publicintcompareTo(Objecto)
{
Rationalr=(Rational)o;
doublethisValue=(double)numerator/denominator;
doubleotherValue=(double)r.numerator/r.denominator;
if(Math.abs(thisValueotherValue)<TOLERANCE)
return0;
else
if(thisValue>otherValue)
return1;
else
return1;
}
//
//Reducesthisrationalnumberbydividingboththenumerator
//andthedenominatorbytheirgreatestcommondivisor.
//
privatevoidreduce()
{
if(numerator!=0)
{
intcommon=gcd(Math.abs(numerator),denominator);
numerator=numerator/common;
denominator=denominator/common;
}
}
//
//Computesandreturnsthegreatestcommondivisorofthetwo
//positiveparameters.UsesEuclid'salgorithm.
2011 Pearson Education

S 85

Lewis/Loftus/Cocking, 3/e: Chapter 5


Solutions

//
privateintgcd(intnum1,intnum2)
{
while(num1!=num2)
if(num1>num2)
num1=num1num2;
else
num2=num2num1;
returnnum1;
}
}
5.2 RationalNumbers
//********************************************************************
//RationalNumbers.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.2
//
//DrivertoexercisetheuseofmultipleRationalobjects.
//********************************************************************
publicclassRationalNumbers
{
//
//Createssomerationalnumberobjectsandperformsvarious
//operationsonthem.
//
publicstaticvoidmain(String[]args)
{
Rationalr1=newRational(6,8);
Rationalr2=newRational(1,3);
Rationalr3,r4,r5,r6,r7;
System.out.println("Firstrationalnumber:"+r1);
System.out.println("Secondrationalnumber:"+r2);
intcompareValue=r1.compareTo(r2);
if(compareValue==0)
System.out.println("r1andr2areequal.");
else
if(compareValue<0)
System.out.println("r1islessthanr2");
else
System.out.println("r1isgreaterthanr2");
Rationalr8=newRational(6,7);
Rationalr9=newRational(6,7);
System.out.println("\nr8rationalnumber:"+r8);
System.out.println("r9rationalnumber:"+r9);
compareValue=r8.compareTo(r9);
if(compareValue==0)
System.out.println("r8andr9areequal.");
else
if(compareValue<0)
System.out.println("r8islessthanr9");
2011 Pearson Education

Lewis/Loftus/Cocking, 3/e: Chapter 5 Solutions


86

else
System.out.println("r8isgreaterthanr9");
Rationalr10=newRational(4,7);
Rationalr11=newRational(5,6);
System.out.println("\nr10rationalnumber:"+r10);
System.out.println("r11rationalnumber:"+r11);
compareValue=r10.compareTo(r11);
if(compareValue==0)
System.out.println("r10andr11areequal.");
else
if(compareValue<0)
System.out.println("r10islessthanr11");
else
System.out.println("r10isgreaterthanr11");
r3=r1.reciprocal();
System.out.println("\nThereciprocalofr1is:"+r3);
r4=r1.add(r2);
r5=r1.subtract(r2);
r6=r1.multiply(r2);
r7=r1.divide(r2);
System.out.println("r1+r2:"+r4);
System.out.println("r1r2:"+r5);
System.out.println("r1*r2:"+r6);
System.out.println("r1/r2:"+r7);
}
}
Priority.java for 5.3, 5.4, & 5.5
//***************************************************************
//Priority.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.3,5.4&5.5
//
//***************************************************************
publicinterfacePriority
{
staticfinalintMED_PRIORITY=5;
staticfinalintMAX_PRIORITY=10;
staticfinalintMIN_PRIORITY=1;
//
//Setstheobject'sprioritylevel
//
publicvoidsetPriority(intvalue);
//
//Returnstheobject'sprioritylevel
//
publicintgetPriority();
}
5.3 Task
2011 Pearson Education

S 87

Lewis/Loftus/Cocking, 3/e: Chapter 5


Solutions

//***************************************************************
//Task.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.3
//
//********************************************************************
publicclassTaskimplementsPriority
{
privateintpriority;
Stringname;
//
//Setsupthetask,assigningthetask'sname
//
publicTask(StringtaskName)
{
name=taskName;
priority=MED_PRIORITY;
}
//
//ReturnstheTask'sname
//
StringgetName()
{
returnname;
}
//
//SetstheTask'sprioritylevel
//
publicvoidsetPriority(intvalue)
{
priority=value;
}
//
//ReturnstheTask'sprioritylevel
//
publicintgetPriority()
{
returnpriority;
}
}
5.3 TaskDriver
//***************************************************************
//TaskDriver.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.3
//
//***************************************************************
publicclassTaskDriver
{
publicstaticvoidmain(Stringargs[])
{
Tasktask1=newTask("WriteanotherJavaprogram");
task1.setPriority(7);
Tasktask2=newTask("Eat");
2011 Pearson Education

Lewis/Loftus/Cocking, 3/e: Chapter 5 Solutions


88

task2.setPriority(Priority.MIN_PRIORITY);
Tasktask3=newTask("Attendclass");
task3.setPriority(Priority.MAX_PRIORITY);
Tasktask4=newTask("Sleep");
task4.setPriority(4);
System.out.println("TODO\n");
System.out.println(task1.getName()+"\tpriority:"+
task1.getPriority());
System.out.println(task2.getName()+"\tpriority:"+
task2.getPriority());
System.out.println(task3.getName()+"\tpriority:"+
task3.getPriority());
System.out.println(task4.getName()+"\tpriority:"+
task4.getPriority());
}
}
5.4Complexity
//***************************************************************
//Complexity.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.4
//***************************************************************
publicinterfaceComplexity
{
staticfinalintMED_COMPLEXITY=5;
staticfinalintMAX_COMPLEXITY=10;
staticfinalintMIN_COMPLEXITY=1;
//
//Setstheobject'scomplexitylevel
//
publicvoidsetComplexity(intcomplexity);
//
//Returnstheobject'scomplexitylevel
//
publicintgetComplexity();
}
5.4 Task 2
//***************************************************************
//Task2.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.4
//
//***************************************************************
publicclassTask2implementsPriority,Complexity
{
privateintpriority;
privateintcomplexity;
Stringname;
//
//Setsupthetask,assigningthetask'sname
//
publicTask2(StringtaskName)
2011 Pearson Education

S 89

Lewis/Loftus/Cocking, 3/e: Chapter 5


Solutions

{
name=taskName;
priority=MED_PRIORITY;
}
//
//Returnsthetask'sname
//
StringgetName()
{
returnname;
}
//
//Setsthetask'sprioritylevel
//
publicvoidsetPriority(intvalue)
{
priority=value;
}
//
//Returnsthetask'sprioritylevel
//
publicintgetPriority()
{
returnpriority;
}
//
//Setsthetask'scomplexitylevel
//
publicvoidsetComplexity(intcomplexity)
{
this.complexity=complexity;
}
//
//Returnsthetask'scomplexitylevel
//
publicintgetComplexity()
{
returncomplexity;
}
}
5.4 TaskDriver2
//***************************************************************
//TaskDriver2.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.4
//
//***************************************************************
publicclassTaskDriver2
{
publicstaticvoidmain(Stringargs[])
{
Task2task1=newTask2("WriteanotherJavaprogram");
task1.setPriority(7);
task1.setComplexity(Complexity.MAX_COMPLEXITY);
2011 Pearson Education

Lewis/Loftus/Cocking, 3/e: Chapter 5 Solutions


90

Task2task2=newTask2("Eat");
task2.setPriority(Priority.MIN_PRIORITY);
task2.setComplexity(Complexity.MIN_COMPLEXITY);
Task2task3=newTask2("Attendclass");
task3.setPriority(Priority.MAX_PRIORITY);
task3.setComplexity(Complexity.MED_COMPLEXITY);
Task2task4=newTask2("Sleep");
task4.setPriority(4);
task4.setComplexity(Complexity.MIN_COMPLEXITY);
System.out.println("TODO\n");
System.out.println(task1.getName());
System.out.println("\tpriority:"+task1.getPriority()+",complexity:
"+task1.getComplexity());
System.out.println("");
System.out.println(task2.getName());
System.out.println("\tpriority:"+task2.getPriority()+",complexity:
"+task2.getComplexity());
System.out.println("");
System.out.println(task3.getName());
System.out.println("\tpriority:"+task3.getPriority()+",complexity:
"+task3.getComplexity());
System.out.println("");
System.out.println(task4.getName());
System.out.println("\tpriority:"+task4.getPriority()+",complexity:
"+task4.getComplexity());
}
}
5.5Complexity
//***************************************************************
//Complexity.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.4
//***************************************************************
publicinterfaceComplexity
{
staticfinalintMED_COMPLEXITY=5;
staticfinalintMAX_COMPLEXITY=10;
staticfinalintMIN_COMPLEXITY=1;
//
//Setstheobject'scomplexitylevel
//
publicvoidsetComplexity(intcomplexity);
//
//Returnstheobject'scomplexitylevel
//
publicintgetComplexity();
}
5.5 Task3
//***************************************************************
//Task3.javaAuthor:Lewis/Loftus/Cocking
//
2011 Pearson Education

S 91

Lewis/Loftus/Cocking, 3/e: Chapter 5


Solutions

//SolutiontoProgrammingProject5.5
//
//***************************************************************
publicclassTask3implementsPriority,Complexity,Comparable
{
privateintpriority;
privateintcomplexity;
Stringname;
//
//Setsupthetask,assigningthetask'sname
//
publicTask3(StringtaskName)
{
name=taskName;
priority=MED_PRIORITY;
}
//
//Returnsthetask'sname
//
StringgetName()
{
returnname;
}
//
//Setsthetask'sprioritylevel
//
publicvoidsetPriority(intvalue)
{
priority=value;
}
//
//Returnsthetask'sprioritylevel
//
publicintgetPriority()
{
returnpriority;
}
//
//Setsthetask'scomplexitylevel
//
publicvoidsetComplexity(intcomplexity)
{
this.complexity=complexity;
}
//
//Returnsthetask'scomplexitylevel
//
publicintgetComplexity()
{
returncomplexity;
}
//
//Comparestwotasksbasedonpriority
2011 Pearson Education

Lewis/Loftus/Cocking, 3/e: Chapter 5 Solutions


92

//
publicintcompareTo(Objecto)
{
Task3other=(Task3)o;
if(other.priority==this.priority)
return0;
else
if(other.priority>this.priority)
return1;
else
return1;
}
}
5.5 TaskDriver3
//***************************************************************
//TaskDriver3.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.5
//
//***************************************************************
publicclassTaskDriver3
{
publicstaticvoidmain(Stringargs[])
{
Task3task1=newTask3("WriteanotherJavaprogram");
task1.setPriority(7);
task1.setComplexity(Complexity.MAX_COMPLEXITY);
Task3task2=newTask3("Eat");
task2.setPriority(Priority.MIN_PRIORITY);
task2.setComplexity(Complexity.MIN_COMPLEXITY);
Task3task3=newTask3("Attendclass");
task3.setPriority(Priority.MAX_PRIORITY);
task3.setComplexity(Complexity.MED_COMPLEXITY);
Task3task4=newTask3("Sleep");
task4.setPriority(4);
task4.setComplexity(Complexity.MIN_COMPLEXITY);
System.out.println("TODO\n");
System.out.println(task1.getName());
System.out.println("\tpriority:"+task1.getPriority()+",complexity:
"+task1.getComplexity());
System.out.println("");
System.out.println(task2.getName());
System.out.println("\tpriority:"+task2.getPriority()+",complexity:
"+task2.getComplexity());
System.out.println("");
System.out.println(task3.getName());
System.out.println("\tpriority:"+task3.getPriority()+",complexity:
"+task3.getComplexity());
System.out.println("");
System.out.println(task4.getName());
System.out.println("\tpriority:"+task4.getPriority()+",complexity:
"+task4.getComplexity());
System.out.print("\nTASK:");
2011 Pearson Education

S 93

Lewis/Loftus/Cocking, 3/e: Chapter 5


Solutions

if(task1.compareTo(task2)==0)
System.out.println(task1.getName()+"hasthesamepriorityasTASK:"
+task2.getName());
else
if(task1.compareTo(task2)>0)
System.out.println(task1.getName()+"hasgreaterprioritythan
TASK:"+task2.getName());
else
System.out.println(task2.getName()+"hasgreaterprioritythan
TASK:"+task1.getName());
System.out.print("\nTASK:");
if(task3.compareTo(task4)==0)
System.out.println(task3.getName()+"hasthesamepriorityasTASK:"
+task4.getName());
else
if(task3.compareTo(task4)>0)
System.out.println(task3.getName()+"hasgreaterprioritythan
TASK:"+task4.getName());
else
System.out.println(task4.getName()+"hasgreaterprioritythan
TASK:"+task3.getName());
}
}
5.6 Lockable
//***************************************************************
//Lockable.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.6&5.7
//
//***************************************************************
publicinterfaceLockable
{
//
//Setstheobject'skey
//
publicvoidsetKey(intkey);
//
//Lockstheobject
//
publicvoidlock(intkey);
//
//Unlockstheobject
//
publicvoidunlock(intkey);
//
//Returnstrueittheobjectislocked,elsereturnsfalse
//
publicbooleanlocked();
}
2011 Pearson Education

Lewis/Loftus/Cocking, 3/e: Chapter 5 Solutions


94

5.6 Coin
//***************************************************************
//Coin.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.6
//***************************************************************
importjava.util.Random;
publicclassCoinimplementsLockable
{
privatefinalintHEADS=0;
privatefinalintTAILS=1;
privatefinalintLOCK=3;
privatebooleanlocked;
privateintcoinKey;
privateintface;
//
//Setsupthecoinbyflippingitinitially.
//
publicCoin()
{
locked=false;
coinKey=0;
flip();
}
//
//Flipsthecoinbyrandomlychoosingafacevalue.
//
publicvoidflip()
{
if(!locked)
face=(int)(Math.random()*2);
}
//
//Returnstrueifthecurrentfaceofthecoinisheads.
//
publicbooleanisHeads()
{
return(face==HEADS);
}
//
//Returnsthecurrentfaceofthecoinasastring.
//
publicStringtoString()
{
if(!locked)
{
StringfaceName;
if(face==HEADS)
faceName="Heads";
else
faceName="Tails";
returnfaceName;
2011 Pearson Education

S 95

Lewis/Loftus/Cocking, 3/e: Chapter 5


Solutions

}
else
return"LOCKED";
}
//
//Setstheobject'skey
//
publicvoidsetKey(intkey)
{
if(!locked)
coinKey=key;
}
//
//Lockstheobject
//
publicvoidlock(intkey)
{
if(key==coinKey)
locked=true;
}
//
//Unlockstheobject
//
publicvoidunlock(intkey)
{
if(key==coinKey)
locked=false;
}
//
//Returnstrueittheobjectislocked,elsereturnsfalse
//
publicbooleanlocked()
{
returnlocked;
}
}
5.6 TestCoin
//***************************************************************
//TestCoin.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingAssignment5.6
//********************************************************************
publicclassTestCoin
{
//
//Flipsacoinmultipletimesandcountsthenumberofheads
//andtailsthatresult.Locksandunlockscoins
//
publicstaticvoidmain(String[]args)
{
finalintNUM_FLIPS=25;
intkey=10;
CoinmyCoin=newCoin();//instantiatetheCoinobject
2011 Pearson Education

Lewis/Loftus/Cocking, 3/e: Chapter 5 Solutions


96

myCoin.setKey(key);
for(intcount=1;count<=NUM_FLIPS;count++)
{
myCoin.flip();
System.out.println(myCoin);
if(count%10==0)
myCoin.lock(key);
else
if(count%5==0)
myCoin.unlock(key);
}
}
}
5.7Lockable
//***************************************************************
//Lockable.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.6&5.7
//
//***************************************************************
publicinterfaceLockable
{
//
//Setstheobject'skey
//
publicvoidsetKey(intkey);
//
//Lockstheobject
//
publicvoidlock(intkey);
//
//Unlockstheobject
//
publicvoidunlock(intkey);
//
//Returnstrueittheobjectislocked,elsereturnsfalse
//
publicbooleanlocked();
}
5.7 Account
//***************************************************************
//Account.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.7
//***************************************************************
importjava.text.NumberFormat;
2011 Pearson Education

S 97

Lewis/Loftus/Cocking, 3/e: Chapter 5


Solutions

publicclassAccountimplementsLockable
{
privateNumberFormatfmt=NumberFormat.getCurrencyInstance();
privatefinaldoubleRATE=0.035;//interestrateof3.5%
privatelongacctNumber;
privatedoublebalance;
privateStringname;
privateintaccountKey;
privatebooleanlocked;
//
//Setsuptheaccountbydefiningitsownerandaccountnumber.
//Initialbalanceissettozero
//
publicAccount(Stringowner,longaccount)
{
name=owner;
acctNumber=account;
balance=0.0;
locked=false;
accountKey=0;
}
//
//Setsuptheaccountbydefiningitsowner,accountnumber,
//andinitialbalance.
//
publicAccount(Stringowner,longaccount,doubleinitial)
{
name=owner;
acctNumber=account;
balance=initial;
locked=false;
accountKey=0;
}
//
//Validatesthetransaction.Ifsufficentfundsexist,withdrawsthe
specifiedamount
//fromthe"from"accountanddepositsitintothe"to"accountreturning
true,
//elsedoesnothingandreturnsfalse.
//
publicstaticbooleantransfer(doubleamount,doublefee,Accountfrom,
Accountto)
{
if(from.locked()||to.locked())
returnfalse;
if(from.balance+fee<amount||amount<0)
returnfalse;
from.withdraw(amount,fee);
to.deposit(amount);
returntrue;
2011 Pearson Education

Lewis/Loftus/Cocking, 3/e: Chapter 5 Solutions


98

}
//
//Validatesthetransaction,thendepositsthespecifiedamount
//intotheaccount.Returnsthenewbalance.
//
publicdoubledeposit(doubleamount)
{
if(locked)
returnbalance;
if(amount<0)//depositvalueisnegative
{
System.out.println();
System.out.println("Error:Depositamountisinvalid.");
System.out.println(acctNumber+""+fmt.format(amount));
}
else
balance=balance+amount;
returnbalance;
}
//
//Validatesthetransaction,thenwithdrawsthespecifiedamount
//fromtheaccount.Returnsthenewbalance.
//
publicdoublewithdraw(doubleamount,doublefee)
{
if(locked)
returnbalance;
amount+=fee;
if(amount<0)//withdrawvalueisnegative
{
System.out.println();
System.out.println("Error:Withdrawamountisinvalid.");
System.out.println("Account:"+acctNumber);
System.out.println("Requested:"+fmt.format(amount));
}
else
if(amount>balance)//withdrawvalueexceedsbalance
{
System.out.println();
System.out.println("Error:Insufficientfunds.");
System.out.println("Account:"+acctNumber);
System.out.println("Requested:"+fmt.format(amount));
System.out.println("Available:"+fmt.format(balance));
}
else
balance=balanceamount;
returnbalance;
}
//
//Addsinteresttotheaccountandreturnsthenewbalance.
//
publicdoubleaddInterest()
2011 Pearson Education

S 99

Lewis/Loftus/Cocking, 3/e: Chapter 5


Solutions

{
if(locked)
returnbalance;
balance+=(balance*RATE);
returnbalance;
}
//
//Returnsthecurrentbalanceoftheaccount.
//
publicdoublegetBalance()
{
returnbalance;
}
//
//Returnstheaccountnumber.
//
publiclonggetAccountNumber()
{
returnacctNumber;
}
//
//Returnsaonelinedescriptionoftheaccountasastring.
//
publicStringtoString()
{
return(acctNumber+"\t"+name+"\t"+fmt.format(balance));
}
//
//Setstheaccount'skey
//
publicvoidsetKey(intkey)
{
accountKey=key;
}
//
//Lockstheaccount
//
publicvoidlock(intkey)
{
if(key==accountKey)
locked=true;
}
//
//Unlockstheaccount
//
publicvoidunlock(intkey)
{
if(key==accountKey)
locked=false;
}
//
//Returnstrueittheaccountislocked,elsereturnsfalse
//
2011 Pearson Education

Lewis/Loftus/Cocking, 3/e: Chapter 5 Solutions


100

publicbooleanlocked()
{
returnlocked;
}
}
5.8 SumProduct
//***************************************************************
//SumProduct.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.8
//
//***************************************************************
importjavax.swing.JOptionPane;
publicclassSumProduct
{
//
//Usesdialogboxestopromptauserfortwointegers.Displays
//thesumandtheproductoftheintegers.Allowstheuserto
//choosetoprocessmorepairsofnumbers
//
publicstaticvoidmain(Stringargs[])
{
StringnumString,result;
intnum1,num2,again;
do
{
numString=JOptionPane.showInputDialog("Enteraninteger:");
num1=Integer.parseInt(numString);
numString=JOptionPane.showInputDialog("Enteranotherinteger:");
num2=Integer.parseInt(numString);
result="Youentered"+num1+"and"+num2;
result+="\nThesumofthesenumbersis"+(num1+num2);
result+="\nTheproductofthesenumbersis"+(num1*num2);
JOptionPane.showMessageDialog(null,result);
again=JOptionPane.showConfirmDialog(null,"Another?");
}
while(again==JOptionPane.YES_OPTION);
}
}
5.9 PalindromeTester
//***************************************************************
//PalindromeTester.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.9
//***************************************************************
importjavax.swing.JOptionPane;
publicclassPalindromeTester
{
2011 Pearson Education

S 101

Lewis/Loftus/Cocking, 3/e: Chapter 5


Solutions

//
//Removeswhitespaceandpunctionfromastring.Convertsall
//characterstolowercase.
//
privatestaticStringconvertString(Strings)
{
Stringconverted="";
charcurrent;
for(inti=0;i<s.length();i++)
{
current=s.charAt(i);
if(Character.isLetterOrDigit(current))//onlycountlettersand
digits
{
if(Character.isUpperCase(current))//converttolowercaseif
needed
current=Character.toLowerCase(current);
converted+=current;
}
}
returnconverted;
}
//
//Testsstringstoseeiftheyarepalindromes.
//
publicstaticvoidmain(String[]args)
{
Stringstr,result,in;
intleft,right;
intanother;
do
{
in=JOptionPane.showInputDialog("Enterapotentialpalindrome:");
str=convertString(in);
left=0;
right=str.length()1;
while(str.charAt(left)==str.charAt(right)&&left<right)
{
left++;
right;
}
result="\""+in+"\"";
if(left<right)
result+="isNOTapalindrome.";
else
result+="ISapalindrome.";
JOptionPane.showMessageDialog(null,result);
another=JOptionPane.showConfirmDialog(null,"Testanotherpalindrome?
");
}
2011 Pearson Education

Lewis/Loftus/Cocking, 3/e: Chapter 5 Solutions


102

while(another==JOptionPane.YES_OPTION);
}
}
5.10 IncDec
//***************************************************************
//IncDec.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject5.10
//***************************************************************
publicclassIncDec
{
//
//Createsanddisplaystheincrement/decrementGUI.
//
publicstaticvoidmain(String[]args)
{
IncDecGUIid=newIncDecGUI();
id.display();
}

}
AP-Style Multiple Choice
Solutions
1.

2.

3.

4.

5.

6.

AP-Style Free Response Solution


5.1
a.
implements Comparable

b.
public String getFirst()
{
return first;
}
public String getLast()
{
return last;
}
public int compareTo (Object otherName)
{
if (this.last.compareTo(((Name)otherName).getLast()) == 0)
return this.first.compareTo(((Name)otherName).getFirst());
else
return this.last.compareTo(((Name)otherName).getLast());

2011 Pearson Education

S 103

c.
public String toString ()
{
return first + " " + last;
}

2011 Pearson Education

Lewis/Loftus/Cocking, 3/e: Chapter 5


Solutions