Java实验指导书Word文件下载.docx
《Java实验指导书Word文件下载.docx》由会员分享,可在线阅读,更多相关《Java实验指导书Word文件下载.docx(34页珍藏版)》请在冰豆网上搜索。
}
3.Tocompiletheprogram,enterthiscommandintotheDOSwindow:
C:
\SomeDir>
IamINFO.java
4.Thecompilerwillcreateafilecontaining.Thisfilewillbenamed.
5.Torunthebytecodes,enterthiscommandintotheDOSwindow:
IamINFO
ProgrammingExercises2(twohours)
ModifytheCarclassofthechapterbyaddingtwomethods:
booleangasHog()
evaluatestotrueifthemilespergallonislowerthan15.0.
booleaneconomyCar()
evaluatestotrueifthemilespergallonishigherthan30.0.
TheconstructorandthecalculateMPG()methodremainunchanged.EachofthesenewmethodsshouldusethecalculateMPG()togetthemilespergallon,notcalculateitthemselves.Anif-elsestatementpicksthecorrectbooleanreturnvalue.
Putuserinteractionbackintothemain()methodmethodsotheuserentersvaluesforeachcar.Themain()methodusestheseadditionalmethodstowriteamessagetotheuserifthecarisagashogoraneconomycar.
Youmightbetemptedtomakeoneofthesecommondesignerrors:
SavingmilespergalloninaninstancevariableoftheobjectalongwithstartMiles,endMiles,andgallons.
Thisalmostseemslogical,butisapoordesign.Don'
tkeepapermanentcopyofavaluethatcanbeeasilycalculatedfromdata.Thereasonforthisisthatitaddscomplexitytotheobject,butofferslittleadvantage.
Directlycalculatingmilespergalloninsideeachofthenewmethods.
Itisusuallybesttodoaparticularcalculationinonlymethod,andtouseitwheneverthecalculationisneeded.Nowifthereisabuginthecalculation,orthecalculationmustbemodified,thereisonlyoneplacetolook.
\>
javaMiles
Enterfirstreading:
10000
Entersecondreading:
10400
Entergallons:
10
Milespergallon:
40
EconomyCar!
intfirst;
//thenumberofintegerstoaddup
Stringline;
BufferedReaderstdin=newBufferedReader(
newInputStreamReader(System.in));
//getthenumberofintegerstoaddup
line=stdin.readLine();
first=Integer.parseInt(line.trim());
importjava.io.*;
classCar
{
//instancevariables
intstartMiles;
//Statingodometerreading
intendMiles;
//Endingodometerreading
doublegallons;
//Gallonsofgasused
//constructor
Car(intfirst,intlast,doublegals)
{
startMiles=first;
endMiles=last;
gallons=gals;
//methods
doublecalculateMPG()
return(endMiles-startMiles)/gallons;
classMilesPerGallon
publicstaticvoidmain(String[]args)
Carcar=newCar(32456,32810,10.6);
System.out.println("
Milespergallonis"
+car.calculateMPG());
ProgrammingExercises3(fourhours)
Part1ImmutableBox
ImplementaclassBoxsimilartotheclassinapreviousreviewexercise.ButthenewimplementationofBoxwillhavebetterencapsulation.HereisthedocumentationforBox:
classBox
Aclassthatimplementsacardboardbox.
Constructors
Box(doublewidth,doubleheight,doublelength)
Box(doubleside)
Methods
doublevolume()
doublearea()
Lookatthepreviousprogrammingexerciseformorediscussionandforcodewhicheasilycanbemodifiedforthisandthenexttwoexercises.
InthecurrentimplementationofBoxmakealltheinstancevariablesprivate.ThismeansthatonlymethodsofaBoxobjectcanseethatobject'
sdata.Theobjectwillbeimmutableiftherearenoaccessmethodsthatmakechangestothisdata.Animmutableobjectisonewhosedatadoesnotchange.YoumayrememberthatStringobjectsareimmutable---oncethecharactersoftheStringaresetwithaconstructortheyneverchange(althoughtheycanbeusedtocreateotherStringobjects.)Therearemanyadvantagestousingimmutableobjects,especiallywhenprogrammingwiththreads(whichishownearlyallbigprogramsarewritten.)
GivepublicaccesstothemethodsofBox.
TestyourBoxclasswithseveralversionsofthisprogram:
importBox;
classBoxTester
publicstaticvoidmain(String[]args)
Boxbox=newBox(2.5,5.0,6.0);
Area:
"
+box.area()+"
volume:
+box.volume());
length:
+box.length+"
height:
+box.height+
width:
+box.width);
Part2:
PrivateMethodsforBox
Theimplementationofarea()giveninthepreviousreviewexerciseisprobablyreasonablefortheBoxclass.Buttopracticeprivatemethodswriteitlikethis:
doublearea()
return2*faceArea()+2*topArea()+2*sideArea();
Inthis,faceArea(),topArea(),andsideArea()areprivatemethodsthatcalculatetheareaofthefrontface,thetopandthesideofthebox.Youwillhavetoaddthemtoyourclass.Oftenprivatemethodsare"
helping"
methodsthatthepublicmethodsuse,butarenottobeusedoutsidetheclass.Testyourprogramwithseveralversionsofthefollowing:
topArea:
+box.topArea());
(Theaboveprogramwillnotcompile,asexpected.)
Part3:
BoxConstructorandAccessMethods
AddanewconstructortotheBoxclass:
Box(BoxoldBox)
ThisconstructorcreatesanewBoxobjectwithidenticaldimensionsastheoldBoxobject.Ofcourse,theoldobjectisnotchanged.
Nowaddsomeaccessmethods.Anaccessmethodisamethodthatcanbeusedtoaccesstheprivatevariables(andothervariables)ofanobject:
publicdoublelength()
publicdoubleheight()
publicdoublewidth()
Eachofthesemethodsmerelyreturnsthevalueofoneinstancevariable.Sincetheobjectisimmutable,therewillbenoaccessmethodsthataltertheinstancevariables.Testyouprogramwithmodificationsoftheprevioustestingclass.
Exercise4:
BiggerBoxes
Itwouldbenicetocreateaboxthatisbiggerthanagivenbox.Writethismethod:
publicBoxbiggerBox(BoxoldBox)
Thisisapublicmethodthatreturns(evalutesto)areferencetoanewBox.ThenewBoxwillbe25%largerineachdimensionthattheoldbox.Themethodwillhavetouseaconstructorinsideofittocreatethenewbox:
returnnewBox(1.25*oldBox.width(),......)
Nowwriteamethodthatreturnsaboxthatis25%smallerineverydimensionthanagivenbox.Asusual,writeatestingprogramthatexercisesyourclass.
Part5:
NestingBoxes
Writeamethodthatevaluatestotrueorfalsedependingonwhetheroneboxcompletelyfitsinsideanother:
publicbooleannests(BoxoutsideBox,BoxinsideBox)
Thisispotentiallyadifficultmethod,sincetheinsideboxmayfitornotfitdependingonhowitisrotated.Tosimplifythemethod,writeitsothatitreturnstrueifthetwoboxesnestwithoutconsideringrotations(soheightiscomparedtoheight,lengthcomparedtolength,andsoon.)
Whattoturnin:
Ifthiswereanassignmentinaregularclassyoumightbeaskedtoturninthefollowing:
Neatlywrittendocumentationofthefinalversionofyourclass.
Writethedocumentationinthestylegivenatthetopofthispage,similarinstyletomostJavaclassdocumentation.
Shortcommentsdescribeeachmethodandconstructor.
Privateinstancevariablesandprivatemethodsarenotmentionedinthisdocumentation.Thedocumentationissupposedtodescribetheinterfacetousersoftheclass.
Thesourcecodeforthefinalimplementationoftheclass.
Commentsatthetopofthesoucedescribewhatitis,whowroteit,whenitwaswritten,andwhatisdebuggingstatusis.
Shortcommentsareusedtoexplaineachmethodandsomestatements.
Indentingandblanklinesmustbeusedtoshowthestructureandorganizationoftheclass.
Sourcecodeandoutputforseveralsmallprogramsthattestthevariousfeaturesoftheclass.
Often,puttingtogetherthematerialtoturninisasubstantialpartofthework.Thisisgoodpracticeforthe"
realworld."
classBox
//InstanceVariables
doublelength;
doublewidth;
doubleheight;
//Constructors
Box(doublewidth,doubleheight,doublelength)
this.width=width;
this.height=height;
this.length=length;
Box(doubleside)
width=side;
height=side;
length=side;
//Methods
doublevolume()
returnwidth*height*length;
return2*(*+
*+
*);
import;
//createaboxwithsides=2.5,3.0,and5.0
Boxbox1=newBox(2.5,3.0,5.0);
Box1Area:
+box1.area()+
Volume:
+box1.volume());
//createaboxwithallsides=3.0
Boxbox2=Box();
Box2Area:
+box2.area()+
+box2.volume());
Part1UserInteraction.
ModifythePantryTesterclasssothatitcarriesoutadialogwiththeuser:
WelcometoMotherHubbard'
sPantry!
Thejamsare:
1:
Gooseberry7/4/8612fl.oz.
2:
CrabApple9/30/998fl.oz.
3:
Rhubarb10/31/9916fl.oz.
Enteryourselection(1,2,or3):
1
Enteramounttospread:
2
Spreading2fluidouncesofGooseberry
Gooseberry7/4/8610fl.oz.