21 Pages

17-lunar-lander

Course: CIT 591, Fall 2009
School: UPenn
Rating:
 
 
 
 
 

Word Count: 1237

Document Preview

Lander An Lunar Example of Interacting Classes Apr 10, 2009 LunarLanderGame This class contains the publicstaticvoidmain(String[]args) method. In this method, you should (1) create a LunarLander object, (2) create an IOFrame object, and (3) send messages to these two objects in order to get the burn rate from the user, tell the lander what to do, find out the lander status, and report the status back to the...

Register Now

Unformatted Document Excerpt

Coursehero >> Pennsylvania >> UPenn >> CIT 591

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
Lander An Lunar Example of Interacting Classes Apr 10, 2009 LunarLanderGame This class contains the publicstaticvoidmain(String[]args) method. In this method, you should (1) create a LunarLander object, (2) create an IOFrame object, and (3) send messages to these two objects in order to get the burn rate from the user, tell the lander what to do, find out the lander status, and report the status back to the user. When the lander's altitude is less than or equal to zero, the game ends (one way or the other). When the game finishes, you should ask the user whether he/she would like to play again. Allow as many games as the user wants before quitting the program. 2 Additional constraints At the time this program was assigned, we had: Classes and methods Declarations, with and without initialization Assignment statements while loops if and ifelse statements System.out.print and System.out.println The first version of this program reflects these constraints 3 publicstaticvoidmain(String[]args) Heres the outline of the mainmethod: publicstaticvoidmain(String[]args){ IOFrameframe=newIOFrame("LunarLander"); LunarLanderlander; doublesafeLandingSpeed=10.0; Stringagain="yes"; //MainloopOnegameisoncethroughtheloop //Innerloop:PlayuntiltheLandercrashesorlands frame.exit(); } 4 Main loop Recall that we had a Stringagain="yes"; declaration Heres the main loop: while("yes".equals(again)){ //setup lander=newLunarLander(100,0,15); frame.clear(); frame.displayLine("Altitude:"+lander.getAltitude()); frame.displayLine("Velocity:"+lander.getVelocity()); frame.displayLine("Fuelleft:"+lander.getFuelRemaining()); //innerlooptoplaythegame //telluserhowgameended again=frame.getString("Wouldyouliketoplayagain?"); } 5 Inner loop to play game //innerlooptoplayonegame while(lander.getAltitude()>0){ doubleamount=frame.getDouble("HowmuchfuelshouldIburn?"); lander.burn(amount); frame.displayLine(""); frame.displayLine("Altitude:"+lander.getAltitude()); frame.displayLine("Velocity:"+lander.getVelocity()); frame.displayLine("Fuelleft:"+lander.getFuelRemaining()); } //telluserhowgameended doublefinalVelocity=lander.getVelocity(); if(finalVelocity>safeLandingSpeed){ frame.display("CRASH!"); } else{ frame.display("Congratulations!Asafelanding!"); } 6 LunarLander instance variables publicclassLunarLander{ doublealtitude; doublevelocity; doublefuel; finaldoubleacceleration=1.64; finaldoublefuelFactor=1.0; finaldoublefuelLimit=2.0; Where: acceleration is the Moons gravity (meters/second/second) fuelFactor is how much to reduce the velocity per unit of fuel burned fuelLimit is the maximum amount of fuel that can be burned at once 7 The LunarLander constructor LunarLander(doublealtitude,doublevelocity, doublefuel){ this.altitude=altitude; this.velocity=velocity; this.fuel=fuel; } 8 The burn(double) method This is the method that does all the work of the LunarLanderit recomputes velocity, altitude, and fuel remaining voidburn(doubleamount){ if(amount>fuel)amount=fuel; if(amount>fuelLimit)amount=fuelLimit; velocity=velocity+accelerationamount*fuelFactor; fuel=fuelamount; altitude=altitudevelocity; } 9 The getter methods doublegetFuelRemaining(){ returnfuel; } doublegetAltitude(){ returnaltitude; } doublegetVelocity(){ returnvelocity; } Thats all... ...but the program could be improved 10 Part II Improving the Lunar Lander program Refactoring Refactoring is the process of rearranging and modifying code to improve it (without changing what it does) The following lines occur twice in the code: frame.displayLine("Altitude:"+lander.getAltitude()); frame.displayLine("Velocity:"+lander.getVelocity()); frame.displayLine("Fuelleft:"+lander.getFuelRemaining()) Duplicated code is bad because, if you have to change it, you have to change it everyplace it is used One way to avoid code repetition is to put the offending code into a method This particular refactoring is called Method Extract It isnt necessarily a single-step method Ill do it informally 12 Extract Method IdisplayStatus() I create the following method: voiddisplayStatus(){ frame.displayLine("Altitude:"+lander.getAltitude()); frame.displayLine("Velocity:"+lander.getVelocity()); frame.displayLine("Fuelleft:"+lander.getFuelRemaining()); } displayStatus(); I call our new method this way (in two places): This gives me syntax errors, because both frame and lander are local variables in main I have three choices: Pass in frame and lander as parameters Make frame and lander instance variables of LunarLanderGame Make frame and lander class variables of LunarLanderGame 13 Extract Method IIframe I only ever want one IOFrame, so it makes sense to make frame a static variable I move this line IOFrameframe=newIOFrame("LunarLander"); out of the main method, put the word static in front of it, and make it a field of the LunarLanderGameclass publicclassLunarLanderGame{ staticIOFrameframe=newIOFrame("LunarLander"); This solves the syntax error for frame 14 Extract Method III--lander It seemed to me that each LunarLanderGameshould have its ownLunarLander Besides, I have no easy way to reset LunarLander for a new game I therefore decided to make LunarLander an instance variable Hence, this code: publicclassLunarLanderGame{ publicstaticvoidmain(String[]args){ LunarLanderlander; ... Becomes this code: publicclassLunarLanderGame{ LunarLanderlander; publicstaticvoidmain(String[]args){ ... This does not fix the syntax errorI cant access LunarLander (an instance variable) from within main (a static method) 15 Extract Method III--run We have a syntax error because: Every LunarLanderGame has its own LunarLander We have no LunarLanderGame objects Solution: Make a LunarLanderGame object in the main method, and let it do the work publicstaticvoidmain(String[]args){ LunarLanderGamegame=newLunarLanderGame(); game.run(); } voidrun(){...uselanderhere...} 16 Minor improvements I It seems unnatural to set the variable again just so we can go through the loop the first time: Stringagain="yes"; while("yes".equalsIgnoreCase(again)){ .... again=frame.getString("Wouldyouliketoplayagain?"); } Stringagain; do{ ... again=frame.getString("Wouldyouliketoplayagain?"); }while("yes".equals(again)); Note: It doesnt work to define again within the loop 17 With thedo...whileloop, we can revise this to: Minor improvements II As written, any response other than yes will be taken to mean no This is a real nuisance, especially if you make a typing error do{ ...mainbodyofloop... do{ again=frame.getString("Wouldyouliketoplayagain?"); }while(!"yes".equals(again)&&!"no".equals(again)); }while("yes".equals(again)); Instead of equals, we can use equalsIgnoreCase This allows responses such as YES as well as yes 18 How is this improved? Weve moved our status display code into a method, so any corrections or improvements in it need only be done in one place This also made the main loop smaller, so its easier to read and understand Weve used the right kind of loop to avoid a rather silly-looking initialization Weve made the yes/no question much more robust Come to think of it, this would be a good candidate for a methodgetYesOrNo("Wouldyouliketoplayagain?") The code ends up being eight lines longer (you cant win them all!) 19 Summary: Refactoring Refactoring is the process of rearranging and modifying code to improve it (without changing what it does) You improve code by making it: Easier to read and understand Easier to debug Easier to modify Real programs are constantly being read and modified Hence, refactoring is important and useful Conventional wisdom says: If it aint broke, dont fix it! This is because its easy to introduce errors Refactoring is best done if you have a suite of tests you can run to make sure you didnt break anything JUnit is one of the best ways to develop a suite of tests 20 The End 21
Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

UPenn - CIT - 594
StacksWhat is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the top of the stack Anything removed from the stack is taken from the top of the stack Things are removed in the reverse order
UPenn - CIT - 594
RecursionApr 10, 2009Definitions IA recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: An atom is a name or a number A list consists of: An open parenthesis, "(" Zero or m
UPenn - CIT - 597
JSPJava Server PagesReference: http:/www.apl.jhu.edu/~hall/java/Servlet Tutorial/ServletTutorialJSP.htmlApr 10, 2009A Hello World servlet(from the Tomcat installation documentation)publicclassHelloServletextendsHttpServlet{ publicvoiddoGet(H
UPenn - CIT - 597
Regular Expressions in JavaApr 10, 2009Regular Expressions A regular expression is a kind of pattern that can be applied to text (Strings, in Java) A regular expression either matches the text (or part of the text), or it fails to match I
UPenn - CIT - 597
AjaxApr 10, 2009The hypeAjax (sometimes capitalized as AJAX) stands for Asynchronous JavaScript And XML Ajax is a technique for creating better, faster, more responsive web applications Web applications with Ajax are supposed to replac
UPenn - CIT - 591
Enums(and a review of switch statements)Apr 10, 2009Enumerated valuesSometimes you want a variable that can take on only a certain listed (enumerated) set of values Examples: dayOfWeek: SUNDAY, MONDAY, TUESDAY, month: JAN, FEB, MAR,
UPenn - CIT - 591
Additional Java SyntaxApr 10, 2009Odd cornersWe have already covered all of the commonly used Java syntax Some Java features are seldom used, because: They are needed in only a few specialized situations, or Its just as easy to do withou
UPenn - CIT - 591
Which is better?Apr 10, 2009Which is better?Assume s1 and s2 are Strings: A. if(s1=s2){.} B. if(s1.equals(s2){.}?2Answer: Bs1=s2tests whether s1 and s2 reference the same string;s1.equals(s2) tests whether they reference equal str
UPenn - CIT - 591
Characters and StringsApr 10, 2009CharactersIn Java, a char is a primitive type that can hold one single character A character can be: A letter or digit A punctuation mark A space, tab, newline, or other whitespace A control character
UPenn - CIT - 594
GenericsApr 10, 2009Arrays and collectionsIn Java, array elements must all be of the same type: int[]counts=newint[10]; String[]names={"Tom","Dick","Harry"};Hence, arrays are type safe: The compiler will not let you put the wrong kind
UPenn - CIT - 594
Linked ListsAnatomy of a linked list A linked list consists of: A sequence of nodesmyList a b c dEach node contains a value and a link (pointer or reference) to some other node The last node contains a null link The list may have a headerMor
UPenn - LING - 001
Ling 001: Syntax IIMovement & Constraints 2-11-2009Phrases In the last lecture, we talked about simple phrases; e.g. Noun Phrases like The dog The big dog The big dog that John was talking to In this lecture, we will look at how phrases and
UPenn - LING - 102
GenieandLanguageAcquisitionHowchildrenlearntospeakandwhat happensoncetheypassthecritical periodwithouthavingdoneso.Infants:010mos. Infantscandistinguishsoundsfrombirth,even ifthosesoundsarenotpartoftheirparents speech. Bysixmonths,babiesbegintol
UPenn - LING - 102
LanguageContactpresentedby MichaelL.Friesner August6,2007Thank you to Gillian Sankoff for sending me her PPT slides (among other things).TwoMainTypesof LanguageContactAgent:Nonnativespeakersaffectingalanguagethey cometospeak languageshift
UPenn - LING - 102
Acts of Conflicting IdentityThe Sociolinguistics of British pop-song pronunciation by Peter TrudgillThe Accent of pop singing At least since the 20s and the advent of Jazz, singers have adopted speech patterns while singing that are different fro
UPenn - LING - 001
A puzzle: why language? Quantitatively and qualitatively unique like elephants trunks No similar evolutionary trends in other species other species dont want to pick up peanuts with their noses all mammals have flexible noses, some use them as
UPenn - LING - 120
LING 120 Introduction to Speech AnalysisFall 2007Week 6Speech analysis II: Stops, nasals, liquidsOct. 8-12, 20072LING 120 Introduction to Speech Analysis, Fall 20073LING 120 Introduction to Speech Analysis, Fall 20074LING 1
UPenn - LING - 520
LING 520 Introduction to Phonetics IFall 2008Week 9Basic audition Speech perception Nov. 3, 20082LING 520 Introduction to Phonetics I, Fall 20083LING 520 Introduction to Phonetics I, Fall 20084LING 520 Introduction to Phonetics
UPenn - LING - 520
LING 520 Introduction to Phonetics IFall 2008Week 2English consonants and vowels Articulatory phonology Sep. 15, 20082 1. Consonants are longer when at the end of a phrase (bib, did, don, nod). 2. Voiceless stops (i.e., /p, t, k/) are asp
UPenn - COGSCI - 501
Loudness predicts prominence: fundamental frequency lends little.G. Kochanski and E. Grabe and J. Coleman and B. Rosner( 2006/08/27 09:49:02 UTC )Running title: Fundamental Frequency Lends Little Prominence The University of Oxford Phonetics Lab
UPenn - COGSCI - 501
Psychological Review Vol. 65, No. 6, 19S8THE PERCEPTRON: A PROBABILISTIC MODEL FOR INFORMATION STORAGE AND ORGANIZATION IN THE BRAIN 1F. ROSENBLATT Cornell Aeronautical LaboratoryIf we are eventually to understand the capability of higher organi
UPenn - LING - 120
LING 120 Introduction to Speech AnalysisFall 2007Week 5Speech analysis I: Vowels and FricativesOct. 1-5, 20072[From: UCL phonetics website]LING 120 Introduction to Speech Analysis, Fall 20073LING 120 Introduction to Speech Ana
UPenn - LING - 520
LING 520 Introduction to Phonetics IFall 2008Week 3Sounds in other languagesSep. 22, 2008Languages in the world There are about 7,000 languages in the world today. Over half of them (52 percent) are spoken by fewer than 10,000 people; over
UPenn - COGSCI - 501
268IEEE TRANSACTIONS ON PATTERN ANALYSIS AND MACHINE INTELLIGENCE,VOL. 24, NO. 2,FEBRUARY 2002Short Papers_Two Variations on Fishers Linear Discriminant for Pattern RecognitionTristrom CookeAbstractDiscriminants are often used in patter
UPenn - LING - 106
Right Linear GrammarsLing 106 October 8, 20031.Regular languages as languages generated by FSAWhen we did distributional analysis, we saw that linguistic units in natural language (roughly words) can be classified into grammatical categories o
UPenn - LING - 520
LING 520 Introduction to Phonetics IFall 2008Week 5Acoustic theory of speech production Acoustics of vowels Oct. 6, 20082 LING 120 Introduction to Phonetics I, Fall 20083LING 120 Introduction to Phonetics I, Fall 20084n=2L
UPenn - LING - 120
LING 120 Introduction to Speech AnalysisFall 2007Week 2Anatomy of speech production Phonetic transcription RecordingSep. 10-14, 20072Nasal Cavity Oral Cavity Pharynx Larynx: vocal folds in it Trachea: the windpipe Lung: supply airstreamSa
UPenn - LING - 120
LING 120 Introduction to Speech AnalysisFall 2007Week 4Acoustics of speech production SamplingSep. 24-28, 20072 LING 120 Introduction to Speech Analysis, Fall 20073n=2L nfn =vn=nv 2Ln = 1, 2, 3.L = /2 = 2L f = v/
UPenn - LING - 120
LING 120 Introduction to Speech AnalysisFall 2007Week 3Physics of soundSep. 17-21, 20072Motion: Distance (unit: meters, 1 m 39 inches); displacement (vector); Speed = distance / time (units: meters/sec, m/s); Velocity specifies the di
UPenn - LING - 120
LING 120 Introduction to Speech AnalysisFall 2007Week 8Speech analysis IV: Variation and statistical techniques (I)Oct. 22-24, 2007Variation in speech2 Linguistic factors: phonetic context, intonation, syntax/semantics, etc. Paralin
UPenn - LING - 120
LING 120 Introduction to Speech AnalysisFall 2007Week 9Speech analysis IV: Variation and statistical techniques (II)Oct. 29 - Nov. 2, 2007Hypothesis testing Steps for Hypothesis Testing: 1. Formulate your hypotheses: - Need a Null Hypothesis
UPenn - LING - 102
LING-102, Summer 2007Instructor: Marjorie PakJuly 25, 2007Homework 4. Due Monday, July 30, at 10am. Part of the homework will be handwritten and turned in to me in class; the other part will be emailed to me before class. See below for exact in
UPenn - LING - 120
LING 120 Introduction to Speech AnalysisFall 2007Week 1Overview of the course The speech chain Linguistic organizationSep. 5-7, 2007Syllabus2http:/www.ling.upenn.edu/courses/ling120/LING 120 Introduction to Speech Analysis, Fall 2007
UPenn - LING - 102
LING-102, Summer 2007Instructor: Marjorie PakHomework 2. Due Wednesday, July 18, at the beginning of class. 1. The following spectrogram shows me saying two separate made-up words with a pause in between. Each word is composed of three vowels. On
UPenn - LING - 525
Signal Processing ToolboxFor Use with MATLABComputation Visualization ProgrammingUsers GuideVersion 4.2How to Contact The MathWorks:PHONEFAX MAIL508-647-7000 508-647-7001Phone Fax MailuINTERNETThe MathWorks, Inc. 24 Prime Park
UPenn - LING - 120
LING 120 Introduction to Speech AnalysisFall 2007Week 7Speech analysis III: Speech prosodyOct. 17-19, 20072LING 120 Introduction to Speech Analysis, Fall 20073LING 120 Introduction to Speech Analysis, Fall 20074Tone1: High level
UPenn - LING - 102
LING-102, Summer 2007 Homework 1. Due Wednesday, July 11 at the beginning of class (hard copy) Part 1. Pick any sentence from todays class handout that contains at least 5 words, and transcribe it on a separate piece of paper using the IPA. Bring you
UPenn - LING - 001
SyntaxLING 001 - October 11, 2006 Joshua TaubererSyntaxHow can the words of a language be put together?SyntaxWhat makes a valid combination or order of words? What are the relations between the words in a sentence? What is the mecha
UPenn - LING - 001
Sound StructurePart II: Phonology 1-28-2009Review of Phonetics Speech sounds are decomposable into articulatory primitives (also known as features) Consonants and Vowels Feature differences (e.g., voiced vs. voiceless, nasal vs. not nasal, labi
UPenn - LING - 001
undergraduate faculty campus student college academic curriculum freshman classroom professor moral considerateness bison whale governance utilitarianism ethic entity preference utilitarian diabetes elderly appendix geriatric directory hospice arthri
UPenn - LING - 001
Semanticsand some syntax, math, and computational linguistics tooLING 001 - October 16, 2006Joshua TaubererSemantics Why does a sentence mean what it means? What are the meanings of words and how do they come together to make larger meanings
UPenn - LING - 001
Linguistics 001: StructuresSyntax I 2-9-2009Plagiarism at Harvard Last year, a Harvard student accused of plagiarism of a teen novel Sabrina was the brainy Angel. Yet another example of how every girl had to be one or the other: Pretty or smart
UPenn - LING - 001
Who has a more sophisticated communication system, molluscs or monkeys? frequency and length of communicative interactions? role of communication in social life? number of distinct communicative displays? information content (entropy) of communi
UPenn - LING - 102
featuresofAAVEasfeaturesofPPE:a studyofadolescentsinphiladelphiapaperby: tonyawolford keelanevanini presentationby: anthonysobackground puertoricansfoundtoadoptaspectsof AAE effectsofdirectcontactwithAAE grammaticaluninflectedbe phonologica
UPenn - LING - 521
LING 521 Phonetics PracticumLiberman & Yuan, Spring 2006Lecture8IntroductorystatisticsIII: Correlationandregression MoreonANOVA Mar.1,2006Correlation Istherearelationshipbetweentwovariables(e.g.,ageand speechrate)?Whatisthestrengthofthisrelati
UPenn - LING - 521
LING 521 Phonetics PracticumLiberman & Yuan, Spring 2006Lecture7IntroductorystatisticsII: ttests OnewayANOVA Feb.22,2006Review:distributionofsamplemean Themeanofthesamplemean(X)isthepopulationmean(): mean(X)=Overrepeatedsamples,thesamplemeanw
UPenn - LING - 521
LING 521 Phonetics PracticumLiberman & Yuan, Spring 2006Lecture5Probability Machinelearning (ataglance) Feb.8,2006Probability Itisatruthvaluethatallowsyoutobeuncertain,ifyouwish. Itdescribeshowmuchyouknowaboutasituation. Itcountshowbigaspec
UPenn - LING - 521
LING 521 Phonetics PracticumLiberman & Yuan, Spring 2006Lecture6IntroductorystatisticsI: ExploratoryDataAnalysis Inferenceofpopulationmeans Feb.17,2006Fundamentalconcepts Statistics:thescienceofcollecting,analyzing,andinterpreting data. Popula
UPenn - LING - 001
undergraduate faculty campus student college academic curriculum freshman classroom professor moral considerateness bison whale governance utilitarianism ethic entity preference utilitarian diabetes elderly appendix geriatric directory hospice arthri
UPenn - LING - 001
Linguistics 001Spring 2009Professors David Embick and Charles YangBasics An introduction to the scientific study of language No prerequisites Satisfies Gen.Req. V/Sector VIIWebpage Information about readings and other matters will appear on
UPenn - LING - 102
LING-102, Summer 2007Instructor: Marjorie PakJuly 25, 2007Homework 4. Due Monday, July 30, at 10am. Part of the homework will be handwritten and turned in to me in class; the other part will be emailed to me before class. See below for exact in
UPenn - LING - 102
This is a questionnaire for a class Im taking. Were interested in language, and in the meanings and sounds of words for people in different places. There are a few parts. First I just need some information about you: What year were you born? What cit
UPenn - LING - 106
Highlights of Pinker, Chapter 4 (How Language Works) Ling 106 the arbitrariness of the sign discrete combinatorial system (examples: grammars, DNA) A generative grammar consists of a finite collection of discrete elements and a finite number of ru
UPenn - LING - 106
TAUTOLOGY An expression of propositional logic is a tautology iff its truth table yields nothing but 1's (i.e., a tautology is true under any circumstance). E.g. "p or not p" (either it's raining or it's not) Do the truth table for (p or not p) and y
UPenn - LING - 521
# # Description of the fields in Fisher English 2003 "calldata.tbl"# # Fifteen fields, comma-delimited:# # FLD - Description1 CALLID - 5-digit number, matches file names (fe_03_CALLID.*)2 DATE_TIME - when the call was recorded: YYY
UPenn - LING - 001
He: Statement. Statement. Statement. Question?She: Agreement.He: Reassuring statement. Confident statement. Confident statement. Overconfident statement.She: Question?He: Elaborate defensive excuse.She: Half
UPenn - LING - 538
PREAMBLE Whereas recognition of the inherent dignity and of the equal and inalienable rights of all members of the human family is the foundation of freedom, justice and and peace in the world, Whereas disregard and co
UPenn - LING - 538
368 abott.e1.p1 917 alhatton1.e3.p1 740 anhatton.e3.p1 349 aplumpt.e1.p1 5480 armin.e2.p1 5344 asch.e1.p1 1042 aungier.e3.p1 13068 authnew.e2.p1 11330 authold.e2.p1 6048 bacon.e2.p1 5929 behn.e3.p1 72
UPenn - LING - 538
873 alhatton.e3 627 anhatton.e3 2002 aplumpt.e1 5358 armin.e2 5171 asch.e1 1188 aungier.e3 11795 authnew.e2 10842 authold.e2 6015 bacon.e2 510 bedyll.e1 5657 behn.e3 6985 blundev.e2 10264 boethco.e1
UPenn - LING - 538
Ceaselessly the river flows, yet the water is never the same, while in the still poolsthe billowing foam gathers and is gone, never staying for a moment.In this world, even so is man and his habitation.
UPenn - LING - 538
UNIVERSAL DECLARATION OF LINGUISTIC RIGHTSPRELIMINARIESThe institutions and non-governmental organizations,signatories to the present Universal Declaration ofLinguistic Rights, meeting in Barcelona from 6 to 9 June1996,Having regard to the 1