Java Exercises JAVA练习题.docx

上传人:b****5 文档编号:12367829 上传时间:2023-04-18 格式:DOCX 页数:22 大小:359.05KB
下载 相关 举报
Java Exercises JAVA练习题.docx_第1页
第1页 / 共22页
Java Exercises JAVA练习题.docx_第2页
第2页 / 共22页
Java Exercises JAVA练习题.docx_第3页
第3页 / 共22页
Java Exercises JAVA练习题.docx_第4页
第4页 / 共22页
Java Exercises JAVA练习题.docx_第5页
第5页 / 共22页
点击查看更多>>
下载资源
资源描述

Java Exercises JAVA练习题.docx

《Java Exercises JAVA练习题.docx》由会员分享,可在线阅读,更多相关《Java Exercises JAVA练习题.docx(22页珍藏版)》请在冰豆网上搜索。

Java Exercises JAVA练习题.docx

JavaExercisesJAVA练习题

1.5InputandOutput

Exercises

1WriteaprogramMaxMin.javathatreadsinintegers(asmanyastheuserenters)fromstandardinputandprintsoutthemaximumandminimumalues.

2Modifyyourprogramfromthepreviousexercisetoinsistthattheintegersmustbepositive(bypromptingtheusertoenterpositiveintegerswheneverthevalueenteredisnotpositive).

3WriteaprogramStats.javathattakesanintegerNfromthecommandline,readsNdoublevaluesfromstandardinput,andprintstheirmean(averagevalue)andstandarddeviation(squarerootofthesumofthesquaresoftheirdifferencesfromtheaverage,dividedbyN-1).

4Extendyourprogramfromthepreviousexercisetocreateafilterthatprintsallthevaluesthatarefurtherthan1.5standarddeviationsfromthemean.

5WriteaprogramLongestRun.javathatreadsinasequenceofintegersandprintsoutboththeintegerthatappearsinalongestconsecutiverunandthelengthoftherun.Forexample,iftheinputis1221511777711,thenyourprogramshouldprintLongestrun:

4consecutive7s.

6Writeafilterthatreadsinasequenceofintegersandprintsouttheintegers,removingrepeatedvaluesthatappearconsecutively.Forexample,iftheinputis12215117777111111111,yourprogramshouldprintout1215171.

7Writeaprogramthattakesacommand-lineargumentN,readsinN-1distinctintegersbetween1andN,anddeterminesthemissingvalue.

8WriteaprogramGeometricMean.javathatreadsinpositiverealnumbersfromstandardinputandprintsouttheirgeometricmean.ThegeometricmeanofNpositivenumbersx1,x2,...,xNis(x1*x2*...*xN)1/N.WriteaprogramHarmonicMean.javathatreadsinpositiverealnumbersfromstandardinputandprintsouttheirharmonicmean.TheharmonicmeanofNpositivenumbersx1,x2,...,xNis(1/x1+1/x2+...+1/xN)/(1/N).

Hint:

forthegeometricmean,considertakinglogstoavoidoverflow.

9Supposethatthefileinput.txtcontainsthetwostringsFandF.Whatdoesthefollowingcommanddo(seeExercises1.2.35)?

HereistheJavaprogramDragon.java.

javaDragon

10WriteafilterTenPerLine.javathattakesasequenceofintegersbetween0and99andprints10integersperline,withcolumnsaligned.ThenwriteaprogramRandomIntSeqthattakestwocommand-lineargumentsMandNandoutputsNrandomintegersbetween0andM-1.TestyourprogramswiththecommandjavaRandomIntSeq200100|javaTenPerLine.

11WriteaprogramWordCount.javathatreadsintextfromstandardinputandprintsoutthenumberofwordsinthetext.Forthepurposeofthisexercise,awordisasequenceofnon-whitespacecharactersthatissurroundedbywhitespace.

12Writeaprogramthatreadsinlinesfromstandardinputwitheachlinecontaininganameandtwointegersandthenusesprintf()toprintatablewithacolumnofthenames,theintegers,andtheresultofdividingthefirstbythesecond,accuratetothreedecimalplaces.Youcoulduseaprogramlikethistotabulatebattingaveragesforbaseballplayersorgradesforstudents.

13Whichofthefollowingrequiresavingallthevaluesfromstandardinput(inanarray,say),andwhichcouldbeimplementedasafilterusingonlyafixednumberofvariables?

Foreach,theinputcomesfromstandardinputandconsistsofNrealnumbersbetween0and1.

∙Printthemaximumandminimumnumbers.

∙Printthekthsmallestvalue.

∙Printthesumofthesquaresofthenumbers.

∙PrinttheaverageoftheNnumbers.

∙Printthepercentageofnumbersgreaterthantheaverage.

∙PrinttheNnumbersinincreasingorder.

∙PrinttheNnumbersinrandomorder.

14Writeaprogramthatprintsatableofthemonthlypayments,remainingprincipal,andinterestpaidforaloan,takingthreenumbersascommand-linearguments:

thenumberofyears,theprincipal,andtheinterestrate(seeExercise1.2.24).

15WriteaprogramClosest.javathattakesthreecommand-lineargumentsx,y,z,readsfromstandardinputasequenceofpointcoordinates(xi,yi,zi),andprintsthecoordinatesofthepointclosestto(x,y,z).Recallthatthesquareofthedistancebetween(x,y,z)and(xi,yi,zi)is(x-xi)2+(y-yi)2+(z-zi)2.Forefficiency,donotuseMath.sqrt()orMath.pow().

16Giventhepositionsandmassesofasequenceofobjects,writeaprogrmtocomputetheircenter-of-massorcentroid.ThecentroidistheaveragepositionoftheNobjects,weightedbymsass.Ifthepositionsandmassesaregivenby(xi,yi,mi),thenthecentroid(x,y,m)isgivenby:

m=m1+m2+...+mN

x=(m1x1+...+mnxN)/m

y=(m1y1+...+mnyN)/m

WriteaprogramCentroid.javathatreadsinasequenceofpositionsandmasses(xi,yi,mi)fromstandardinputandprintsouttheircenterofmass(x,y,m).Hint:

modelyourprogramafterAverage.java.

17WriteaprogramSignalAnalyzer.javathatreadsinasequenceofrealnumbersbetween-1and1andprintsouttheiraveragemagnitude,averagepower,andthenumberofzerocrossings.Theaveragemagnitudeistheaverageoftheabsolutevaluesofthedatavalues.Theaveragepoweristheaverageofthesquaresofthedatavalues.Thenumberofzerocrossingsisthenumberoftimesadatavaluetransitionsfromastrictlynegativenumbertoastrictlypositivenumber,orviceversa.Thesethreestatisticsarewidelyusedtoanalyzedigitalsignals.

18WriteaprogramCheckerBoard.javathattakesacommand-lineargumentNandplotsanN-by-Ncheckerboardwithredandblacksquares.Colorthelowerleftsquarered.

19Writeaprogramthattakesascommand-lineargumentsanintegerNandadoublevaluep(between0and1),plotsNequallyspacedpointsofsizeonthecircumferenceofacircle,andthen,withprobabilitypforeachpairofpoints,drawsagraylineconnectingthem.

20Writecodetodrawhearts,spades,clubs,anddiamonds.Todrawaheart,drawadiamond,thenattachtwosemicirclestotheupperleftandupperrightsides.

21WriteaprogramRose.javathattakesacommand-lineargumentNandplotsarosewithNpetals(ifNisodd)or2Npetals(ifNiseven)byplottingthepolarcoordinates(r,θ)ofthefunctionr=sin(N×θ)forθrangingfrom0to2πradians.BelowisthedesiredoutputforN=4,7,and8.

22WriteaprogramBanner.javathattakesastringsfromthecommandlineanddisplayitinbannerstyleonthescreen,movingfromlefttorightandwrappingbacktothebeginningofthestringastheendisreached.Addasecondcommand-lineargumenttocontrolthespeed.

23ModifyPlayThatTune.javatotakeadditionalcommand-lineargumentsthatcontrolthevolume(multiplyeachsamplevaluebythevolume)andthetempo(multiplyeachnotesdurationbythetempo).

24Writeaprogramthattakesthenameofa.wavfileandaplaybackraterascommand-lineargumentsandplaysthefileatthegivenrate.First,useStdAudio.read()toreadthefileintoanarraya[].Ifr=1,justplaya[];otherwisecreateanewarrayb[]ofapproximatesizertimesa.length.Ifr<1,populateb[]bysamplingfromtheoriginal;ifr>1,populateb[]byinterpolatingfromtheoriginal.Thenplayb[].

25WriteprogramsthatusesStdDrawtocreateeachofthefollowingdesigns.

26

27WriteaprogramCircles.javathatdrawsfilledcirclesofrandomsizeatrandompositionsintheunitsquare,producingimageslikethosebelow.Yourprogramshouldtakefourcommand-linearguments:

thenumberofcircles,theprobabilitythateachcircleisblack,theminimumradius,andthemaximumradius.

CreativeExercises

28Visualizingaudio.ModifyPlayThatTune.javatosendthevaluesplayedtostandarddrawing,sothatyoucanwatchthesoundwavesastheyareplayed.Youwillhavetoexperimentwithplottingmultiplecurvesinthedrawingcanvastosynchronizethesoundandthepicture.

29Statisticalpolling.Whencollectingstatisticaldataforcertainpoliticalpolls,itisveryimportanttoobtainanunbiasedsampleofregisteredvoters.AssumethatyouhaveafilewithNregisteredvoters,oneperline.WriteafilterthatprintsoutarandomsampleofsizeM(seeProgram1.4.1).

30Terrainanalysis.Supposethataterrainisrepresentedbyatwo-dimensionalgridofelevationvalues(inmeters).Apeakisagridpointwhosefourneighboringcells(left,right,up,anddown)havestrictlylowerelevationvalues.WriteaprogramPeaks.javathatreadsaterrainfromstandardinputandthencomputesandprintsthenumberofpeaksintheterrain.

31Histogram.Supposethatthestandardinputstreamisasequenceofdoublevalues.WriteaprogramthattakesanintegerNandtwodoublevalueslandrfromthecommandlineandusesStdDrawtoplotahistogramofthecountofthenumbersinthestandardinputstreamthatfallineachoftheNintervalsdefinedbydividing(l,r)intoNequal-sizedintervals.

32Spirographs.WriteaprogramSpirograph.javathattakesthreecommand-lineargumentsR,r,andaanddrawstheresultingspirograph.Aspirograph(technically,anepicycloid)isacurveformedbyrollingacircleofradiusraroundalargerfixedcircleorradiusR.Ifthepenoffsetfromthecenteroftherollingcircleis(r+a),thentheequationoftheresultingcurveattimetisgivenby

x(t)=(R+r)*cos(t)-(r+a)*cos(((R+r)/r)*t)

y(t)=(R+r)*sin(t)-(r+a)*sin(((R+r)/r)*t)

Suchcurveswerepopularizedbyabest-sellingtoythatcontainsdiscswithgearteethontheedgesandsmallholesthatyoucouldputapenintotracespirographs.

Foradramatic3deffect,drawacircularimage,e.g.,earth.gifinsteadofadot,andshowitrotatingovertime.Here'sapictureoftheresultingspirographwhenR=180,r=40,anda=15.

33Clock.WriteaprogramClock.javathatdisplaysananimation

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

当前位置:首页 > 初中教育 > 学科竞赛

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

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