0% found this document useful (0 votes)
669 views19 pages

Test 1

Uploaded by

xiangli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
669 views19 pages

Test 1

Uploaded by

xiangli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Chapter1

1. Thispartofthecomputerfetchesinstructions,carriesouttheoperationscommandedbythe
instructions,andproducessomeoutcomeorresultantinformationCPU.
2. Abyteismadeupofeightbits.
3. Eachbyteisassignedauniqueaddress.
4. Thistypeofmemorycanholddataforlongperiodsoftimeevenwhenthereisnopowertothe
computersecondarystorage.
5. Ifyouweretolookatamachinelanguageprogram,youwouldseeastreamofbinary
numbers.
6. ThistypeofprogramisdesignedtobetransmittedovertheInternetandruninawebbrowser.
Applet
7. Thesearewordsthathaveaspecialmeaningintheprogramminglanguage.Keywords.
8. Therearesymbolsorwordsthatperformoperationsononeormoreoperands.Operators
9. Thesecharactersservespecificpurposes,suchasmarkingthebeginningorendingofastatement,
orseparatingitemsinalist.Punctuation
10. Thesearewordsornamesthatareusedtoidentifystoragelocationsinmemoryandpartsofthe
programthatarecreatedbytheprogrammer.Programmerdefinednames.
11. Thesearetherulesthatmustbefollowedwhenwritingaprogram.Syntax
12. Thisisanamedstoragelocationinthecomputersmemory.Variable
13. TheJavacompilergeneratesbytecode.
14. JVMstandsforJavaVirtualMachine
1.3

1.6

Whenaprogramrunsonacomputer,thepartofthecomputerthatcarriesouttheinstructionsis
calledtheCPU
Ateachstepofitsoperation,theinputtoaCentralProcessingUnitisaninstruction
RAM,randomaccessmemory,iscalledthatbecauseyoucanpickanytworandomlocationsand
itwilltakethesametimetoaccessthedata
Abitisabinarydigit,like0or1
Abyteinmemoryisidentifiedbyauniquenumbercalleditsaddress
Inmoderncomputersystems,abyteconsistsof8bits
Monitors,printers,statuslightsareallexamplesofoutputdevices
Mice,trackpads,keyboards,scanners,joysticksareallexamplesofinputdevices.
Flashdrives,CDs,externaldisksareallexamplesofexternalstorage(memory)devices
Whenaprogramrunsonacomputer,itisstoredinRAM
Whenaprogramisnotrunning,itisstoredonadisk

Anerrorinaprogramthatinvolvesaviolationoflanguageruleswillbedetectedatcompiletime
Divisionbyzerowhentheprogramisexecutingisanexampleofaruntimeerror
Thepurposeoftestingaprogramwithdifferentcombinationsofdataistoexposeruntime
andlogicalerrors

Chapter2

1. Everycompletestatementendswithasemicolon.
2. Thefollowingdata
72
A
HelloWorld
2.8712
areallexamplesofliterals.
3. Agroupofstatements,suchasthecontentofaclassoramethod,areenclosedinbraces{}.
4. Whichofthefollowingarenotvalidassignmentstatements?72=amount;&profit=129
5. Whichifthefollowingarenotvalidprintlnstatements?System.out.println+HelloWorld;&
out.System.println(value);&println.out(programmingisgreatfun);
6. Thenegationoperatorisunary.
7. Thiskeywordisusedtodeclareanamedconstant.Final
8. Thesecharactersmarkthebeginningodamultilinecomment./*
9. Thesecharactersmarkthebeginningofasinglecomment.//
10. Thesecharactesmarkthebeginningofadocumentationcomment./**
11. WhichScannerclassmethodwouldyouusetoreadastringasinput?nextLine
12. WhichScannerclassmethodwouldyouusetoreadadoubleasinput?nextDouble
13. Youcanusethisclasstodisplaydialogboxes.JOptionPane
14. WhenJavaconvertsalowerrankedvaluetoahigherrankedtype,itiscalledawidening
conversion.
15. Thistypeofoperatorletsyoumanuallyconvertavalue,evenifitmeansthatanarrowing
converasionwilltakeplace.Cast
16. AleftbraceinaJavaprogramisalwaysfollowedbyarightbracelaterintheprogram.T
17. Avariablemustbedeclaredbeforeitcanbeused.T
18. Variablenamesmaybeginwithanumber.F
19. Youcannotchangethevalueofavariablewhosedeclarationusesthefinalkeyword.T
20. Commentsthatbeginwith//canbeprocessedbyJavadoc.F
21. Ifoneofanoperatorsoperandsisadouble,andtheotheroperandisanint,Javawill
automaticallyconvertthevalueofthedoubletoanint.F
2.1

RearrangethefollowingcodesothatitformsacorrectprogramthatprintsouttheletterQ:
publicclassQ{
publicstaticvoidmain(String[]a){
System.out.println("Q");
}
}
WriteacompleteprogramwhoseclassnameisHelloandthatdisplaysHello,worldonthe
screen.
publicclassHello{
publicstaticvoidmain(String[]args){
System.out.print("Hello,world");
}
}

2.2

2.3

WriteastatementthatprintsHello,worldtothescreen.
System.out.println("Hello,world");
SupposeyournamewasAlanTuring.Writeastatementthatwouldprintyourlastname,
followedbyacomma,followedbyaspaceandyourfirstname
System.out.println("Turing,Alan");
WriteacompletemainmethodthatprintsHello,worldtothescreen.
publicstaticvoidmain(String[]args){
System.out.println("Hello,world");
}
SupposeyournamewasGeorgeGershwin.Writeacompletemainmethodthatwouldprint
yourlastname,followedbyacomma,followedbyaspaceandyourfirstname.
publicstaticvoidmain(String[]args){
System.out.println("Gershwin,George");
}
Thecharacterescapesequencetoforcethecursortogotothenextlineis:\n
Thecharacterescapesequencetoforcethecursortoadvanceforwardtothenexttabsettingis:\t
Thecharacterescapesequencetorepresentasinglequoteis:\
Thecharacterescapesequencetorepresentadoublequoteis:\
Thecharacterescapesequencetorepresentabackslashis:\\
InJava,anargumentisinformationprovidedtoamethod

Beforeavariableisuseditmustbedeclared
Writealiteralrepresentingtheintegervaluezero.
0
WhichofthefollowingisNOTalegalidentifier?7thheaven
WhichofthefollowingISalegalidentifier?____________
Whichisthebestidentifierforavariabletorepresenttheamountofmoneyyourbosspaysyou
eachmonth?monthlyPay
Ofthefollowingvariablenames,whichisthebestoneforkeepingtrackofwhetherapatienthas
afeverornot?hasFever
Ofthefollowingvariablenames,whichisthebestoneforkeepingtrackofwhetheraninteger
mightbeprimeornot?mightBePrime
DeclareanintegervariablenameddegreesCelsius.
intdegreesCelsius;
GivenanintegervariabledrivingAgethathasalreadybeendeclared,write
astatementthatassignsthevalue17todrivingAge.
drivingAge=17;
Whichofthefollowingnamesinaprogramisequivalenttothenameint?Noneoftheabove
Givenanintegervariablecount,writeastatementthatdisplaysthevalueofcountonthe
screen.
System.out.println(count);

2.4

AssumethatmessageisaStringvariable.Writeastatementtodisplayitsvalueonstandard
output.
System.out.println(message);
Twovariables,numandcosthave beendeclared andgivenvalues:numis an integer
andcostis adouble. Write a single statement thatoutputsnumandcosttostandard output.
Printbothvalues(numfirst,thencost),separatedbyaspaceonasinglelinethatisterminated
withanewlinecharacter.Donotoutputanythingelse.
System.out.println(num+""+cost+"\n");
Givenafloatingpointvariablefraction,writeastatementthatdisplaysthevalueoffractionon
thescreen.
System.out.println(fraction);
AssumethatwordisaStringvariable.Writeastatementtodisplaythemessage"Today's
WordOfTheDayis:"followedbythevalueofword.Themessageandthevalue
ofwordshouldappeartogether,onasinglelineonstandardoutput.
System.out.println("Today'sWordOfTheDayis:"+word);
Writeasinglestatementthatwillprintthemessage"firstis"followedbythevalueoffirst,and
thenaspace,followedby"second=",followedbythevalueofsecond.Printeverythingonone
lineandgotoanewlineafterprinting.Assumethatfirsthasalreadybeendeclaredasadouble
and thatsecondhas beendeclared as anint.Assume also that thevariables havealready
beengivenvalues.
System.out.println("firstis"+first+"second="+second+"\n");
DeclareashortvariablenamedpatientsAge.
shortpatientsAge;
DeclaretwointegervariablesnamedprofitStartOfQuarterandcashFlowEndOfYear.
intprofitStartOfQuarter;
intcashFlowEndOfYear;
Writeafloatingpointliteralcorrespondingtothevaluezero.
0.0
Writealiteralcorrespondingtothefloatingpointvalueoneandahalf.
1.5
Writealiteralcorrespondingtothevalueofthefirst6digitsofPI("threepointonefouronefive
nine").
3.14159
Declareafloatvariablenamedprice.
floatprice;
DeclareadoublevariablenamednetWeight.
doublenetWeight;
Writealiteralrepresentingthefalsevalue.
false
Writealiteralrepresentingthetruevalue
true
DeclareavariableisACustomersuitableforrepresentingatrueorfalsevalue.
booleanisACustomer;
JavarepresentscharactersusingUnicode
WithitsencodingJavacanworkwith65536characters

Writeacharacterliteralrepresentingthe(uppercase)letterA.
A
Writeacharacterliteralrepresentingacomma.
,
Writeacharacterliteralrepresentingthedigit1.
'1'
Writealiteralrepresentingthecharacterwhoseunicodevalueis65.
65
Writealiteralrepresentingthelargestcharactervalue.
65535
Declareacharactervariablenamedc.
charc;
What'sthedifferenceinUNICODEvaluebetween'E'and'A'?(consultatableofUNICODE
values):4
What'sthedifferenceinUNICODEvaluebetween'e'and'a'?(consultatableofUNICODE
values):4
What'sthedifferenceinUNICODEvaluebetween'3'and'0'?(consultatableofUNICODE
values):3
What'sthedifferenceinUNICODEvaluebetween'6'and'0'?(consultatableofUNICODE
values):6
Declareandinitializethefollowingvariables:
o

monthOfYear,initializedtothevalue11

companyRevenue,initializedtothevalue5666777

firstClassTicketPrice,initializedtothevalue6000

totalPopulation,initializedtothevalue1222333

intmonthOfYear,firstClassTicketPrice;

monthOfYear=11;

firstClassTicketPrice=6000;

intcompanyRevenue,totalPopulation;

companyRevenue=5666777;

totalPopulation=1222333;
DeclareanintegervariablecardsInHandandinitializeitto13.
intcardsInHand=13;

Declaretwodoublevariables,onenamedlengthwithavalueof3.5andthe
othernamedwidthwithavalueof1.55.
doublelength=3.5,width=1.55;
GiventwointegervariablesoldRecordandnewRecord,writeastatementthat
givesnewRecordthesamevaluethatoldRecordhas.
newRecord=oldRecord;
DeclareavariablehasPassedTest,andinitializeittotrue.
booleanhasPassedTest=true;
Giventwointvariables,iandj,whichhavebeendeclaredandinitialized,andtwo
otherintvariables,itempandjtemp,whichhavebeendeclared,writesomecode
thatswapsthevaluesiniandjbycopyingtheirvaluestoitempandjtemprespectively,andthen
copyingitempandjtemptojandirespectively.
itemp=i;
jtemp=j;
i=jtemp;
j=itemp;
Giventhreealreadydeclaredintvariables,i,j,andtemp,writesomecode
thatswapsthevaluesiniandj.Usetemptoholdthevalueofiandthenassignj'svaluetoi.
Theoriginalvalueofi,whichwassavedintemp,cannowbeassignedtoj.
temp=i;
i=j;
j=temp;
Giventwointvariables,firstPlaceWinnerandsecondPlaceWinner,writesomecode
thatswapstheirvalues.Declareanyadditionalvariablesasnecessary.
intswap_me=firstPlaceWinner;
firstPlaceWinner=secondPlaceWinner;
secondPlaceWinner=swap_me;
Giventwodoublevariables,bestValueandsecondBestValue,writesomecode
thatswapstheirvalues.Declareanyadditionalvariablesasnecessary.
doubletempNum;
tempNum=bestValue;
bestValue=secondBestValue;
secondBestValue=tempNum;
Fourintegervariables,pos1,pos2,pos3,pos4havebeendeclaredandinitialized.Writethe
codenecessaryto"leftrotate"theirvalues:foreachvariabletogetthevalueofthe
successivevariable,withpos4gettingpos1'svalue.
inttempP1=pos1;
inttempP2=pos2;
inttempP3=pos3;
inttempP4=pos4;
pos4=tempP1;
pos3=tempP4;
pos2=tempP3;
pos1=tempP2;
DeclareavariablepopulationChange,suitableforholdingnumberslike593142and8930522.
intpopulationChange;
Declareavariablex,suitableforstoringvalueslike3.14159and6.02E23.

2.5

floatx;
Declareavariabletemperatureandinitializeitto98.6.
doubletemperature=98.6;
Declareavariablepreciseandinitializeittothevalue1.09388641.
doubleprecise=1.09388641;
Writeanexpressionthatcomputesthesumof
twovariablesverbalScoreandmathScore(alreadydeclaredandassignedvalues).
verbalScore+mathScore
GiventhevariablestaxablePurchasesandtaxFreePurchases(alreadydeclared
andassignedvalues),writeanexpressioncorrespondingtothetotalamountpurchased.
taxablePurchases+taxFreePurchases
WriteanexpressionthatcomputesthedifferenceofthevariablesendingTimeandstartingTime.
endingTimestartingTime
GiventhevariablesfullAdmissionPriceanddiscountAmount(alreadydeclared
andassignedvalues),writeanexpressioncorrespondingtothepriceofadiscountadmission.
fullAdmissionPricediscountAmount
GiventhevariablepricePerCase,writeanexpressioncorrespondingtothepriceofadozen
cases.
pricePerCase*12
GiventhevariablescostOfBusRentalandmaxBusRidersoftypeint,write
anexpressioncorrespondingtothecostperrider(assumingthebusisfull).(Donotworryabout
anyfractionalpartoftheexpressionletintegerarithmetic,withtruncation,acthere.)
costOfBusRental/maxBusRiders
Writeanexpressionthatcomputestheremainderofthevariableprincipalwhendividedby
thevariabledivisor.(Assumebotharetypeint.)
principal%divisor
Awallhasbeenbuiltwithtwopiecesofsheetrock,asmalleroneandalargerone.Thelengthof
thesmalleroneisstoredinthevariablesmall.Similarly,thelengthofthelargeroneisstoredin
thevariablelarge.Writeasingleexpressionwhosevalueisthelengthofthiswall.
small+large
Assumethatpriceisanintegervariablewhosevalueistheprice(inUScurrency)incentsof
anitem.Assumingtheitemispaidforwithaminimumamountofchangeandjustsingledollars,
writeanexpressionforthenumberofsingledollarsthatwouldhavetobepaid.
price/100
Assumethatpriceisanintegervariablewhosevalueistheprice(inUScurrency)incentsof
anitem.Assumingtheitemispaidforwithaminimumamountofchangeandjustsingledollars,
writeanexpressionfortheamountofchange(incents)thatwouldhavetobepaid.
price%100
Assumethatpriceisanintegervariablewhosevalueistheprice(inUScurrency)incentsof
anitem.Writeastatementthatprintsthevalueofpriceintheform"XdollarsandYcents"ona
linebyitself.So,ifthevalueofpricewas4321,yourcodewouldprint"43dollarsand21cents".
Ifthevaluewas501itwouldprint"5dollarsand1cents".Ifthevaluewas99yourcodewould
print"0dollarsand99cents".
System.out.println(price/100+"dollarsand"+price%100+"cents");
Assumethatanintvariablexthathasalreadybeendeclared,andinitializedtoanon
negativevalue.Writeanexpressionwhosevalueisthelast(rightmost)digitofx.

x%10
Writeanexpressionthatcomputesthesumoftwodoublevariablestotal1andtotal2,which
havebeenalreadydeclaredandassignedvalues.
total1+total2
Writeanexpressionthatcomputesthedifferenceof
twodoublevariablessalesSummerandsalesSpring,whichhavebeenalreadydeclared
andassignedvalues.
salesSummersalesSpring
Youaregiventwodoublevariables,alreadydeclared
andassignedvalues,namedtotalWeight,containingtheweightofashipment,
andweightOfBox,containingtheweightoftheboxinwhichaproductisshipped.Write
anexpressionthatcalculatesthenetweightoftheproduct.
totalWeightweightOfBox
Youaregiventwovariables,alreadydeclaredandassignedvalues,one
oftypedouble,namedtotalWeight,containingtheweightofashipment,andtheother
oftypeint,namedquantity,containingthenumberofitemsintheshipment.Write
anexpressionthatcalculatestheweightofoneitem.
totalWeight/quantity
Youaregiventwovariables,alreadydeclaredandassignedvalues,one
oftypedouble,namedprice,containingthepriceofanorder,andtheother
oftypeint,namedtotalNumber,containingthenumberoforders.Writeanexpressionthat
calculatesthetotalpriceforallorders.
price*totalNumber
Writeanexpressionthatcomputestheaverageofthevalues12and40.
(12+40)/2
Writeanexpressionthatcomputestheintegeraverageof
theintvariablesexam1andexam2(bothdeclaredandassignedvalues).
(exam1+exam2)/2
Thedimensions(widthandlength)ofroom1havebeenreadinto
twovariables:width1andlength1.Thedimensionsofroom2havebeenreadintotwo
othervariables:width2andlength2.Writeasingleexpressionwhosevalueisthetotalareaof
thetworooms.
width1*length1+length2*width2
Eachofthewallsofaroomwithsquaredimensionshasbeenbuiltwithtwopiecesofsheetrock,a
smalleroneandalargerone.Thelengthofallthesmalleronesisthesameandisstoredin
thevariablesmall.Similarly,thelengthofallthelargeronesisthesameandisstoredin
thevariablelarge.Writeasingleexpressionwhosevalueisthetotalareaofthisroom.DO
NOTanymethodinvocations.
(small+large)*(small+large)
WhichofthefollowingisNOTanoperator?add
WhichofthefollowingisNOTanoperator?;

Chapter3
1. Theifstatementisanexampleofadecisionstructure.
2. Thistypeofexpressionhasavauleofeithertrueorfalse.booleanexpression
3. >,<,and==arerelationaloperators.

4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
3.1

&&,ll,and!arelogicaloperators.
Thisisanemptystatementthatdoesnothing.nullstatement.
Tocreateablockofstatements,youenclosethatstatementsinthese.braces{}
Thisisabooleanvariablethatsignalswhensomeconditionexistsintheprogram.Flag
HoedoesthecharacterAcomparetoehcharacterB?AislessthanB
Thisisanifstatementthatappearsinsideanotherifstatement.Nestedifstatement
Anelseclausealwaysgoeswiththeclosestpreviosifclausethatdoesntalreadyhaveitsown
elseclause.
Whendeterminingwhetheranumberisinsidearange,itsbesttousethisoperator.&&
ThisdetermineswhetherteodifferentStringobjectscontainthesamestring.Theequalmethod
Theconditionaloperatortakesthismanyoperands.Three
Thissectionsofaswitchstatementisbranchedtoifnoneofthecaseexpressionsmatchthe
switchexpression.Default
Youcanusthismethodtodisplayformattedoutputinaconsolewindow.System.out.printf
The=operatorandthe==operatorperformthesameoperation.F
Aconditionallyexecutedblockshouldbeindentedonelevelfromtheifclause.T
Alllinesinaconditionallyexecutedblockshouldbeindentedonelevel.T
Whenanifstatementisnestedintheifclauseofanotherstatement,theonlytimetheinnerif
statementisexecutediswhenthebooleanexpressionoftheouterstatementistrue.T
Whenanifstatementisnestedintheelseclauseofanotherstatement,theonlythingtheinnerif
statementisexecutediswhenthebooleanexpressionoftheouterifstatementistrue.F
Thescopeofavariableislimitedtotheblockinwhichitisdefined.T

Writeanexpressionthatevaluatestotrueifandonlyiftheintegerxisgreaterthan
theintegery.
(x>y)
Writeanexpressionthatevaluatestotrueifandonlyifthevalueof
theintegervariablexisequaltozero.
(x==0)
Writeanexpressionthatevaluatestotrueifandonlyif
thevariablesprofitsandlossesareexactlyequal.
(profits==losses)
Writeanexpressionthatevaluatestotrueifthevalueofindexisgreaterthanthevalue
oflastIndex.
index>lastIndex
Workingovertimeisdefinedashavingworkedmorethan40hoursduringtheweek.Given
thevariablehoursWorked,writeanexpressionthatevaluatestotrueiftheemployeeworked
overtime.
hoursWorked>40
Writeanexpressionthatevaluatestotrueifthevaluexisgreaterthanorequaltoy.
x>=y
GiventhevariablesnumberOfMenandnumberOfWomen,writeanexpressionthatevaluates
totrueifthenumberofmenisgreaterthanorequaltothenumberofwomen.
numberOfMen>=numberOfWomen

Givenadoublevariablecalledaverage,writeanexpressionthatistrueifandonlyif
thevariable'svalueisless
than60.0.
average<60.0
GivenanintvariablegrossPay,writeanexpressionthatevaluatestotrueifandonlyif
thevalueofgrossPayisless
than10,000.
grossPay<10000
Writeanexpressionthatevaluatestotrueifthevalueof
theintegervariablenumberOfPrizesisdivisible(withnoremainder)by
theintegervariablenumberOfParticipants.AssumethatnumberOfParticipantsisnotzero.
numberOfPrizes%numberOfParticipants==0
Writeanexpressionthatevaluatestotrueifthevalueof
theintegervariablewidthOfBoxisnotdivisiblebythevalueof
theintegervariablewidthOfBook.AssumethatwidthOfBookisnotzero.("Notdivisible"means
hasaremainder.)
(widthOfBox%widthOfBook!=0)
Writeanexpressionthatevaluatestotrueiftheintegervariablexcontainsanevenvalue,
andfalseifitcontainsanoddvalue.
(x%2==0)
AssumethatabooleanvariableworkedOvertimehasbeendeclared,andthat
anothervariable,hoursWorkedhasbeendeclaredandinitialized.Writeastatementthatassigns
thevaluetruetoworkedOvertimeifhoursWorkedisgreaterthan40andfalseotherwise.
if(hoursWorked>40)
workedOvertime=true;
else
workedOvertime=false;
Writeanexpressionthatevaluatestotrueifandonlyifthevalueof
thebooleanvariableworkedOvertimeistrue.
(workedOvertime==true)
AssumethatabooleanvariableisQuadrilateralhasbeendeclared,andthat
anothervariable,numberOfSideshasbeendeclaredandinitialized.Writeastatement
thatassignsthevaluetrueifnumberOfSidesisexactly4andfalseotherwise.
if(numberOfSides==4)
isQuadrilateral=true;
else
isQuadrilateral=false;
Writeaconditionalthatassigns10,000tothevariablebonusifthevalueof
thevariablegoodsSoldisgreaterthan500,000.
if(goodsSold>500000){
bonus=10000;
}
WriteaconditionalthatdecreasesthevariableshelfLifeby4if
thevariableoutsideTemperatureisgreaterthan90.
if(outsideTemperature>90)
shelfLife=shelfLife4;
Assumethatthevariablesgpa,deansListandstudentName,havebeendeclaredandinitialized.
Writeastatementthatadds1todeansListandprintsstudentNametostandardoutifgpaexceeds
3.5.

3.2

if(gpa>3.5)
{
deansList+=1;
System.out.println(studentName);
}
Writeaconditionalthatassignsthebooleanvaluetruetothevariablefeverif
thevariabletemperatureisgreaterthan98.6.
if(temperature>98.6)
fever=true;
Writeaconditionalthatmultipliesthevalueofthevariablepaybyoneandahalfifthevalue
ofthebooleanvariableworkedOvertimeistrue.
if(workedOvertime==true)
pay=pay*1.5;
Writeanif/elsestatementthatassignstruetothevariablefeverif
thevariabletemperatureisgreaterthan98.6;otherwiseitassignsfalsetofever.
if(temperature>98.6){
fever=true;
}else{
fever=false;
}
AssumethatisIsoscelesisabooleanvariable,andthatthevariablesisoCount,triangleCount,
andpolygonCounthaveallbeendeclaredandinitialized.Writeastatementthatadds1toeach
ofthesecountvariables(isoCount,triangleCount,andpolygonCount)ifisIsoscelesistrue.
if(isIsosceles==true)
{
isoCount+=1;
triangleCount+=1;
polygonCount+=1;
}
Writeanif/elsestatementthatcomparesthevariableagewith65,adds1to
thevariableseniorCitizensifageisgreaterthanorequalto65,andadds1to
thevariablenonSeniorsotherwise.
if(age>=65)
seniorCitizens+=1;
else
nonSeniors+=1;
Writeanif/elsestatementthatcomparesthevalueof
thevariablessoldYesterdayandsoldToday,andbaseduponthat
comparisonassignssalesTrendthevalue1or1.1representsthecase
wheresoldYesterdayisgreater

thansoldToday;1representsthecase
wheresoldYesterdayisnotgreater

thansoldToday.
if(soldYesterday>soldToday)
salesTrend=1;
else
salesTrend=1;

3.3

GivenadoublevariablenamedareaOfSquarewritethenecessarycodetoreadinavalue,the
areaofsomesquare,intoareaOfSquareandprintoutthelengthofthesideofthatsquare.
HOWEVER:ifanyvaluereadinisnotvalidinput,justprintthemessage"INVALID".
ASSUMEtheavailabilityofavariable,stdin,thatreferencesaScannerobjectassociatedwith
standardinput.
areaOfSquare=stdin.nextDouble();
if(areaOfSquare<0)
System.out.print("INVALID");
else
System.out.print(Math.sqrt(areaOfSquare));
GivenaintvariablenamedcallsReceivedand
anotherintvariablenamedoperatorsOnCallwritethenecessarycodetoreadvalues
intocallsReceivedandoperatorsOnCallandprintoutthenumberofcallsreceivedperoperator
(integerdivisionwithtruncationwilldo).HOWEVER:ifanyvaluereadinisnotvalidinput,
justprintthemessage"INVALID".ASSUMEtheavailabilityofavariable,stdin,
thatreferencesaScannerobjectassociatedwithstandardinput.
callsReceived=stdin.nextInt();
operatorsOnCall=stdin.nextInt();
if(operatorsOnCall==0)
System.out.print("INVALID");
else
System.out.print(callsReceived/operatorsOnCall);
Giventhecharvariablec,writeanexpressionthatistrueifandonlyifthevalueofcisnot
thespacecharacter.
c!=''
Assumethatcisacharvariablehasbeendeclaredandalreadygivenavalue.Write
anexpressionwhosevalueistrueifandonlyifcisanewlinecharacter.
(c=='\n')
Assumethatcisacharvariablehasbeendeclaredandalreadygivenavalue.Write
anexpressionwhosevalueistrueifandonlyifcisaspacecharacter.
(c=='')
Assumethatcisacharvariablehasbeendeclaredandalreadygivenavalue.Write
anexpressionwhosevalueistrueifandonlyifcisatabcharacter.
(c=='\t')
Assumethatcisacharvariablehasbeendeclaredandalreadygivenavalue.Write
anexpressionwhosevalueistrueifandonlyifciswhatiscalledawhitespacecharacter(that
isaspaceorataboranewlinenoneofwhichresultininkbeingprintedonpaper).
(c==''||c=='\n'||c=='\t')
Assumethatcisacharvariablehasbeendeclaredandalreadygivenavalue.Write
anexpressionwhosevalueistrueifandonlyifcisNOTwhatiscalledawhitespacecharacter
(thatisaspaceorataboranewlinenoneofwhichresultininkbeingprintedonpaper).
!(c==''||c=='\n'||c=='\t')
Assumethatanintvariableagehasbeendeclaredandalreadygivenavalue.Assumefurther
thattheuserhasjustbeenpresentedwiththefollowingmenu:

S:hangarsteak,redpotatoes,asparagus

T:wholetrout,longrice,brusselsprouts

B:cheddarcheeseburger,steakfries,coleslaw

(Yes,thismenureallyISamenu!)
WritesomecodethatreadstheString(SorTorB)thattheusertypesininto
aStringvariablechoicethathasalreadybeendeclaredandprintsoutarecommended
accompanyingdrinkasfollows:ifthevalueofageis21orlower,therecommendationis
"vegetablejuice"forsteak,"cranberryjuice"fortrout,and"soda"fortheburger.
Otherwise,therecommendationsare"cabernet","chardonnay",and"IPA"forsteak,
trout,andburgerrespectively.Regardlessofthevalueofage,yourcodeshouldprint
"invalidmenuselection"ifthecharacterreadintochoicewasnotSorTorB.
choice=stdin.next();
if(choice.equals("S")){
if(age<=21)System.out.println("vegetablejuice");
elseSystem.out.println("cabernet");
}elseif(choice.equals("T")){
if(age<=21)System.out.println("cranberryjuice");
elseSystem.out.println("chardonnay");
}elseif(choice.equals("B")){
if(age<=21)System.out.println("soda");
elseSystem.out.println("IPA");
}else
System.out.println("invalidmenuselection");
OnlineBookMerchantsofferspremiumcustomers1freebookwitheverypurchaseof5ormore
booksandoffers2freebookswitheverypurchaseof8ormorebooks.Itoffersregularcustomers
1freebookwitheverypurchaseof7ormorebooks,andoffers2freebookswitheverypurchase
of12ormorebooks.WriteastatementthatassignsfreeBookstheappropriatevaluebasedon
thevaluesofthebooleanvariableisPremiumCustomerandtheintvariablenbooksPurchased.
o

freeBooks=0;
if(isPremiumCustomer==true){
if(nbooksPurchased>=5)freeBooks=1;
if(nbooksPurchased>=8)freeBooks=2;
}elseif(isPremiumCustomer==false){
if(nbooksPurchased>=7)freeBooks=1;
if(nbooksPurchased>=12)freeBooks=2;
}
3.9

Writeaswitch

statementthatteststhevalueofthecharvariableresponseandperformsthe
followingactions:
o

ifresponseisy,themessageYourrequestisbeingprocessedisprinted

ifresponseisn,themessageThankyouanywayforyourconsiderationisprinted

ifresponseish,themessageSorry,nohelpiscurrentlyavailableisprinted

foranyothervalueofresponse,themessageInvalidentry;pleasetryagainisprinted

switch(response)
{
case'y':
System.out.println("Yourrequestisbeingprocessed");
break;
case'n':
System.out.println("Thankyouanywayforyourconsideration");
break;
case'h':
System.out.println("Sorry,nohelpiscurrentlyavailable");
break;
default:
System.out.println("Invalidentry;pleasetryagain");
}
HTTPistheprotocolthatgovernscommunicationsbetweenwebserversandwebclients(i.e.
browsers).Partoftheprotocolincludesastatuscodereturnedbytheservertotellthebrowserthe
statusofitsmostrecentpagerequest.Someofthecodesandtheirmeaningsarelistedbelow:
o

200,OK(fulfilled)

403,forbidden

404,notfound

500,servererror

Givenanintvariablestatus,writeaswitch

statementthatprintsout,onalinebyitself,
theappropriatelabelfromtheabovelistbasedonstatus.

switch(status)
{
case200:
System.out.println("OK(fulfilled)");
break;
case403:
System.out.println("forbidden");
break;
case404:
System.out.println("notfound");
break;
case500:
System.out.println("servererror");
break;

IntheHappyValleySchoolSystem,childrenareclassifiedbyageasfollows:
o

lessthan2,ineligible

2,toddler

35,earlychildhood

67,youngreader

810,elementary

11and12,middle

13,impossible

1416,highschool

1718,scholar

greaterthan18,ineligible

Givenanintvariableage,writeaswitchstatementthatprintsout,onalinebyitself,
theappropriatelabelfromtheabovelistbasedonage.

switch(age)
{
case0:
case1:
System.out.println("ineligible");
break;
case2:
System.out.println("toddler");
break;
case3:
case4:
case5:
System.out.println("earlychildhood");
break;
case6:
case7:
System.out.println("youngreader");
break;
case8:
case9:
case10:

System.out.println("elementary");
break;
case11:
case12:
System.out.println("middle");
break;
case13:
System.out.println("impossible");
break;
case14:
case15:
case16:
System.out.println("highschool");
break;
case17:
case18:
System.out.println("scholar");
break;
default:
System.out.println("ineligible");
}
GivenaintvariablenamedyesCountandanotherintvariablenamednoCountand
anintvariablenamedresponsewritethenecessarycodetoreadavalueintointoresponseand
thencarryoutthefollowing:
o

ifthevaluetypedinisa1ora2thenincrementyesCountandprintout"YESWAS
RECORDED"

ifthevaluetypedinisa3oran4thenincrementnoCountandprintout"NOWAS
RECORDED

Iftheinputisinvalidjustprintthemessage"INVALID"anddonothingelse.

ASSUMEtheavailabilityofavariable,stdin,thatreferencesaScannerobject
associatedwithstandardinput.

response=stdin.nextInt();
if(response==1||response==2)
{
yesCount++;
System.out.print("YESWASRECORDED");
}
elseif(response==3||response==4)
{
noCount++;
System.out.print("NOWASRECORDED");
}
else

System.out.print("INVALID");
Chapter4
1. Whatwilltheprintlnstatementinthefollowingprogramsegmentdisplay?
intx=5;
System.out.println(x++);
5
2. Whatwilltheprintlnstatementinthefollowingprogramsegmentdisplay?
intx=5;
System.out.println(++x);
6
3. Intheexpressionnumber++,the++operatorisinwhatmode?Postfix
4. Whatiseachrepetitionofaloopknownas?Iteration
5. Thisisavariablethatcontrolsthenumberofiterationsperformedbyaloop.Loopcontrol
variable
6. Thewhileloopisthistypeofloop.Pretest
7. Thedowhileloopisthistypeofloop.Posttest
8. Theforloopisthistypeofloop.Pretest
9. Thistypeofloophasnowayofendingandrepeatsuntiltheprogramisinterrupted.Infinite
19.Thewhileloopisapretestloop.T
20.Thedowhileloopisapretestloop.F
21.Theforloopisaposttestloop.F
22.Itisnotnecessarytoinitializeaccumulatorvariables.F
23.Onelimitationoftheforloopisthatinlyonevariablemaybeinitializedintheinitialization
expression.F
24.Avariablemaybedefinedintheinitializationexpressionoftheforloop.T
25.Inanestedloop,theinnerloopgoesthroughallofitsiterationsforeveryiterationoftheouter
loop.T
26.Tocalculatethetotalnumberofiterationsofanestedloop,addthenumberofiterationsofall
loops.F
4.1
GivenanintegervariablestrawsOnCamel,writeastatementthatusestheauto
incrementoperatortoincreasethevalueofthatvariableby1.
strawsOnCamel++;
Givenanintegervariabletimer,writeastatementthatusestheautodecrement

operator
todecreasethevalueofthatvariableby1.
timer;
Considerthiscode:"intv=20;v;System.out.println(v++);".Whatvalueisprinted,whatvalue
isvleftwith?19isprinted,vendsupwith20
Considerthiscode:"ints=20;intt=s+++s;".Whatarethevaluesofsandt?sis20andtis
40
4.2

Givenanintvariablekthathasalreadybeendeclared,useawhile

looptoprintasingleline
consistingof88asterisks.Usenovariablesotherthank.
k=0;
while(k<88)

{
System.out.print("*");
k=k+1;
}
Givenanintvariablenthathasalreadybeendeclaredandinitializedtoapositivevalue,use
awhile

looptoprintasinglelineconsistingofnasterisks.Usenovariablesotherthann.
while(n!=0)
{
System.out.print("*");
n=n1;
}

4.4

4.5

Givenanintvariablekthathasalreadybeendeclared,useado...while

looptoprintasingle
lineconsistingof53asterisks.Usenovariablesotherthank.
k=0;
do
{
System.out.print("*");
k++;
}
while(k<53);
Givenanintvariablenthathasalreadybeendeclaredandinitializedtoapositivevalue,use
ado...while

looptoprintasinglelineconsistingofnasterisks.Usenovariablesotherthann.
do
{
System.out.print("*");
n;
}while(n>0);
Givenanintvariablekthathasalreadybeendeclared,useafor
looptoprintasingleline
consistingof97asterisks.Usenovariablesotherthank.
for(k=1;k<=97;k++)
{
System.out.print("*");
}
Givenanintvariablenthathasalreadybeendeclaredandinitializedtoapositivevalue,and
anotherintvariablejthathasalreadybeendeclared,useafor
looptoprintasingleline
consistingofnasterisks.Thusifncontains5,fiveasteriskswillbeprinted.Usenovariables
otherthannandj.
for(j=0;j<n;j++)
{
System.out.print("*");
}
Writeaforloopthatprintstheintegers0through39,separatedbyspaces.

for(intn=0;n<40;n++)
System.out.print(n+"");
Writeaforloopthatprintstheoddintegers11through121inclusive,separatedbyspaces.
for(intn=11;n<=121;n=n+2)
System.out.print(n+"");
Writeaforloopthatprintsinascendingorderallthepositivemultiplesof5thatarelessthan
175,separatedbyspaces.
for(intn=5;n<175;n=n+5)
System.out.print(n+"");
Writeaforloopthatprintstheintegers50through1,separatedbyspaces.Usenovariables
otherthancount
for(intcount=50;count>=1;count)
System.out.print(count+"");
Writeaforloopthatprintsalltheevenintegersfrom80through20inclusive,separatedby
spaces.
for(intn=80;n>=20;n=n2)
System.out.print(n+"");
Writeaforloopthatprintsinascendingorderallthepositiveintegerslessthan200thatare
divisiblebyboth2and3,separatedbyspaces.
for(intcount=1;count<200;count++)
{
if(count%2==0)
{
if(count%3==0)
System.out.print(count+"");
}
}

You might also like