Java实验指导书Word文件下载.docx

上传人:b****5 文档编号:20974976 上传时间:2023-01-26 格式:DOCX 页数:34 大小:178.57KB
下载 相关 举报
Java实验指导书Word文件下载.docx_第1页
第1页 / 共34页
Java实验指导书Word文件下载.docx_第2页
第2页 / 共34页
Java实验指导书Word文件下载.docx_第3页
第3页 / 共34页
Java实验指导书Word文件下载.docx_第4页
第4页 / 共34页
Java实验指导书Word文件下载.docx_第5页
第5页 / 共34页
点击查看更多>>
下载资源
资源描述

Java实验指导书Word文件下载.docx

《Java实验指导书Word文件下载.docx》由会员分享,可在线阅读,更多相关《Java实验指导书Word文件下载.docx(34页珍藏版)》请在冰豆网上搜索。

Java实验指导书Word文件下载.docx

}

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.

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 自然科学 > 天文地理

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1