Вы находитесь на странице: 1из 21

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

21

Chapter 3: Program Statements


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. a

Short Answer Solutions


3.1.

WhathappensintheMinOfThreeprogramiftwoormoreofthevaluesareequal?
Theprogramstillprintsthelowestvalue.Becauseonlylessthancomparisonsare
made,thecomparisonoftwoequalvaluesproducesafalseresult.Iftwovalues
areequal,andlowerthanthethirdvalue,thenoneofthetwolowerbutequal
valuesisprinted.Ifallthreevaluesareequal,thenthisvalueisprinted.
Whichversionoftheequalvalueisirrelevant.

Ifexactlytwoofthevaluesareequal,doesitmatterwhethertheequalvaluesarelowerorhigherthanthe
third?
Thecorrectresultisdeterminedineithercase.Ifthetwoequalvaluesare
lowerthanthethird,thenoneofthetwolowerbutequalvaluesisprinted.If
thetwoequalvaluesarehigherthanthethird,thenthethirdvalueisprinted.

3.2.

Whatiswrongwiththefollowingcodefragment?Rewriteitsothatitproducescorrectoutput.
if (total == MAX)
if (total < sum)
System.out.println ("total == MAX and is < sum.");
else
System.out.println ("total is not equal to MAX");
Despitetheindentation,theelseclauseisassociatedwiththeimmediately
precedingifratherthanthefirstif.Theprogramwillproducethecorrect
outputifitisrewrittenas:
if(total==MAX)
{
if(total<sum)

2011 Pearson Education

S 22

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


Solutions

System.out.println(total==MAXandis<sum.);
}
else
System.out.println(totalisnotequaltoMAX);

3.3.

Whatiswrongwiththefollowingcodefragment?Willthiscodecompileifitispartofanotherwisevalid
program?Explain.
if (length = MIN_LENGTH)
System.out.println ("The length is minimal.");
Theassignmentoperator(=)isusederroneouslyinplaceoftheequalityoperator
(==).Hence,itwillnotcompileinanotherwisevalidprogram.

3.4

What output is produced by the following code fragment?


int num = 87, max = 25;
if (num >= max*2)
System.out.println ("apple");
System.out.println ("orange");
System.out.println ("pear");
Theoutputproducedis:

apple
orange
pear
Thesecondprintlnstatementisimproperlyindented.

3.5 Whatoutputisproducedbythefollowingcodefragment?
int limit = 100, num1 = 15, num2 = 40;
if (limit <= limit)
{
if (num1 == num2)
System.out.println ("lemon");
System.out.println ("lime");
}
System.out.println ("grape");
Theoutputis:

lime
grape
3.6 PutthefollowinglistofstringsinlexicographicorderasifdeterminedbythecompareTomethodofthe
Stringclass.ConsulttheUnicodechartinAppendixC.
"fred"
"Ethel"
"?-?-?-?"
"{([])}"
"Lucy"
"ricky"
"book"
2011 Pearson Education

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


23

"******"
"12345"
"
"
"HEPHALUMP"
"bookkeeper"
"6789"
";+<?"
"^^^^^^^^^^"
"hephalump"
Thestringsinlexicographicorder:
""
"******"
"12345"
"6789"
";+<?"
"????"
"Ethel"
"HEPHALUMP"
"Lucy"
"^^^^^^^^^^"
"book"
"bookkeeper"
"fred"
"hephalump"
"ricky"
"{([])}"

3.7 Whatoutputisproducedbythefollowingcodefragment?
int num = 1, max = 20;
while (num < max)
{
if (num%2 == 0)
System.out.println (num);
num++;
}
Theoutputproducedis:

2
4
6
8
10
12
2011 Pearson Education

S 24

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


Solutions

14
16
18
3.8 Whatoutputisproducedbythefollowingcodefragment?
for (int num = 0; num <= 200; num += 2)
System.out.println (num);
Theoutputproducedis:

0
2
4
6
.
.
.
198
200
3.9 Whatoutputisproducedbythefollowingcodefragment?
for (int val = 200; val >= 0; val -= 1)
if (val % 4 != 0)
System.out.println (val);
Theoutputproducedis:

199
198
197
195
.
.
.
5
3
2
1
3.10Transformthefollowingwhileloopintoaforloop(makesureitproducesthesameoutput).
int num = 1;
while (num < 20)
{
num++;
System.out.println (num);
}
Thiscodecanbewrittenusingaforloopasfollows:
for(intnum=1;num<20;)
{

2011 Pearson Education

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


25

num++;
System.out.println(num);
}

3.11Whatiswrongwiththefollowingcodefragment?Whatarethreedistinctwaysitcouldbechangedtoremove
theflaw?
count = 50;
while (count >= 0)
{
System.out.println (count);
count = count + 1;
}
Theloopisinfinitebecausecountinitiallyisgreaterthanzero,andcontinues
toincreaseinvalue.Theflawcanberemovedby(1)decrementingratherthan
incrementingcount,(2)initializingcountto0andusing,astheconditionof
thewhileloop,count<=50,and(3)pickinganupperlimitandusing,asthe
conditionofthewhileloop,count<=upperLimit.

3.13Writeawhileloopthatverifiesthattheuserentersapositiveintegervalue.
System.out.print(Enterapositiveinteger:);
number=scan.nextInt();
while(number<=0)
{
System.out.print(Enterapositiveinteger:);
number=scan.nextInt();
}

3.14Writeacodefragmentthatreadsandprintsintegervaluesenteredbyauseruntilaparticularsentinelvalue
(storedinSENTINEL)isentered.Donotprintthesentinelvalue.
System.out.print(Enteraninteger(
+SENTINEL+toquit):);
number=scan.nextInt();
while(number!=SENTINEL)
{
System.out.println(number);
number=scan.nextInt();
}

3.15Writeaforlooptoprinttheoddnumbersfrom1to99(inclusive).
for(intvalue=1;value<=99;value+=2)
System.out.println(value);

3.16Writeaforlooptoprintthemultiplesof3from300downto3.
for(intvalue=300;value>=3,value=3)
System.out.println(value);

3.17WriteaforeachloopthatprintsallpossiblevaluesofanenumeratedtypecalledMonth.
for(Monthm:Month.values())
System.out.println(m);

2011 Pearson Education

S 26

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


Solutions

3.18Writeacodefragmentthatreads10integervaluesfromtheuserandprintsthehighestvalueentered.
intmax,number;
System.out.print("Enteraninteger:");
max=scan.nextInt();
for(intcount=2;count<=10;count++)
{
System.out.print("Enteranotherinteger:");
number=scan.nextInt();
if(number>max)
max=number;
}
System.out.println("Thehighestvalueis:"+max);

3.19Writeacodefragmentthatdeterminesandprintsthenumberoftimesthecharacter'a'appearsinaString
objectcalledname.
intcount=0;
for(intposition=0;position<name.length();position++)
if(name.charAt(position)=='a')
count++;
System.out.println("Thecharacter\'a\'appears"
+count+"time(s)");

3.20WriteacodefragmentthatprintsthecharactersstoredinaStringobjectcalledstrbackwards.
for(intposition=str.length()1;position>=0;position)
System.out.print(str.charAt(position));
System.out.println();

3.21WriteacodefragmentthatprintseveryothercharacterinaStringobjectcalledwordstartingwiththefirst
character.
for(intposition=0;position<word.length();position+=2)
System.out.println(word.charAt(position));

Programming Project Solutions


3.1 Average
//********************************************************************
//Average.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.1
//
//Demonstratestheuseofawhileloop,asentinelvalue,anda
//runningsum.
//********************************************************************
importjava.text.DecimalFormat;
importjava.util.Scanner;
publicclassAverage
{
//
//Computestheaverageofasetofvaluesenteredbytheuser.
//Therunningsumisprintedasthenumbersareentered.
//
publicstaticvoidmain(String[]args)
2011 Pearson Education

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


27

{
intsum=0,value,count=0;
doubleaverage;
Scannerscan=newScanner(System.in);
System.out.print("Enteraninteger(0toquit):");
value=scan.nextInt();
while(value!=0)//sentinelvalueof0toterminateloop
{
count++;
sum+=value;
System.out.println("Thesumsofaris"+sum);
System.out.print("Enteraninteger(0toquit):");
value=scan.nextInt();
}
System.out.println();
System.out.println("Numberofvaluesentered:"+count);
if(count<1)
{
System.out.println("Cannotcomputeaverage,novaluesentered");
}
else
{
average=(double)sum/count;
DecimalFormatfmt=newDecimalFormat("0.###");
System.out.println("Theaverageis"+fmt.format(average));
}
}
}
3.2 LeapYear
//********************************************************************
//LeapYear.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.2
//
//Readsanintegervaluerepresentingayear.Determinesiftheyear
//isaleapyear
//********************************************************************
importjava.util.Scanner;
publicclassLeapYear
{
//
//Readsanintegervaluerepresentingayear.Determinesiftheyear
//isaleapyear
//
publicstaticvoidmain(String[]args)
{
intyear;
booleanleap=false;
Scannerscan=newScanner(System.in);
System.out.print("Enterayear:");
2011 Pearson Education

S 28

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


Solutions

year=scan.nextInt();
if(year<1582)
System.out.println("ERRORyearnotvalidintheGregoriancalendar");
else
{
if(year%4==0)//divisibleby4
{
leap=true;
if((year%100==0)&&(year%400!=0))
{
leap=false;
}
}
if(leap)
System.out.println(year+"isaleapyear");
else
System.out.println(year+"isnotaleapyear");
}
}
}
3.3 LeapYear2
//********************************************************************
//LeapYear2.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.3
//
//Determinesifayearisaleapyear.
//********************************************************************
importjava.util.Scanner;
publicclassLeapYear2
{
//
//Readsanintegervaluerepresentingayear.Determinesiftheyear
//isaleapyear.Promptstheusertoenteranotheryearorquit.
//
publicstaticvoidmain(String[]args)
{
intyear;
booleanleap=false;
Scannerscan=newScanner(System.in);
do
{
System.out.print("\nEnterayear(0toquit):");
year=scan.nextInt();
if(year!=0)
{
if(year<1582)
System.out.println("ERRORyearnotvalidintheGregorian
calendar");
else
{
if(year%4==0)//divisibleby4
{
2011 Pearson Education

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


29

leap=true;
if((year%100==0)&&(year%400!=0))
{
leap=false;
}
}
if(leap)
System.out.println(year+"isaleapyear");
else
System.out.println(year+"isnotaleapyear");
}
}
leap=false;
}while(year!=0);
}
}
3.4 SumEvens
//********************************************************************
//SumEvens.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.4
//********************************************************************
importjava.util.Scanner;
publicclassSumEvens
{
//
//Computesandprintsthesumoftheevenvaluesbetween2and
//apositivevalueenteredbytheuser.
//
publicstaticvoidmain(String[]args)
{
intsum=0,value;
Scannerscan=newScanner(System.in);
System.out.print("Enterapositiveinteger:");
value=scan.nextInt();
if(value<2)
System.out.println("Thevaluemustbegreaterthantwo.");
else
{
for(intcount=2;count<=value;count+=2)
sum+=count;
System.out.println("Thesumoftheevenintegersfrom2to"
+value+"is"+sum);
}
}
}
3.5 StringDown
//********************************************************************
//StringDown.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.5
//********************************************************************
importjava.util.Scanner;
2011 Pearson Education

S 30

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


Solutions

publicclassStringDown
{
//
//Readsastringfromtheuserandprintsitonecharacter
//perline.
//
publicstaticvoidmain(String[]args)
{
Stringstr;
Scannerscan=newScanner(System.in);
System.out.println("Enterastringofcharacters:");
str=scan.nextLine();
for(intindex=0;index<str.length();index++)
System.out.println(str.charAt(index));
}
}
3.6 CountDigits
//********************************************************************
//CountDigits.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.6
//********************************************************************
importjava.util.Scanner;
publicclassCountDigits
{
//
//Countsthenumberofodd,even,andzerodigitsinan
//integerinputvalue.
//
publicstaticvoidmain(String[]args)
{
intoddCount=0,evenCount=0,zeroCount=0;
intvalue,digit;
Scannerscan=newScanner(System.in);
System.out.print("Enteranintegervalue:");
value=scan.nextInt();
value=Math.abs(value);
if(value==0)
zeroCount++;
while(value>0)
{
digit=value%10;
if(digit==0)
zeroCount++;
else
if(digit%2==0)
evenCount++;
else
oddCount++;
value=value/10;
2011 Pearson Education

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


31

}
System.out.println("Zerodigits:"+zeroCount);
System.out.println("Evendigits:"+evenCount);
System.out.println("Odddigits:"+oddCount);
}
}
3.7 MultTable
//********************************************************************
//MultTable.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.7
//********************************************************************
publicclassMultTable
{
//
//Printsamultiplicationtable.
//
publicstaticvoidmain(String[]args)
{
finalintMAX=12;
for(introw=1;row<=MAX;row++)
{
for(intcolumn=1;column<=MAX;column++)
System.out.print(row*column+"\t");
System.out.println();
}
}
}
3.8 Counter4
//********************************************************************
//Counter4.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.8
//********************************************************************
publicclassCounter4
{
//
//Printsintegervaluesfrom1toaspecificlimit.
//
publicstaticvoidmain(String[]args)
{
finalintLIMIT=5;
intcount=1;
do
{
System.out.println(count);
count=count+1;
}
while(count<=LIMIT);
System.out.println("Done");
}
2011 Pearson Education

S 32

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


Solutions

}
3.9 TravelSong
//********************************************************************
//TravelingSong.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.9.
//********************************************************************
importjava.util.Scanner;
publicclassTravelingSong
{
//
//Printsthefirstfewversesof"100BottlesofBeer"
//
publicstaticvoidmain(String[]args)
{
finalintMAX=100;
intnumVerses=0;//numberofversestoprint
Scannerscan=newScanner(System.in);
while(numVerses<1||numVerses>MAX)
{
System.out.print("Howmanyverses(1to"+MAX+")?");
numVerses=scan.nextInt();
}
intcount=MAX;
for(intverse=1;verse<=numVerses;verse++)
{
System.out.println(count+"bottlesofbeeronthewall.");
System.out.println(count+"bottlesofbeer.");
System.out.println("Ifoneofthosebottlesshouldhappen"
+"tofall");
count=count1;
System.out.println(count+"bottlesofbeeronthewall.");
System.out.println();
}
}
}
3.10 HiLo
//********************************************************************
//HiLo.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.10
//********************************************************************
importjava.util.Scanner;
publicclassHiLo
{
//
//Randomlyselectsanumberinaparticularrange,whichthe
//userattemptstoguess.
//
publicstaticvoidmain(String[]args)
{
2011 Pearson Education

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


33

finalintMAX=100;
inttarget,count=0,guess;
Stringagain;
Scannerscan=newScanner(System.in);
do
{
System.out.println();
System.out.println("Guessanumberbetween1and"+MAX);
target=(int)(Math.random()*MAX)+1;
do
{
System.out.println();
System.out.print("Enteryourguess(0toquit):");
guess=scan.nextInt();
count=count+1;
if(guess>0)
if(guess==target)
System.out.println("Right!Guesses:"+count);
else
if(guess<target)
System.out.println("YourguesswastooLOW.");
else
System.out.println("YourguesswastooHIGH.");
}
while(guess!=target&&guess>0);
System.out.println();
System.out.print("Playagain(y/n)?:");
again=scan.nextLine();
}
while(again.equalsIgnoreCase("y"));
}
}
3.11 PalindromeTester
//********************************************************************
//PalindromeTester.javaAuthor:Lewis/Loftus/Cocking
//
//Demonstratestheuseofnestedwhileloops.
//********************************************************************
importjava.util.Scanner;
publicclassPalindromeTester
{
//
//Removeswhitespaceandpunctionfromastring.Convertsall
//characterstolowercase.
//
privatestaticStringconvertString(Strings)
{
Stringconverted="";
charcurrent;
for(inti=0;i<s.length();i++)
2011 Pearson Education

S 34

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


Solutions

{
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,another="y";
intleft,right;
Scannerscan=newScanner(System.in);
while(another.equalsIgnoreCase("y"))//allowsyorY
{
System.out.println("Enterapotentialpalindrome:");
str=convertString(scan.nextLine());
left=0;
right=str.length()1;
while(str.charAt(left)==str.charAt(right)&&left<right)
{
left++;
right;
}
System.out.println();
if(left<right)
System.out.println("ThatstringisNOTapalindrome.");
else
System.out.println("ThatstringISapalindrome.");
System.out.println();
System.out.print("Testanotherpalindrome(y/n)?");
another=scan.nextLine();
}
}
}
3.12a Stars2
//********************************************************************
//Stars2.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.12a
//********************************************************************
publicclassStars2
2011 Pearson Education

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


35

{
//
//Printsatriangleshapeusingasterisk(star)characters.
//
publicstaticvoidmain(String[]args)
{
finalintLIMIT=10;
for(introw=1;row<=LIMIT;row++)
{
for(intstar=1;star<=LIMITrow+1;star++)
System.out.print("*");
System.out.println();
}
}
}
3.12b Stars3
//********************************************************************
//Stars3.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.12b
//********************************************************************
publicclassStars3
{
//
//Printsatriangleshapeusingasterisk(star)characters.
//
publicstaticvoidmain(String[]args)
{
finalintLIMIT=10;
for(introw=1;row<=LIMIT;row++)
{
for(intspace=1;space<=LIMITrow;space++)
System.out.print("");
for(intstar=1;star<=row;star++)
System.out.print("*");
System.out.println();
}
}
}
3.12c Stars4
//********************************************************************
//Stars4.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.12c
//********************************************************************
publicclassStars4
{
//
//Printsatriangleshapeusingasterisk(star)characters.
//
publicstaticvoidmain(String[]args)
{
2011 Pearson Education

S 36

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


Solutions

finalintLIMIT=10;
for(introw=1;row<=LIMIT;row++)
{
for(intspace=1;space<=row1;space++)
System.out.print("");
for(intstar=1;star<=LIMITrow+1;star++)
System.out.print("*");
System.out.println();
}
}
}
3.12d Stars5
//********************************************************************
//Stars5.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.12d
//********************************************************************
publicclassStars5
{
//
//Printsadiamondshapeusingasterisk(star)characters.
//
publicstaticvoidmain(String[]args)
{
finalintLIMIT=10;
//Printtophalfofdiamond
for(introw=1;row<=LIMIT/2;row++)
{
for(intspace=1;space<=(LIMIT/2)row;space++)
System.out.print("");
for(intstar=1;star<=(row*2)1;star++)
System.out.print("*");
System.out.println();
}
//Printbottomhalfofdiamond
for(introw=1;row<=LIMIT/2;row++)
{
for(intspace=1;space<=row1;space++)
System.out.print("");
for(intstar=1;star<=LIMIT(row*2)+1;star++)
System.out.print("*");
System.out.println();
}
}
}
3.13 Vowels
//********************************************************************
//Vowels.javaAuthor:Lewis/Loftus/Cocking
2011 Pearson Education

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


37

//
//SolutiontoProgrammingProject3.13
//********************************************************************
importjava.util.Scanner;
publicclassVowels
{
//
//Countsthenumberofeachvowelinastring.
//
publicstaticvoidmain(String[]args)
{
intacount=0,ecount=0,icount=0,ocount=0,ucount=0;
intother=0;
Scannerscan=newScanner(System.in);
System.out.println("Enterastringofcharacters:");
Stringstr=scan.nextLine();
str=str.toLowerCase();//forconsistentcounting
for(intindex=0;index<str.length();index++)
{
switch(str.charAt(index))
{
case'a':
acount++;
break;
case'e':
ecount++;
break;
case'i':
icount++;
break;
case'o':
ocount++;
break;
case'u':
ucount++;
break;
default:
other++;
}
}
System.out.println();
System.out.println("Numberofeachvowelinthestring:");
System.out.println("a:"+acount);
System.out.println("e:"+ecount);
System.out.println("i:"+icount);
System.out.println("o:"+ocount);
System.out.println("u:"+ucount);
System.out.println("othercharacters:"+other);
}
}
3.14 RockPaperScissors
//********************************************************************
//RockPaperScissors.javaAuthor:Lewis/Loftus/Cocking
//
2011 Pearson Education

S 38

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


Solutions

//SolutiontoProgrammingProject3.14
//********************************************************************
importjava.util.Scanner;
publicclassRockPaperScissors
{
//
//PlaystheRockPaperScissorsgamewiththeuser.
//
publicstaticvoidmain(String[]args)
{
finalintOPTIONS=3;
finalintROCK=1,PAPER=2,SCISSORS=3;
finalintCOMPUTER=1,PLAYER=2,TIE=3;
intcomputer,player,winner=0;
intwins=0,losses=0,ties=0;
Stringagain;
Scannerscan=newScanner(System.in);
do
{
computer=(int)(Math.random()*OPTIONS)+1;
System.out.println();
System.out.print("Enteryourchoice1forRock,2for"+
"Paper,and3forScissors:");
player=scan.nextInt();
System.out.print("Mychoicewas");
//Determinethewinner
switch(computer)
{
caseROCK:
System.out.println("Rock.");
if(player==SCISSORS)
winner=COMPUTER;
else
if(player==PAPER)
winner=PLAYER;
else
winner=TIE;
break;
casePAPER:
System.out.println("Paper.");
if(player==ROCK)
winner=COMPUTER;
else
if(player==SCISSORS)
winner=PLAYER;
else
winner=TIE;
break;
caseSCISSORS:
System.out.println("Scissors.");
if(player==PAPER)
winner=COMPUTER;
2011 Pearson Education

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


39

else
if(player==ROCK)
winner=PLAYER;
else
winner=TIE;
}
//Printresultsandincrementappropriatecounter
if(winner==COMPUTER)
{
System.out.println("Iwin!");
losses++;
}
else
if(winner==PLAYER)
{
System.out.println("Youwin!");
wins++;
}
else
{
System.out.println("Wetied!");
ties++;
}
System.out.println();
System.out.print("Playagain(y/n)?:");
again=scan.nextLine();
}
while(again.equalsIgnoreCase("y"));
//Printfinalresults
System.out.println();
System.out.println("Youwon"+wins+"times.");
System.out.println("Youlost"+losses+"times.");
System.out.println("Wetied"+ties+"times.");
}
}
3.15 SimpleSlot
//********************************************************************
//SimpleSlot.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.15
//********************************************************************
importjava.util.Scanner;
publicclassSimpleSlot
{
//
//Playsasimpleslotmachineusingdigits.
//
publicstaticvoidmain(String[]args)
{
finalintDIGITS=10;
intslot1,slot2,slot3;
Stringagain;
Scannerscan=newScanner(System.in);
do
2011 Pearson Education

S 40

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


Solutions

{
slot1=(int)(Math.random()*DIGITS);
slot2=(int)(Math.random()*DIGITS);
slot3=(int)(Math.random()*DIGITS);
System.out.println(slot1+""+slot2+""+slot3);
if(slot1==slot2&&slot2==slot3)
System.out.println("Jackpot!!!");
else
if(slot1==slot2||slot2==slot3||slot1==slot3)
System.out.println("Matched2!!");
System.out.println();
System.out.print("Playagain(y/n)?:");
again=scan.nextLine();
}
while(again.equalsIgnoreCase("y"));
}
}
3.16 StairSteps
//********************************************************************
//StairSteps.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.16
//********************************************************************
importjavax.swing.JApplet;
importjava.awt.*;
publicclassStairStepsextendsJApplet
{
privatefinalintNUM_STEPS=15;
privatefinalintSTAIR_HEIGHT=15;
privatefinalintSTAIR_DEPTH=15;
privatefinalintSTART_X=20;
privatefinalintSTART_Y=300STAIR_DEPTH;
//
//Paintsasideviewofsomestairsteps.
//
publicvoidpaint(Graphicspage)
{
intstepX=START_X,stepY=START_Y;
setBackground(Color.cyan);
page.setColor(Color.black);
for(intcount=1;count<=NUM_STEPS;count++)
{
page.drawLine(stepX,stepY,stepX,stepY+STAIR_HEIGHT);
page.drawLine(stepX,stepY,stepX+STAIR_DEPTH,stepY);
stepX+=STAIR_DEPTH;
stepY=STAIR_HEIGHT;
}
}
}
3.17 ColoredCircles
2011 Pearson Education

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


41

//********************************************************************
//ColoredCircles.javaAuthor:Lewis/Loftus/Cocking
//
//SolutiontoProgrammingProject3.17
//********************************************************************
importjavax.swing.JApplet;
importjava.awt.*;
publicclassColoredCirclesextendsJApplet
{
privatefinalintNUM_CIRCLES=100;
privatefinalintMIN_DIAMETER=5;
privatefinalintMAX_DIAMETER=30;
privatefinalintMAX_COLORVALUE=256;
privatefinalintMAX_X=370;
privatefinalintMAX_Y=170;
//
//Paintsseveralcirclesofrandomcolor,diameter,andlocation.
//
publicvoidpaint(Graphicspage)
{
intx,y,diameter,red,green,blue;
setBackground(Color.black);
for(intcount=1;count<=NUM_CIRCLES;count++)
{
x=(int)(Math.random()*MAX_X);
y=(int)(Math.random()*MAX_Y);
red=(int)(Math.random()*MAX_COLORVALUE);
green=(int)(Math.random()*MAX_COLORVALUE);
blue=(int)(Math.random()*MAX_COLORVALUE);
page.setColor(newColor(red,green,blue));
diameter=(int)(Math.random()*MAX_DIAMETER)+MIN_DIAMETER;
page.drawOval(x,y,diameter,diameter);
}
}
}
AP-Style Multiple Choice
Solutions
1.

2.

3.

4.

5.

6.

2011 Pearson Education

Вам также может понравиться