《斯坦福大学开放课程:编程方法》讲义
斯坦福大学公开课教案模版
课程名称:编程方法授课时间:2课时授课对象:计算机科学与技术专业学生教学目标:1. 了解编程方法的基本概念和原则;2. 掌握面向对象、模块化、封装、抽象化与测试等编程思想;3. 熟悉Java语言的特点和应用;4. 培养良好的编程风格。
教学内容:1. 编程方法的基本概念和原则2. 面向对象编程思想3. 模块化、封装、抽象化与测试4. Java语言的特点和应用5. 良好的编程风格教学过程:第一课时:一、导入1. 介绍斯坦福大学编程方法公开课,激发学生学习兴趣;2. 阐述编程方法的重要性,引导学生认识到掌握编程方法对于计算机专业学生的重要性。
二、编程方法的基本概念和原则1. 讲解编程方法的基本概念,如算法、数据结构等;2. 介绍编程方法的原则,如模块化、封装、抽象化与测试等。
三、面向对象编程思想1. 解释面向对象编程的基本概念,如类、对象、继承、多态等;2. 通过实例讲解面向对象编程的优势和应用。
四、模块化、封装、抽象化与测试1. 介绍模块化的概念和作用;2. 讲解封装、抽象化与测试的原则和方法;3. 通过实例分析模块化、封装、抽象化与测试在编程中的应用。
第二课时:一、Java语言的特点和应用1. 介绍Java语言的特点,如跨平台、面向对象、简单易学等;2. 讲解Java语言的基本语法和常用库;3. 通过实例展示Java语言在实际项目中的应用。
二、良好的编程风格1. 强调良好的编程风格对于代码可读性、可维护性的重要性;2. 介绍良好的编程风格,如命名规范、代码格式、注释等;3. 通过实例分析良好编程风格的具体表现。
三、总结与作业1. 总结本节课的重点内容;2. 布置课后作业,要求学生根据所学知识,运用Java语言编写一个简单的面向对象程序。
教学评价:1. 课堂表现:观察学生在课堂上的参与度、提问和回答问题的积极性;2. 作业完成情况:检查学生课后作业的完成情况,评估学生对本节课知识的掌握程度;3. 期末考试:通过期末考试,全面评估学生对编程方法知识的掌握程度。
《斯坦福大学开放课程:编程方法》讲义#1
Mehran Sahami CS 106A Handout #1 September 24, 2007 CS 106A — General Information Based on a handout by Eric Roberts Professor: Mehran SahamiHead TA: Ben NewmanIn addition to lecture, you must also sign up for a weekly 50-minute section. In order to take CS 106A, you must sign up for a section between 5:00 P .M . Thursday, September Special note on discussion sections for SCPD studentsIf you are an SCPD student, you are automatically enrolled in the SCPD discussion section which meets on Fridays from 1:15-2:05 P .M . in Skilling Auditorium (if you would like to come to campus) and is bro adcast live on SITN channel E2 (for remote viewing). Section leaders and course helpersCS106A provides extensive assistance for students. Section Leaders and Course Helpers are available from Sunday through Thursday evenings each week in Tresidder LaIR to/ and click onthe "Helper Schedule" link for the latest schedule of LaIR Helper Hours.If you are an undergraduate, you are required to take CS 106A for 5 units of credit. If you are a graduate student, you may enroll in CS 106A for 3 units if it is necessary for you to reduce your units for administrative reasons. Taking the course for reduced units does not imply any change in the course requirements.Texts and handoutsThere are two required texts for this class, both of which are available from the Stanford Bookstore. The first is a course reader entitled Karel the Robot Learns Java—a 35-page tutorial that introduces the major concepts in programming in the context of an extremelysimple robot world. The second is the textbook The Art and Science of Java by EricRoberts. In addition to these texts, we will also distribute additional material in the form of class handouts. After class, any extra copies of the handouts will be placed in thehandout bins in the entryway to the Gates B-wing. The handouts are also available inPDF® format on the CS 106 web site. If you miss a handout in class, you can print yourown copy from the web.Having an email account is a requirement for this course. E-mail accounts are availableto all students at Stanford through LaIR. Information on obtaining an account is availableat the Tresidder computer cluster, from your Resident Computer Consultant, or via theweb att /.Programming assignmentsAs you can see from the syllabus, there will be seven assignments (Assignment 1 –Assignment 7). The assignments will become slightly more difficult and require moretime as the quarter progresses. Thus, the later assignments will be weighed slightly morethan the earlier ones. Except for Assignment #7 (which is due at the very end of thequarter), each assignment is graded during an interactive, one-on-one session with your section leader, who rates it according to the following scale:++++––––An absolutely fantastic submission of the sort that will only come along a few timesduring the quarter. To ensure that this score is given only rarely, any grade of ++ must be approved by the instructor and TA. Since your section leader would almost certainlywant to show off any assignment worthy of a ++, this review process should not be too cumbersome.A submission that exceeds our standard expectation for the assignment. The programmust reflect additional work beyond the requirements or get the job done in a particularly elegant way.A submission that satisfies all the requirements for the assignment—a job well done.A submission that meets the requirements for the assignment, possibly with a few smallproblems.A submission that has problems serious enough to fall short of the requirements for theassignment.A submission that has extremely serious problems, but nonetheless shows some effortand understanding.A submission that shows little effort and does not represent passing work.From past experience, we expect most grades to be + and . Dividing the grades intocategories means that your section leader can spend more time talking about what youneed to learn from the assignment and not have to worry about justifying each point. The overall goal is to maximize the learning experience in doing the assignments, and wehave found the "bucket" grading system to work much better for programmingassignments than assigning numeric grades from a pedagogical perspective over manyquarters of experience.For each assignment, you must make an appointment with your section leader for an interactive-grading session. Your section leader will explain in section how to schedule these sessions and go over the grading process in more detail.Late policyEach of the assignments is due at the start of class on the dates specified in the syllabus. Most assignments require both electronic and printed submissions. The printed copies may be handed in during class or turned in to the box outside Ben’s office (Gates 160); the corresponding program code must be submitted electronically as described in a separate handout. All assignments are due at 3:15P.M. sharp on the dates indicated on the assignment handout. Anything that comes in after 3:15P.M. will be considered late. Because each of you will probably come upon some time during the quarter where somuch work piles up that you need a little extra time, every student begins the quarter withtwo free "late days." "Late days" are class days, not actual days (i.e. from Monday to Wednesday is one late day). After the late days are exhausted, programs that come in late(up to a maximum of three class days) will be assessed a late penalty of one grade“bucket” per day (e.g., a + turns into a , and so forth). Assignments received later thanthree class days following the due date will not be graded. The interactive-gradingsession with your section leader must be scheduled within two weeks of the due date.Note that late days may not be used on the last assignment (#7) and no assignments willbe accepted after the last day of classes (December 7th).You should think of these free "late days" as extensions you have been granted ahead oftime, and use them when you might have otherwise tried to ask for an extension. As aresult, getting an extension beyond the two free "late days" will generally not be granted.In very special circumstances (primarily extended medical problems or other emergencies), extensions may be granted beyond the late days. All extension requestsmust be directed to the head TA, Ben Newman, no later than 24 hours before the programis due. Only Ben will be able to approve extensions. In particular, do not ask yoursection leader .ExaminationsThe midterm examination will be will be a ninety-minute test administered outside ofclass from 7:00-8:30pm on Tuesday, October 30th. If you have a conflict with thisrequest by electronic mail to me by 5:00pm on Monday, October 22nd to arrange analternate exam time. The final examination is scheduled forThursday, December 13th from 12:15-3:15pm.All examinations are open-book (class course reader and testbook only), and you may use any notes, handouts, or materials from the class, but you cannot use electronic devices of any type (i.e. portable computers, PDAs, etc).GradingFinal grades for the course will be determined using the following weights:45% 30% 15% 10% Programming assignments (weighted toward the later assignments) Final examinationMidterm examinationSection participationComputer facilitiesAs in any programming course, the assignments in CS 106A require extensive hands-on use of a computer. The preferred platform for doing the work is the Eclipse development environment which runs under both Mac OS X and Microsoft Windows (Vista and XP). Instructions on obtaining and using the Eclipse environment—which is an open-source software project and therefore free to download—will be distributed in a separate class handout.。
【YYeTs人人影视】《斯坦福大学开放课程:编程方法》讲义#5——如何下载Eclipse开发环境
Mehran Sahami斯坦福大学开放课程:编程方法CS 106A 讲义#5如何下载Eclipse 开发环境由人人影视《斯坦福开放课程:编程方法》专译组奶昔译制这门课,我们推荐使用斯坦福大学量身定制的Eclipse 软件。
Eclipse 是业内广泛使用的Java 开发环境,功能众多,同时也是开源程序——任何人都可以免费对其定制修改。
利用这个优势,我们在专版Eclipse 中加入了斯坦福的特色功能,配套CS106A 课程(编程方法)使用。
这份讲义将指导你如何下载安装Eclipse 并使用我们的特色功能。
安装Eclipse在写Java 或卡雷尔程序之前,你需要从CS106A 课程网站上下载Eclipse 软件。
不同系统平台的下载方法略有不同。
如果您使用的是苹果电脑,请按照方法一下载。
如果您使用Windows 平台,请按照方法二下载。
方法一:如何在苹果机上下载Eclipse 开发环境我们的Eclipse 只能在Mac OS X 10.4及更高平台上运行。
如果你的系统版本较低,请升级系统平台,或在机房完成作业。
1.从CS 106A 网站上获取Eclipse Eclipse。
在写Java 或卡雷尔程序之前,你需要点击如下地址下载Eclipse 环境/materials/icspmcs106a/stanford_eclipse32_mac.zip2.安装Eclipse Eclipse。
下载完成之后,你应该得到一个名为eclipse 的文件夹或名为eclipse.dmg 的文件a.如过你下载到的是eclipse.dmg 文件,这是一个虚拟磁盘文件,内有名为eclipse 的文件夹。
双击eclipse.dmg ,你会在Finder 中找到一个名为eclipse-mac-distribution 的磁盘。
内有名为eclipse 的文件夹。
如果你下载到的是名为eclipse 的文件夹,请跳过步骤b。
b.将eclipse 文件夹拖入Applications 文件夹。
《斯坦福大学开放课程:编程方法》讲义#23
Mehran Sahami CS 106AHandout #23October 17, 2007 UFO Game ExampleBased on a handout by Patrick Young./** File: UfoGame.java* ------------------* This program plays a game where the user tries to * shoot a UFO before the UFO "lands".*/import import import import acm.program.*; acm.graphics.*; java.awt.*;java.awt.event.*;public class UfoGame extends GraphicsProgram {/** Size and speed of UFO */private static final int UFO_WIDTH = 40;private static final int UFO_HEIGHT = UFO_WIDTH / 2;private static final int UFO_SPEED = 5;/** Size and speed of bullets */private static final int BULLET_SPEED = 10;private static final int BULLET_DIAM = 5;/** Animation cycle delay */private static final int DELAY = 10;public void run() {setup();while (!gameOver()) {moveUFO();moveBullet();checkForCollisions();pause(DELAY);}}/** setup UFO and add mouse listeners */private void setup() {ufo = new GRect(UFO_WIDTH, UFO_HEIGHT);ufo.setFilled(true);add(ufo, getWidth(), 0); // UFO starts at top rightufoToLeft = true;addMouseListeners();}/** determines if game is over -- true if either* the UFO is destroyed or if the UFO lands */private boolean gameOver() {return (ufo == null) ||(ufo.getY() >= getHeight() - UFO_HEIGHT);}/** when mouse is clicked create bullet, unless a bullet * already exists.*/public void mouseClicked(MouseEvent e) {if (bullet == null) {bullet = new GOval(BULLET_DIAM, BULLET_DIAM);bullet.setFilled(true);bullet.setColor(Color.RED);add(bullet, (getWidth() - BULLET_DIAM) / 2,getHeight() - BULLET_DIAM);}}/** moves UFO, if UFO has moved to edge of screen, moves * UFO down and changes UFO direction.*/private void moveUFO() {if (ufoToLeft) {ufo.move(-UFO_SPEED, 0);if (ufo.getX() <= 0) {ufoToLeft = false;ufo.move(0, UFO_HEIGHT);}} else {ufo.move(UFO_SPEED, 0);if (ufo.getX() >= getWidth() - UFO_WIDTH) {ufoToLeft = true;ufo.move(0, UFO_HEIGHT);}}}/** moves bullet */private void moveBullet() {if (bullet != null) {bullet.move(0, -BULLET_SPEED);}}/** checks for bullet interaction with the world* (either colliding with the UFO or moving offscreen*/private void checkForCollisions() {collideWithUFO();moveOffScreen();}/** checks to see if UFO and bullet collide, if so* bullet and UFO are removed and both variables are* set to null.*/private void collideWithUFO() {if (bullet != null) {GObject collObj = getElementAt(bullet.getX(), bullet.getY());if (collObj == ufo) {remove(ufo);remove(bullet);ufo = null;bullet = null;}}}/** determines if bullet has moved of screen,* if it has, removes bullet, sets variable to null*/private void moveOffScreen() {if (bullet != null) {if (bullet.getY() <= -BULLET_DIAM) {remove(bullet);bullet = null;}}}/* private instance variables */private GRect ufo;private GOval bullet;private boolean ufoToLeft; // when true, UFO is moving to left }。
《斯坦福大学开放课程:编程方法》讲义#5
Mehran Sahami CS 106A Handout #7 September 26, 2007Assignment #1: Email and Karel the RobotKarel problems due: 3:15pm on Friday, October 5thEmail due: 11:59pm on Sunday, October 7thBased on a handout by Eric RobertsPart II—The REAL Assignment: Karel problems (due 3:15pm on Friday, Oct. 5th) The real problem solving portion of this assignment consists of four Karel programs. There are starter projects for each of these problems on the CS 106 web site in the area for Assignment 1. When you want to work on one of these programs, you need to download that starter folder as described in Handout #6 (Using Karel in Eclipse). Fromth ere, you need to edit the program files so that the assignment actually does what it’s supposed to do, which will involve a cycle of coding, testing, and debugging until everything works. The final step is to submit your assignment using the Submit Project entry under the Stanford menu. Remember that you can submit your programs individually as you finish them and that you can submit more than one version. If you discover an error after you’ve submitted one of these problems, just fix your program and submit a new copy. Also, Please remember that your Karel programs must limit themselvesto the language features described in Karel the Robot Learns Java in the Karel and SuperKarel classes. You may not use other features of Java, even though theEclipse-based version of Karel accepts them.The four Karel problems to solve are described below.Your first task is to solve a simple story-problem in Karel’s world. Suppose that Karelhas settled into its house, which is the square area in the center of the following diagram:543211 2 3 4 5 6 7Karel starts off in the northwest corner of its house as shown in the diagram. The problem you need to get Karel to solve is to collect the newspaper—represented (as all objects in Karel’s world are) by a beeper—from outside the doorway and then to return to its initial position.This exercise is extremely simple and exists just to get you started. You can assume that every part of the world looks just as it does in the diagram. The house is exactly this size, the door is always in the position shown, and the beeper is just outside the door. Thus, all you have to do is write the sequence of commands necessary to have Karel1. Move to the newspaper,2. Pick it up, and3. Return to its starting point.Even though the program is only a few lines, it is still worth getting at least a little practice in decomposition. In your solution, include a private method for each of the steps shown in the outline.A Word of AdviceBefore you go on to the harder problems on this assignment, why don’tyou try submitting your project as soon as you are done with this firstproblem? Every year, a handful of students run into some kind of problemwith the electronic submission option provided in the Stanford version ofEclipse. If you wait until 4:45 P.M. on Friday before you submit any ofyour work, you may discover that there is some aspect of the submissionprocess that you didn’t quite understand only after it’s too late to get anyhelp. So right now, as soon as you’ve got this first program working, goahead and hit the submit button to make sure that you can ship things off.Once you’ve done so, you’ll know that you’ve got the submission processunder control. Remember, we only look at the last submission you makebefore the due date, so it doesn’t hurt to submit new versions of yoursolution as you finish them.Karel has been hired to repair the damage done to the Quad in the 1989 earthquake. In particular, Karel is to repair a set of arches where some of the stones (represented by beepers, of course) are missing from the columns supporting the arches, as follows:876543211 2 3 4 5 6 7 8 9 10 11 12 13Your program should work on the world shown above, but it should be general enough to handle any world that meets certain basic conditions as outlined at the end of this problem. There are several example worlds in the starter folder, and your program should work correctly with all of them.When Karel is done, the missing stones in the columns should be replaced by beepers, so that the final picture resulting from the world shown above would look like this:876543211 2 3 4 5 6 7 8 9 10 11 12 13Karel may count on the following facts about the world, list on the next page:· Karel starts at 1st Avenue and 1st Street, facing east, with an infinite number of beepers. · The columns are exactly four units apart, on 1st, 5th, 9th Avenue, and so forth. · The end of the columns is marked by a wall immediately after the final column. This wall section appears after 13th Avenue in the example, but your program should work for any number of columns. · The top of the column is marked by a wall, but Karel cannot assume that columns are always five units high, or even that all columns are the same height. · Some of the corners in the column may already contain beepers representing stones that are still in place. Your program should not put a second beeper on these corners.Problem 3In this exercise, your job is to get Karel to create a checkerboard pattern of beepers inside an empty rectangular world, as illustrated in the following before-and-after diagram:8 7 6 5 4 3 2 1BeforeAfter1 2 3 4 5 6 7 8 12 3 4 5 6 7 8 This problem has a nice decomposition structure along with some interesting algorithmic issues. As you think about how you will solve the problem, you should make sure that your solution works with checkerboards that are different in size from the standard 8x 8 checkerboard shown in the example. Odd-sized checkerboards are tricky, and you should make sure that your program generates the following pattern in a 5x 3 world:Another special case you need to consider is that of a world which is only one column wide or one row high. The starter folder contains several sample worlds that test these special cases, and you should make sure that your program works for each of them.Problem 4As an exercise in solving algorithmic problems, program Karel to place a single beeper at the center of 1st Street. For example, if Karel starts in the world543211 2 3 4 5it should end with Karel standing on a beeper in the following position:543211 2 3 4 5Note that the final configuration of the world should have only a single beeper at the midpoint of 1st Street. Along the way, Karel is allowed to place additional beepers wherever it wants to, but must pick them all up again before it finishes.In solving this problem, you may count on the following facts about the world:· Karel starts at 1st Avenue and 1st Street, facing east, with an infinite number of beepers in its bag.· The initial state of the world includes no interior walls or beepers.· The world need not be square, but you may assume that it is at least as tall as it is wide. Your program, moreover, can assume the following simplifications:· If the width of the world is odd, Karel must put the beeper in the center square. If the width is even, Karel may drop the beeper on either of the two center squares.· It does not matter which direction Karel is facing at the end of the run.There are many different algorithms you can use to solve this problem. The interesting part of this assignment is to come up with a strategy that works.感谢您试用AnyBizSoft PDF to Word。
斯坦福大学公开课:编程方法学ASSIGNMENT1
斯坦福大学公开课:编程方法学ASSIGNMENT1这个是根据Assignment #1: Email and Karel the RobotKarel problems due: 1:15pm on Friday, April 12th ,2013自己写的代码,没有做过优化,这次的作业中Problem3的代码有问题,只能实现在大多数的世界中使用,在1 X N这种会失效还没有修改,刚接触这门课程,还是挺有趣的,卡雷尔机器人程序。
我先声明了一个通用的类, 然后再做的作业.import stanford.karel.*;public class 通用extends SuperKarel{public void moveBackToWall(){turnAround();while(frontIsClear()){move();}}public void moveToWall(){while(frontIsClear()){move();}}public void moveBackward(){turnAround();move();turnAround();}public void turnBack(){turnLeft();turnLeft();}}problem1/** File: CollectNewspaperKarel.java* --------------------------------* At present, the CollectNewspaperKarel subclass does nothing. * Your job in the assignment is to add the necessary code to* instruct Karel to walk to the door of its house, pick up the* newspaper (represented by a beeper, of course), and then return * to its initial position in the upper left corner of the house.*/public class CollectNewspaperKarel extends 通用{public void run(){moveToWall();turnRight();move();turnLeft();move();pickBeeper();turnBack();move();turnRight();moveToWall();turnLeft();moveToWall();putBeeper();turnBack();}}problem2public class UnitedNationsKarel extends 通用{public void run(){while(frontIsClear()){if(beepersPresent()){pickBeeper();buildHouse();}if(frontIsClear()){move();}}}private void buildHouse(){getReady();build();finish();}private void getReady(){moveBackward();turnLeft();}private void finish(){turnLeft();}private void build(){buildPart();nextToWork();buildPart();getNext();buildPart();}private void buildPart(){putBeeper();move();putBeeper();move();putBeeper();}private void nextToWork(){move();turnRight();move();turnRight();}private void getNext(){turnAround();nextToWork();}}problem3/** File: CheckerboardKarel.java* ----------------------------* When you finish writing it, the CheckerboardKarel class should draw * a checkerboard using beepers, as described in Assignment 1. You * should make sure that your program works for all of the sample* worlds supplied in the starter folder.*/public class CheckerboardKarel extends 通用{public void run(){while(leftIsClear()){while(frontIsClear()){putRow();}moveToNextStreet();}while(frontIsClear()){putRow();}checkBeeper();}private void putRow(){putBeeper();if(frontIsClear()){move();}if(frontIsClear()){move();}}private void moveToNextStreet(){checkBeeper();moveBackToWall();moveForPutRow();}private void checkBeeper(){moveBackward();if(beepersPresent()){}else{move();putBeeper();}}private void moveForPutRow(){turnRight();if(beepersPresent()){move();turnRight();move();}else{move();turnRight();}}}problem4/** File: MidpointFindingKarel.java* -------------------------------* When you finish writing it, the MidpointFindingKarel class should * leave a beeper on the corner closest to the center of 1st Street * (or either of the two central corners if 1st Street has an even* number of corners). Karel can put down additional beepers as it * looks for the midpoint, but must pick them up again before it* stops. The world may be of any size, but you are allowed to* assume that it is at least as tall as it is wide.*/public class MidpointFindingKarel extends 通用{public void run(){fullOfBeepers();while(beepersPresent()){changeForTake();takeOneBeeper();}turnAround();move();}private void fullOfBeepers(){putBeeper();while(frontIsClear()){move();putBeeper();}}private void changeForTake(){moveToWall();turnAround();}private void takeOneBeeper(){for(int i=0;i<15;i++){if(beepersPresent()){}else{move();}}move();checkBeeper();}private void checkBeeper(){if(beepersPresent()){moveBackward();pickBeeper();move(); }}}。
斯坦福大学开放课程讲义18-variables
Steve Cooper Handout #18CS 106A January 24, 2011Variables, variables, everywhere…Local VariablesLocal variables are created local to the method (or the block—see ―Block Scope‖ sectionbelow) in which they are defined. They are destroyed when execution of the method hasbeen completed. Local variables can only be accessed from within the method in whichthey are declared. Because of their transient nature, local variables cannot store persistentinformation about an object between method calls.Local Variables ExampleConsider, for example, the following snippet of code. Note that the variable names inthese notes are horrible – the purpose is to illustrate aspects of variables rather thanhaving a sensible program.The variables a and b are local variables declared within different methods in the class AnExample. Because these variables are local variables, a can only be referred to within methodOne and variable b can only be accessed within methodTwo. Our attempt to initialize b using the value of a is illegal, as code in methodTwo cannot access localvariables from methodOne or any other method.Because local variable values do not persist after their containing method has completed,the variable a will be destroyed when methodOne has completed execution. The nexttime methodOne is called, a new variable a will be created.Block ScopeWhile we typically think of local variables as local to a particular method, in Java localvariables are actually local to a block of code. While a method defines a block of code(since the opening and closing braces of the method define a block), for and while loops, if-statements, and other constructs are also considered blocks of code. If we declare a local variable inside one of these constructs, the local variable will be created when it is declared in the block and destroyed when the block ends execution.Consider the following example:The variable a is local to methodThree, so accessing a within the for loop, or in the println is fine. The variables i and b are only in scope (i.e., "alive") within the confines of the for loop in which they are declared. They are no longer available by the time the last two println s try to access them. The variable c is only in scope within the confines of the if statement body in which it is declared. Note that a new copy of c will get created each time the if statement body is executed, therefore it cannot be used to store values across iterations of the for loop.Instance VariablesInstance variables (also known as "I-vars") are defined as part of a class, but not within any particular method of the class. Each object of the class will have its own independent copy of all the instance variables defined in a class. Instance variables are created when an object is created. They are destroyed when their corresponding object is destroyed. Instance variables can be accessed from any method defined as part of the class in which the instance variable is defined. Access to instance variables from other classes is controlled by the variable’s visibility specifier (e.g., public or private). Instance variables that are public are accessible from methods in other classes while those that are private (which is by far the more common case) are not.Instance Variables ExampleIn this case we have a class Thing which has an instance variable x. Each instance of the class has its own independent copy of the variable. Our main program creates three instances (objects) of the Thing class. It then sets the value of each instance’s x variable. Because there are three different Thing objects, there are three different x variables—one x variable per instance. We can change the variable values independently from one another. When we print out the results we’ll see:Class VariablesAs with instance variables, class variables are defined as part of a class. However, in contrast to instance variables, with a class variable there is only one copy of the variable which is shared by all instances of the class. Similar to an instance variable, a class variable can be accessed by any method in the class in which the variable is declared. Access to class variables from other classes is controlled by the variable’s visibility specifier (e.g., public or private). Class variables that are public are accessible from methods in other classes while those that are private are not.Syntactically, class variable declarations are distinguished from instance variable declarations by using the keyword static before the variable type in the variable declaration. Because of this, class variables are sometimes referred to as static variables. Note that the constants you have seen so far were all in fact class variables, since they were defined using the keyword static, and it would make sense that all objects of a particular class would share the same value for some constant.Class Variables ExampleIn this case we have a class Thing which has a public instance variable x and a public class variable y. All instances (objects) of that class share the variable. Our main program creates three instances of the Thing class. When it changes the value of y, it is changing the value shared by all the instances. When we print the results, we’ll see:As seen in the example above, a public class variable can be accessed via the name of the class instead of through an instance of the class like this:This has an important advantage over accessing the variable via the name of an instance of the object: it emphasizes that y is really a property of the class, shared by all the instances of a class, rather than a property of a particular instance of the class. Compare the following two code snippets:Looking at Example 1, we cannot tell whether y is an instance variable or a class variable. In order to know for sure which type of variable is in use, we need to search out the declaration for the y variable and see if it used the static keyword. In contrast, looking at Example 2, we see that y must be a class variable, because we cannot access an instance variable using a class name. Because of this reason, using the name of the class (rather than the name of an instance) is the preferred method for accessing a class variable.ConstantsAs we discussed in class, we will sometimes find it useful to define a "variable" whose value does not change during the entire program. Such a variable is called a constant. In this case, the constant does not fulfill the traditional purpose of a variable (i.e., storing a temporary program value). To declare a variable as a constant, use the keyword final when declaring the variable. As mentioned above, virtually all constants are class variables. However, it is possible to also define constant instance variables or constant local variables.。
讲义+#9——卡雷尔例程序四则
|《斯坦福大学开放课程:编程方法》专译组
4
清洁工卡雷尔(CleanupKarel)程序代码 /* * File: CleanupKarel.java * ----------------------* Karel starts at (1, 1) facing East and cleans up any * beepers scattered throughout his world. */ import stanford.karel.*; public class CleanupKarel extends SuperKarel { /* Cleans up a field of beepers, one row at a time */ public void run() { cleanRow(); while (leftIsClear()) { repositionForRowToWest(); cleanRow(); if (rightIsClear()) { repositionForRowToEast(); cleanRow(); } else { /* * In rows with an even number of streets, we want * Karel's left to be blocked after he cleans the last * row, so we turn him to the appropriate orientation. */ turnAround(); } } }
|《斯坦福大学开放课程:编程方法》专译组 5
private void repositionForRowToEast() { turnRight(); move(); turnRight(); } }
《斯坦福大学开放课程:编程方法》讲义#44
Mehran Sahami CS 106A Handout #44 November 30, 2007Packaging Your Program into a Distributable JAR FileBased on a handout by Eric Roberts and Brandon Burr Now that you’ve written all these wonderful programs, wouldn’t it be great if you couldpackage them up and send them to your mom, dad, friends, and pets so that she could see what you’ve done? Because we here in CS106A feel that no parent sho uld be spared the joy of sitting through a simplified version of a game he or she has undoubtedly played a million times before, here’s a short guide to making an executable JAR file in Eclipse!If your program uses no external JAR filesEclipse makes it easy to package your code up into a JAR file that you can double-click to run, especially for those programs that aren’t using other JAR files. In other words, ifyour program is using the ACM libraries (or some other non-standard Java libraries), you’ll have to do the slightly more complicated method that uses a manifest file. Both examples are described below.Using the ACM libraries, Step 1Our programs that have used the ACM libraries have started running via the publicvoid run() method. We changed Eclipse to allow this, to make things easier for you.But in reality, a Java program needs to start at a particular method in a class, the publicstatic void main(String[] args) method. If your program uses the ACM libraries,you’ll need to edit your code t o have a main(). You can do this easily by simply adding the following code to the class that has the public void run(), substituting the name of that class for…Yahtzee‟ below.public static void main(String[] args) {new Yahtzee().start(args);}If you remember at the beginning of the quarter, we said that you needed the special Stanford version of Eclipse to run your programs, this is because of the edit (mentioned above) that we made to Eclipse. But if you add this main() method your program should run fine in any Java compiler.Using the ACM libraries (or using any external JAR files), Step 2Now that we have a normal running Java program, let’s package it up into a JAR file. A JAR file is simple a J ava AR chive – a file that contains a set of Java class files as well as potentially other files that will be used by the program. One important issue to point out here is if we need to specify other libraries that our program will need to reference. The easiest way do this in Eclipse is by using a manifest file when creating your JAR file. The manifest file allows you to specify things like which is the main class to run when theJAR file is double-clicked, or what the external libraries are, or even security information about the JAR file. If you aren’t using other JAR files, you don’t need to use the manifest file. Eclipse provides a straightforward way of exporting your program. In either case,you can create a JAR file as follows.Go through the process of Exporting your project to a JAR file as shown below. In Eclipse, highlight (click on the name of) the project you wish to create a JAR file from:Go to the File menu and select the Export ... command. This should give you the following window:Click on Java to expand the list of options, and then click on the option JAR file . Hit the …Next >‟ button in the window.You will see the JAR Export window:Click on the name of your project (Assignment5, in this case) to make sure the (default package) is selected, and select the destination of the JAR file using the…Browse...”button. Then hit…Next‟.This screen isn’t too important for our purposes. Just hit the…Next >‟ button again.Okay, now here’s where the important stuff happens. First, near the bottom of the window, select the Main class using the…Browse...‟ button. The main class (Yahtzee, in this case) should show up in the list if you correctly added the main() method described above.If your program doesn’t reference other JAR files (i.e., it does not use the ACM libraries or any other libraries), that’s it. You’re done! You don’t need to worry about the manifest file stuff. Just hit the…Finish‟ button, and go double-click the JAR file you just created.Make sure you see the last section of this handout on data files and distribution, though.If you do need to reference other JAR files (i.e., like the ACM libraries), then you need to create a manifest file. To do this, we will go through this exporting process twice. The first time is to generate a manifest file, and the second time is to use that file when exporting our program. So, from here, make sure …Generate the manifest file ‟radio button near the top of the window is selected, and that check box for …Save the manifest in the workspace' is checked. Use the …Browse…‟ button associated with the …Manifest fi le ‟ text box to select the destination of the manifest file. Click the Assignment5 folder (or whatever your project is named), and then in the box type in the name “manifest”. This screen should look something like the image above when you’re done (i.e., the Manifest file will likely be '/Assignment5/manifest'). Now hit the 'Finish' button.You should see the manifest file show up in the package explorer:If you double click on the manifest file, you should see its contents. You need to edit the manifest file to add the line "Class-Path: " followed by the names of all the JAR files that this program uses, separated by spaces. In this case, that would include acm.jar and yahtzeelib.jar . When you’re done the manifest file will look something like this:Make sure to save the updated manifest file. Now that we have this manifest file, repeat the entire above process of exporting a JAR file (i.e., click on your project name, pick Export... from the file menu, select the JAR file option for exporting, etc.). However, this time you will do something different when you get to the last window (shown below): Array When you get here, make sure to click the radio button for“Use existing manifestfrom workspace”.You should then have a screen that looks like this:Now, hit“Finish” button. Eclipse will use the manifest file we just created previously to make our yahtzee.jar. If it asks you to overwrite the old yahtzee.jar, just say “Yes”.We’re almost there!Distributing your programNow you have your yahtzee.jar file, containing your Yahtzee code, but you can’t simply send the yahtzee.jar to your friends. This jar doesn’t contain the code in the other two JAR files (acm.jar and yahtzeelib.jar), nor does it contain any data filesyour program might use (text files with data, or even sounds or images). What you’ll want to do is create a new folder, place your yahtzee.jar file in it, along with any other JAR files your program uses (like acm.jar and any other the ones you added to the manifest file) and data files you use. Once you have all of these files in a single folder, you should be able to just double-click your yahtzee.jar file, and have it run your application. You will need to distribute this entire folder to anyone that you want to share your program with. Usually the easiest way is to just zip the folder up into a single file, and then email that – just make sure that your friends know how to unzip the file!。
[斯坦福大学公开课:编程方法学] [答案] ASSIGNMENT2
斯坦福大学公开课:编程方法学ASSIGNMENT2Assignment #2: Simple Java ProgramsDue: 1:15pm on Friday, April 19th ,2013Your Early Assignment Help (YEAH) hours: time: tbd , Tues ., Apr . 16th in location:tbd自己写的代码,没有做过优化,这次的作业中问题不是很大,做的挺顺的。
一、PythagoreanTheorem/** File: PythagoreanTheorem.java* Name:* Section Leader:* -----------------------------* This file is the starter file for the PythagoreanTheorem problem.*/import acm.program.*;public class PythagoreanTheorem extends ConsoleProgram {public void run() {println("enter vlues to compute the pythagorean theorem.");double a=readDouble("a=");double b=readDouble("b=");println ("c =" + Math.sqrt(a*a+b*b));}}二、Hailstone/** File: Hailstone.java* Name:* Section Leader:* --------------------* This file is the starter file for the Hailstone problem. */import acm.program.*;public class Hailstone extends ConsoleProgram {public void run() {int a=readInt("Enter a number:");int n=0;while(a!=1){n++;if(a%2==0){println(a+" is even,so I take half : "+even(a));a=even(a);}else{println(a+" is odd,so I make 3n + 1 : "+odd(a));a=odd(a);}}println("The process took "+ n +" to reach 1.");}private int even(int x){int y=x/2;return y;}private int odd(int x){int y=3*x+1;return y;}}三、 FindRange/** File: FindRange.java* Name:* Section Leader:* --------------------* This file is the starter file for the FindRange problem.*/import acm.program.*;public class FindRange extends ConsoleProgram {public void run() {println("The program find the largest and smallest numbers."); int i=readInt("?");int max=i;int min=i;if(i==0){println("NO NUMBER");}while(i!=0){i=readInt("?");if(i>max){max=i;}if(i<min){min=i;}}println("largest:"+max);println("smallest:"+min);}}四、Target/** File: Target.java* Name:* Section Leader:* -----------------* This file is the starter file for the Target problem.*/import acm.graphics.*;import acm.program.*;import java.awt.*;public class Target extends GraphicsProgram {public void run() {int x=getWidth()/2;int y=getHeight()/2;GOval outerCircle=new GOval(x-72,y-72,72*2,72*2);outerCircle.setFilled(true);outerCircle.setColor(Color.RED);add(outerCircle);GOval Circle=new GOval(x-46.5,y-46.5,46.5*2,46.5*2);Circle.setFilled(true);Circle.setColor(Color.WHITE);add(Circle);GOval innerCircle=new GOval(x-21,y-21,21*2,21*2);innerCircle.setFilled(true);innerCircle.setColor(Color.RED);add(innerCircle);}}五、ProgramHierarchy/** File: ProgramHierarchy.java* Name:* Section Leader:* ---------------------------* This file is the starter file for the ProgramHierarchy problem. */import acm.graphics.*;import acm.program.*;import java.awt.*;public class ProgramHierarchy extends GraphicsProgram {private static final int m=150;private static final int n=50;private static final double c=0.2;private static final double d=1.6;public void run() {double x=getWidth();double y=getHeight();double my=y/2+n*d/2;add(rect(x/2-m/2,y/2-n*(1+d/2)));add(rect(x/2-m/2,my));add(rect(x/2-m*(1.5+c),my));add(rect(x/2+m*(0.5+c),my));add(line(x/2,y/2-n*d/2,x/2,my));add(line(x/2,y/2-n*d/2,x/2-m*(1+c),my));add(line(x/2,y/2-n*d/2,x/2+m*(1+c),my));GLabel lab1=new GLabel("Program");GLabel lab2=new GLabel("GraphicsProgram");GLabel lab3=new GLabel("ConsoleProgram");GLabel lab4=new GLabel("DialogProgram");lab1.setLocation(lx(x/2-m/2,lab1.getWidth()),ly(y/2-n*(1+d/2),lab1.getAscent( )) );lab2.setLocation(lx(x/2-m*(1.5+c),lab2.getWidth()),ly(my,lab2.getAscent()) ); lab3.setLocation(lx(x/2-m/2,lab3.getWidth()),ly(my,lab3.getAscent()) );lab4.setLocation(lx(x/2+m*(0.5+c),lab4.getWidth()),ly(my,lab4.getAscent()) ); add(lab1);add(lab2);add(lab3);add(lab4);}private GRect rect(double x,double y){GRect e=new GRect(x,y,m,n);return e;}private GLine line(double x1,double y1,double x2,double y2){GLine e=new GLine(x1,y1,x2,y2);return e;}private double lx(double x,double lw){double lx= x+(m-lw)/2;return lx;}private double ly(double y,double lh){double ly= y+(n+lh)/2;return ly;}}六、Pyramid/** File: Pyramid.java* Name:* Section Leader:* ------------------* This file is the starter file for the Pyramid problem.* It includes definitions of the constants that match the* sample run in the assignment, but you should make sure* that changing these values causes the generated display* to change accordingly.*/import acm.graphics.*;import acm.program.*;import java.awt.*;public class Pyramid extends GraphicsProgram {/** Width of each brick in pixels */private static final int BRICK_WIDTH = 8;/** Width of each brick in pixels */private static final int BRICK_HEIGHT = 8;/** Number of bricks in the base of the pyramid */private static final int BRICKS_IN_BASE =50;public void run() {for(int i=1;i<=BRICKS_IN_BASE;i++){double x=getWidth()/2-(double)(BRICKS_IN_BASE-i+1)/2*BRICK_WIDTH; double y=getHeight()-i*BRICK_HEIGHT;for(int j=1;j<=(BRICKS_IN_BASE-i+1);j++){add(rect(x+(j-1)*BRICK_WIDTH,y));}}}private GRect rect(double x,double y){GRect e=new GRect(x,y,BRICK_WIDTH,BRICK_HEIGHT);return e;}}。
斯坦福大学开放课程讲义17-coding-style
Steve Cooper Handout #17CS 106A January 24, 2011Coding StyleWhen writing a paper, you can have well-crafted, correctly spelled sentences and create ―A‖ work. Or you can hack out the text in a hurry. It will not look as good, but it can convey your thoughts and get the job done; it’s worth maybe a ―B‖ or a ―C‖. Computer code is not like that. Code that is messy tends to have all sorts of bugs and other problems. Messy code attracts problems like a half-eaten lollipop attracts lint (and that's never pleasant). The problems and bugs in poorly written code tend to compound each other and pile up, so the code ends up being nearly worthless. It has bugs. Nobody knows how to fix them or add features without creating more bugs. Once code is in that state, it is hard to escape. In a sense, code tends to be more either ―A‖, or ―D‖ or ―F‖. Therefore, it is best to write code that is clean to start, and keep it clean as you add features. This is one of the lessons in CS for successfully building large projects. For that reason CS 106A emphasizes the habits of clean, well-engineered code right from the start, building the right habits for the future.One reason to write clean, well-structured code is that it works better and takes less time in the end. The other reason to write clean code is that it is just more satisfying to do a good job on something. Clear, elegant code feels right, just like any other engineering or artistic creation.The messy code trapIt is a basic fact of computer science that poorly designed, messy code is harder to build and debug than clean code. It is tempting to just type out a quick solution as it occurs to you to get started. It is better to take a little more time at the start to build the clean version, creating fewer headaches in the debugging phase. Once code gets messy, it’s hard to clean it up. It’s easier to start clean, and then keep it clean with each addition. The worst possible strategy is to build the messy version, do your debugging on that, and then clean it up before turning it in—all the work and little of the benefit! Do it the right way from the start, and you’ll be happier.DecompositionDecomposition does not mean taking a completed program and then breaking up large methods into smaller ones merely to appease your section leader. Decomposition is the most valuable tool you have for tackling complex problems. It is much easier to design, implement, and debug small functional units in isolation than to attempt to do so with a much larger chunk of code. Remember that writing a program first and decomposing after the fact is not only difficult, but prone to producing poor results. You should decompose the problem, and write the program from that already decomposed framework. In other words, you are aiming to decompose problems, not programs!The decomposition should be logical and readable. A reader shouldn't need to twist her head around to follow how the program works. Sensible breakdown into modular units and good naming conventions are essential. Methods should be short and to the point. Strive to design methods that are general enough for a variety of situations and achieve specifics through use of parameters. This will help you avoid redundant methods—sometimes the implementation of two or more methods can be sensibly unified into one general method, resulting in less code to develop, comment, maintain, and debug. Avoid repeated code. Even a handful of lines repeated is worth breaking out into a helper method called in both situations.Readable codeOne metric for good code is that it ―reads‖ nicely—that someone sweeping their eye over the code can see the algorithmic idea at hand. The original programmer had an idea inmind—a way to solve the problem. Does the code communicate that idea? Writingreadable code is important both because it will help any future reader and because it helpsyou avoid your own bugs. Bugs, after all, are simply where the code expresses an idea,but it is not the idea you had in mind. Readable code has fewer bugs.Variable namesThe first step in readable code is choosing good names for variables. Typically a variablegets a noun name that reflects what it stores—width or height or bankBalance. If youhave the number 2, but do not know anything about it, then the generic num is an okayname. If you know more specifically that it’s a weight or a number of pixels then thename should reflect that knowledge. In Java, the convention is to begin variables with the first word lowercase, and uppercase later words like this: bestScore, remainingCreamPuffs. This notation is often refered to as "Camel Case," since the capitalization of letters in the middle of the name is similar to humps on a camel. If youhave a pointer to an object but without any more specific word to use for its variablename, then you can use the name of the class in lowercase. So if code deals with a Circle or Person object, then obvious variable names are circle or person. If you know something more specific about the objects, then more specific names like leftCircle or mother are better. There are a few idiomatic one-letter names—i, j, k for int loop counters; x, y, z for coordinates. These are in such wide use that they make very readable code just by familiarity.Method namesIf variables names are the nouns, method names are the verbs. Method names shouldreflect the action they perform—removeAll(), drawLine(), getX(). The prefixes getand set have a typical role. A get method gets a piece of information from an object,either a value that the object stores or computes: getWidth(), getNumChildren().Likewise, set methods typically are used to pass a value in to an object for it to store oruse: setWidth(int width). Methods that return a boolean (i.e., predicate methods) areoften named starting with is or has.WhitespaceUse whitespace to help separate the logical parts of the code, in much the same way that paragraphs separate groups of sentenc es. Rather than write a block of 20 lines, it’s nice to put in blank lines to separate the code into its natural 6-line sections that accomplish logical sub-parts of the computation. Each little section of code might have a comment to describe what it accomplishes. Likewise, you can use whitespace to show the logical grouping of elements within a line. Do not run everything together with no spaces. Here are a few examples/* many terms with no spaces -- never do this */int i=2*i+12/i;/* spaces around every operator----okay */int i = 2 * i + 12 / i;/* could add parens for readability */int i = (2 * i) + (12 / i);/* here’s the same idea, but with boolean expressions... *//* spaces - ok */if (i * 12 < j) {/* could add parens for clarity */if ((i * 12) < j) {IndentationAll programming languages use indentation to show which parts of the code are owned or controlled by other parts. In CS 106A, whenever there is a {, the code on the next line should be indented—this applies to methods, classes, if-statements, loops, and so on. Eclipse will do this automatically. Hit the tab key to indent one level manually. You can also select a few lines and use tab to move them all right on level, and shift-tab to move them all left one level. At the end of the indented code the matching }should not be indented. In this way, the indented section is visually set-off from the outer {}that controls it, as shown:if (i > 10) {println("i too big");i = i % 10;someMethod(i);}CommentsComments add the human context to the raw lines of code. They explain the overall flow and strategy of what is going on. Comments point out assumptions or issues that affect a part of the program that are not obvious from the code itself.As you write larger and more complex pieces of code, comments help you keep track of your own assumptions and ideas as you are building and testing various parts of the code. There gets to be more than you can keep in your head at one time. The first step is good variable and method na mes. They make the code ―read‖ well on its own, so fewer comments are required.Class commentsEach class should have a comment summarizing what it does. Typically the class comment will mention what sort of data the class encapsulates and what sort of methods it implements. Professional quality documentation for a class or group of classes intended for use by others, such as the String class, will also have a few introductory paragraphs of discussion of what sort of problems the class solves and what typical client use of the class looks like. For a system of classes, there may be an architectural overview that summarizes the role of each class and how they all fit together to build the program. Variable commentsSometimes the meaning of an instance variable or local variable is completely clear just from its name. For a complex variable, there is often extra contextual information about the variable that the code must be consistent about. A comment where the instance variable is declared is the perfect place to document such side-issues for the variable: what are its units? Are there constraints on what values it is allowed to take on? For example, weight might be the perfect name for an instance variable indicating the weight of the object, but you still need to know, say for a car simulator, that it is in pounds, or that the weight is for the car but does not include the passengers or fuel. There is often ancillary information about an instance variable—its meaning, assumptions, and constraints—beyond what is captured in its name. The comment for an instance variable can capture this extra information about the variable in one place.Method commentsMethod comments should describe what the method accomplishes. Emphasize what the method does for the caller, not how it is implemented. The comment should describe what the method does to the receiver object, adding in the role of any parameters. In the standard comment style used with javadoc, the method comment begin with a verb in the third-person singular f orm (typically ending in ―s‖) describing what the method does. For a complex method, the comment can address the preconditions that should be true before the method is called, and the postconditions that will be true after it is done.An example of method commenting is shown on the next page.AttributionAll code copied from books, handouts or other sources, and any assistance received from other students, section leaders, fairy godmothers, etc. must be cited. We consider this an important tenet of academic integrity. For example,/*** isLeapYear is adapted from Eric Roberts' text,* The Art and Science of Java, p. 106.*/or/*** I received help designing the decomposition of Breakout, in* particular, the idea having a method to handle one ball in play, * from Jason Ma on Friday, Jan. 28, 2011.*/。
【YYeTs人人影视】《斯坦福大学开放课程:编程方法》讲义#6——使用Eclipse编写卡雷尔程序
Mehran Sahami斯坦福大学开放课程:编程方法CS 106A 讲义#6使用Eclipse 编写卡雷尔程序人人影视《斯坦福大学开放课程:编程方法》专译组奶昔译如果你已经按照讲义#5的步骤下载了Eclipse 开发环境,接下来你需要知道的就是如何利用Eclipse 编写卡雷尔程序。
虽然用Eclipse 建立新工程并不困难,但为了简化过程,我们提供了工程框架。
因此,你无需了解建立新工程的选项细节,只需专注于完成作业习题。
如何下载工程框架在着手完成卡雷尔作业之前,你需要先下载工程框架。
访问CS106A 的Assignment 页面(登录CS106A 课程网站,点击Assignment 链接)。
你会看到如下表格。
点击Assignment1.zip 链接,浏览器会下载本习题的工程框架。
请确保计算机上装有可以解压ZIP 文件的解压软件。
解压后,你会得到一个名为Assignment1的工程文件夹。
将工程导入工作区至此,你需要启动Eclipse 软件(具体方法讲义#5中已详述)。
在工具栏上找到这个图标:这是Import Project (导入工程)按钮,会自动将工程目录复制到工作区内以便使用。
点击这个按钮,并选择Browse(浏览),找到之前解压的Assignment1文件夹。
Eclipse 会自动载入工程框架,并在Package Explorer中显示工程名,如下:点击文件夹名前的小三角可以展开第一层目录:注:你有可能看不到JRE System Library这项(或者后面的版本不是1.4.2)。
庆幸的是,我们终于看到了卡雷尔的影子。
default package中存放着你需要编写的代码文件。
点击前面的小三角显示如下:展开的是每道习题的代码文件。
双击即可打开。
如双击CollectNewspaperKarel,你会看到右上方的编辑区显示如下:注:刚开始,文件开头的注释部分可能不会显示。
可以点击注释行旁边的"+"展开。
《斯坦福大学开放课程:编程方法》讲义#19
Mehran SahamiCS 106A Handout #19 October 15, 2007Assignment #3—Breakout!Due: 3:15pm on Wednesday, October 24thB ase d on a h and out by E ric Rob e rts Your job in this assignment is to write the classic arcade game ofBreakout, which was invented by Steve Wozniak before hefounded Apple with Steve Jobs. It is a large assignment, butentirely manageable as long as you break the problem up intopieces. The decomposition is discussed in this handout, andthere are several suggestions for staying on top of things in the―Strategy and tactics‖ section later in this handout.The Breakout gameIn Breakout, the initial configuration of the world appears asshown on the right. The colored rectangles in the top part of thescreen are bricks, and the slightly larger rectangle at the bottom isthe paddle. The paddle is in a fixed position in the verticaldimension, but moves back and forth across the screen alongwith the mouse until it reaches the edge of its space.A complete game consists of three turns. On each turn, a ball islaunched from the center of the window toward the bottom of thescreen at a random angle. That ball bounces off the paddle andthe walls of the world, in accordance with the physical principlegenerally expressed as ―the angle of incidence equals the angle ofreflection‖ (which turns out to be very easy to implement asdiscussed later in this handout). Thus, after two bounces —oneoff the paddle and one off the right wall —the ball might have thetrajectory shown in the second diagram. (Note that the dotted lineis there to show the ball’s path and won’t appear on the screen.)As you can see from the second diagram, the ball is about tocollide with one of the bricks on the bottom row. When thathappens, the ball bounces just as it does on any other collision,but the brick disappears. The third diagram shows what thegame looks like after that collision and after the player hasmoved the paddle to put it in line with the oncoming ball.The play on a turn continues in this way until one of twoconditions occurs:1. The ball hits the lower wall, which means that the playermust have missed it with the paddle. In this case, the turnends and the next ball is served if the player has any turnsleft. If not, the game ends in a loss for the player.2. The last brick is eliminated. In this case, the player wins, andthe game ends immediately.After all the bricks in a particular column have been cleared, apath will open to the top wall. When this situation occurs, the ballwill often bounce back and forth several times between the topwall and the upper line of bricks without the user ever having toworry about hitting the ball with the paddle. This condition iscalled ―breaking out‖ and gives meaning to the name of the game.The diagram on the right shows the situation shortly after the firstball has broken through the wall. That ball will go on to clearseveral more bricks before it comes back down an open channel.It is important to note that, even though breaking out is a veryexciting part of the player’s experience, you don’t have to doanything special in your program to make it happen. The ga me issimply operating by the same rules it always applies: bouncing offwalls, clearing bricks, and otherwise obeying the laws of physics. The starter fileThe starter project for this assignment has a little more in it than it has in the past, but none of the important parts of the program. The starting contents of the Breakout.java file appear in Figure 1 (on the next page). This file takes care of the following details:· It includes the imports you will need for writing the game.· It defines the named constants that control the game parameters, such as the dimensions of the various objects. Your code should use these constants internally so that changing them in your file changes the behavior of your program accordingly.Success in this assignment will depend on breaking up the problem into manageable pieces and getting each one working before you move on to the next. The next few sections describe a reasonable staged approach to the problem.Set up the bricks Before you start playing the game, you have to set up the various pieces. Thus, it probably makes sense to implement the run method as two method calls: one that sets up the game and one that plays it. An important part of the setup consists of creating the rows of bricks at the top of the game, which look like this:The number, dimensions, and spacing of the bricks are specified using named constants in thestarter file, as is the distance from the top of the window to the first line of bricks. The onlyvalue you need to compute is the x coordinate of the first column, which should be chosen so that the bricks are centered in the window, with the leftover space divided equally on the left and right sides. The color of the bricks remain constant for two rows and run i n the following rainbow-like sequence: RED , ORANGE , YELLOW , GR EEN , CYAN .Figure 1. The Brea kout.jav a starter file/** File: Bre akout.ja va* -------------------* This file will ev entuall y implem ent the game of Breakou t.*/import import import import import import acm.graphic s.*; acm.program.*; acm.util.*;java.applet.*; java.awt.*;java.awt.ev ent.*;public clas s Breako ut exte nds Grap hicsPro gram {/** Width a nd heigh t of ap plicatio n windo w in pix els */ public stat ic final int AP PLICATIO N_WIDTH = 400;public stat ic final int AP PLICATIO N_HEIGH T = 600;/** Dimensi ons of g ame boa rd (usua lly the same) */private sta tic fina l int W IDTH = A PPLICAT ION_WIDT H;private sta tic fina l int H EIGHT = APPLICA TION_HEI GHT;/** Dimensi ons of t he padd le */private sta tic fina l int P ADDLE_WI DTH = 60;private sta tic fina l int P ADDLE_HE IGHT = 10;/** Offset of the p addle u p from t he bott om */private sta tic fina l int P ADDLE_Y_OFFSET = 30;/** Number of brick s per r ow */private sta tic fina l int N BRICKS_P ER_ROW = 10;/** Number of rows of bric ks */private sta tic fina l int N BRICK_RO WS = 10;/** Separat ion betw een bri cks */private sta tic fina l int B RICK_SEP = 4;/** Width o f a bric k */private sta tic fina l int B RICK_WID TH =(WIDTH - (N BRICKS_P ER_ROW - 1) * B RICK_SE P) / NBR ICKS_PER_ROW;/** Height of a bri ck */private sta tic fina l int B RICK_HEI GHT = 8;/** Radius of the b all in pixels */private sta tic fina l int B ALL_RADI US = 10;/** Offset of the t op bric k row fr om the top */private sta tic fina l int B RICK_Y_O FFSET = 70;/** Number of turns */private sta tic fina l int N TURNS = 3;public void run() {/* You fill this in, along with an y subsi diary me thods */ }}This part of the assignment is almost exactly like the pyramidproblem from Assignment #2. The parts that are only a touchmore difficult are that you need to fill and color the bricks. Thisextra complexity is more than compensated by the fact that thereare the same number of bricks in each row, and you don’t have tochange the coordinate calculation from row to row.Here’s a suggestion: Why don’t you get this part of the programworking by Wednesday the 17th so that you can produce just thediagram at the right? The display has most of what you see onthe final screen and will give you considerable confidence thatyou can get the rest done. And you’ll be well on your way beforetime gets short.Create the paddleThe next step is to create the paddle. At one level, this is considerably easier than the bricks. There is only one paddle, which is a filled GRect . You even know its position relative to the bottom of the window.The challenge in creating the paddle is to make it track the mouse. The technique is similar to that discussed in Chapter 9 for dragging an object around in the window. Here, however, you only have to pay attention to the x coordinate of the mouse because the y position of the paddle is fixed. The only additional wrinkle is that you should not let the paddle move off the edge of the window. Thus, you’ll have to check to see whether the x coordinate of the mouse would make the paddle extend beyond the boundary and change it if necessary to ensure that the entire paddle is visible in the window.Here’s a soon -to-become-boring suggestion: Why don’t you get this part of the program working by Friday the 19th, so that you can follow the mouse with the paddle? This entire part of the program takes fewer than 10 code lines, so it shouldn’t take so long. The hard part lies in reading the Graphics chapter and understanding what you need to do.Create a ball and get it to bounce off the wallsAt one level, creating the ball is easy, given that it’s just a filled GOval . The interesting part lies in ge tting it to move and bounce appropriately. You are now past the ―setup‖ phase and into the ―play‖ phase of the game. To start, create a ball and put it in the center of the window. As you do so, keep in mind that the coordinates of the GOval do not specify the location of the center of the ball but rather its upper left corner. The mathematics is not any more difficult, but may be a bit less intuitive.The program needs to keep track of the velocity of the ball, which consists of two separate components, which you will presumably declare as instance variables like this:private dou ble vx, vy; The velocity components represent the change in position that occurs on each time step. Initially, the ball should be heading downward, and you m ight try a starting velocity of +3.0 for vy (remember that y values in Java increase as you move down the screen). The game would be boring if every ball took the same course, so you should choose the vx component randomly.In line with our discussion of generating random num bers last week, you should simply do the following:1. Declare an instance variable rgen, which will serve as a random-number generator:private RandomGenerator rgen = RandomGenerator.getInstance();Remember that instance variables are declared outside of any method but inside the class. 2. Initialize the vx variable as follows:vx = rgen.n extDoubl e(1.0, 3.0);if (rgen.ne xtBoolea n(0.5)) vx = -v x;This code sets vx to be a random doubl e in the range 1.0 to 3.0 and then makes it negative half the time. This strategy works much better for Breakout than callingnextDouble(-3.0, +3.0)which might generate a ball going more or less straight down. That would make life far too easy for the player.Once you’ve done that, your next challenge is to get the ball to bounce around the world, ignoring entirely the paddle and the bricks. To do so, you need to check to see if the coordinates of the ball have gone beyond the boundary, taking into account that the ball has a nonzero size. Thus, to see if the ball has bounced off the right wall, you need to see whether the coordinate of the right edge of the ball has become greater than the width of the window; the other three directions are treated similarly. For now, have the ball bounce off the bottom wall so that you can watch it make its path around the world. You can change that test later so that hitting the bottom wall signifies the end of a turn.Computing w hat happens after a bounce is extremely simple. If a ball bounces off the top or bottom wall, all you need to do is reverse the sign of vy. Symmetrically, bounces off the side walls simply reverse the sign of vx.Checking for collisionsNow comes the interesting part. In order to make Breakout into a real g ame, you have to be able to tell whether the ball is colliding with another object in the window. As scientists often do, it helps to begin by making a simplifying assumption and then relaxing that assumption later. Suppose the ball were a single point rather than a circle. In that case, how could you tell whether it had collided with another object?If you look in Chapter 9 (page 299) at the methods that are defined at the GraphicsPro gram level, you will discover that there is a methodpublic GObj ect getE lementA t(double x, dou ble y)that takes a position in the window and returns the graphical object at that location, if any. If there are no graphical objects that cover that position, getElement At returns the special constant null. If there is more than one, getElem entAt always chooses the one closest to the top of thestack, which is the one that appears to be in front on the display.What happens if you callgetElementA t(x, y)where x and y are the coordinates of the ball? If the point (x, y) is underneath an object, this call returns the graphical object with which the ball has collided. If there are no objects at the point (x, y), you’ll get the value null .So far, so good. But, unfortunately, the ball is not a single point. It occupies physical area andtherefore may collide with something on the screen even though its center does not. The easiest thing to do —which is in fact typical of the simplifying assumptions made in real computer games —is to check a few carefully chosen points on the outside of the ball and see whether any of those points has collided with anything. As soon as you find something at one of those points, you can declare that the ball has collided with that object.In your implementation, the easiest thing to do is to check the four corner points on the square in which the ball is inscribed. Remember that a GOval is defined in terms of its bounding rectangle, so that if the upper left corner of the ball is at the point (x, y), the other corners will be at the locations shown in this diagram:(x , y + 2r) (x + 2r, y ) (x + 2r, y + 2r)These points have the advantage of being outside the ball —which means that getElementA t can’t return the ball itself —but nonetheless close enough to make it appear that collisions have occurred. Thus, for each of these four points, you need to:1. Call getEl ementAt on that location to see whether anything is there.2. If the value you get back is not null , then you need look no farther and can take that value asthe GObject with which the collision occurred.3. If getElemen tAt returns null for a particular corner, go on and try the next corner.4. If you get through all four corners without finding a collision, then no collision exists. It would be very useful to write this section of code as a separate methodprivate GOb ject get Collidi ngObject ()that returns the object involved in the collision, if any, and null otherwise. You could then use it in a declaration likeGObject col lider = getColl idingObj ect();which assigns that value to a variable called colli der .From here, the only remaining thing you need to do is decide what to do when a collision occurs. There are only two possibilities. First, the object you get back might be the paddle, which you can test by checkingif (collide r == pad dle) . . .If it is the paddle, you need to bounce the ball so that it starts traveling up. If it isn’t the paddle, the only other thing it might be is a brick, since those are the only other objects in the world. Once again, you need to cause a bounce in the vertical direction, but you also need to take the brick away. To do so, all you need to do is remove it from the screen by calling the remove method.Finishing upIf you’ve gotten to here, you’ve done all the hard parts. There are, however, a few more details you need to take into account:· You’ve got to take care of the case when the ball hits the bottom wall. In the prototype you’ve been building, the ball just bounces off this wall like all the others, but that makes the game pretty hard to lose. You’ve got to modify your loop structure so that it tests for hitting the bottom wall as one of its terminating conditions.· You’ve got to check for the other terminating condition, which is hitting the last brick. How do you know when you’ve done so? Although there are other ways to do it, one of the easiest is to have your program keep tra ck of the number of bricks remaining. Every time you hit one, subtract one from that counter. When the count reaches zero, you must be done. In terms of the requirements of the assignment, you can simply stop at that point, but it would be nice to give the player a little feedback that at least indicates whether the game was won or lost.· You’ve got to experiment with the settings that control the speed of your program. How long should you pause in the loop that updates the ball? Do you need to change the velocity values to get better play action?· You’ve got to test your program to see that it works. Play for a while and make sure that as many parts of it as you can check are working. If you think everything is working, here is something to try: Just before the ball is going to pass the paddle level, move the paddlequickly so that the paddle collides with the ball rather than vice-versa. Does everything still work, or does your ball seem to get ―glued‖ to the paddle? If you get this error, try tounderstand why it occurs and how you might fix it.Strategy and tacticsHere are some survival hints for this assignment:· Start as soon as possible. This assignment is due in just over a week, which will be here before you know it. If you wait until the day before this assignment is due, you will have a very hard time getting it all together.· Implement the program in stages, as described in this handout. Don’t try to get everything working all at once. Implement the various pieces of the project one at a time and make sure that each one is working before you move on to the next phase.· Set up a milestone schedule. In the handout, I’ve suggested that you get the brick display up and running by this coming Wednesday and the paddle movin g by Friday. If you do, you’ll have lots of time for the more interesting parts of the assignment and for implementingextensions.· Don’t try to extend the program until you get the basic functionality working. The following section describes several ways in which you could extend the implementation. Several of those are lots of fun. Don’t start them, however, until the basic assignment is working. If you add extensions too early, you’ll find that the debugging process gets really difficult. Possible extensionsThis assignment is perfect for those of you who are looking for + or (dare I say it) ++ scores, because there are so many possible extensions. Remember that if you are going to create a version of your program with extensions, you should submit two versions of the assignment: the basic version that meets all the assignment requirements and the extended version. Here are a few ideas of for possible extensions (of course, we encourage you to use your imagination to come up with other ideas as well):· Add sounds. The version that is running as an applet on the CS 106A assignment page plays a short bounce sound every time the ball collides with a brick or the paddle. This extension turns out to be very easy. The starter project contains an audio clip file called bounce.au that contains that sound. You can load the sound by writingAudioClip bounceClip = MediaTools.loadAudioClip("bounce.au");and later play it by callingbounceClip.play();The Java libraries do make some things easy.· Add messages. The web version waits for the user to click the mouse before serving each ball and announces whether the player has won or lost at the end of the game. These are justGLabel objects that you can add and remove at the appropriate time.· Improve the user control over bounces. The program gets rather boring if the only thing the player has to do is hit the ball. It is far more interesting, if the player can control the ball by hitting it at different parts of the paddle. The way the old arcade game worked was that the ball would bounce in both the x and y directions if you hit it on the edge of the paddle from which the ball was coming. The web version implements this feature.· Add in the ―kicker.‖ The arcade version of Breakout lured you in by starting off slowly. But, as soon as you thought you were getting the hang of things, the program sped up, making life just a bit more exciting. The applet version implements this feature by doubling the horizontal velocity of the ball the seventh time it hits the paddle, figuring that’s the time the player is growing complacent.· Keep score. You could easily keep score, generating points for each brick. In the arcade game, bricks were more valuable higher up in the array, so that you got more points for red bricks than cyan bricks. You could display the score underneath the paddle, since it won’t get in the way there.· Use your imagination. What else have you always wanted a game like this to do?。
《斯坦福大学开放课程:编程方法》讲义#32
Mehran SahamiCS 106ASolutions to Midterm ExamProblem 1: Karel the Robot (15 points)/** File: TreasureHuntKarel.java* ----------------------------* This program has Karel run a treasure hunt.*/import stanford.karel.*;public class TreasureHuntKarel extends SuperKarel {public void run() { Handout #32 November 5, 2007/* Continue treasure hunt until we face wall (by treasure). We* are guaranteed not to encounter a wall until we reach treasure.*/while (frontIsClear()) {faceCorrectDirection();moveToNextPile();}}/* Turns Karel until he is facing East */private void faceEast() {while (notFacingEast()) {turnLeft();}}/* To face the correct direction based on a clue represented by a* pile of beepers, we first face East and then make one left turn* for each beeper in the pile.*/private void faceCorrectDirection() {faceEast();while (beepersPresent()) {pickBeeper();turnLeft();}}/* Move forward until you reach next clue or treasure (pile of beepers) */private void moveToNextPile() {while (noBeepersPresent()) {move();}}}Problem 2: Simple Java expressions, statements, and methods (15 points)(2a)7 / ('C' - 'A')4 >5 || 3 % 1 == 0 &&6 * 3 > 19('b' - 'a') + "a" 3false"1a" (2b) What output is printed by the following program:Problem 3: Simple Java program using the random number library (20 points)/** File: CoinToss.java* -------------------* Number of times to toss a coin until it comes up heads 3 times in a row.*/import acm.program.*;import acm.util.*;public class CoinToss extends ConsoleProgram {private static final int NUM_CONSECUTIVE = 3;public void run() {int count = 0;int totalFlips = 0;while (count < NUM_CONSECUTIVE ) {boolean isHeads = rgen.nextBoolean(); if (isHeads) {// value true means "heads"println("heads"); count++; } else { println("tails"); count = 0; } totalFlips++; // print result of coin flip// increment count of consecutive heads// print result of coin flip// reset count of consecutive heads// increment total number of flips}println("It took " + totalFlips + " flips to get "+ NUM_CONSECUTIVE+ " consecutive heads");}private RandomGenerator rgen = RandomGenerator.getInstance ();}Problem 4: Using the graphics libraries (25 points)Although there are a number of ways to solve this problem, there are two common approaches, the first of which would be considered stylistically nicer than the other. The stylistically nicer solution is to keep track of the selected object at all times. When an object is selected, the previous selected object is unselected and the new selection is recorded. This is shown below: /* File: RadioButtonsProgram.java */import import import import acm.graphics.*; acm.program.*; java.awt.*;java.awt.event.*;public class RadioButtonsProgram extends GraphicsProgram {private static final double DIAM = 100;private static final double SPACER = 120;public void run() {drawInitialCircles();addMouseListeners();}// Draw three circles centered in the graphics window.private void drawInitialCircles() {double cy = (getHeight() - DIAM) / 2;double startx = (getWidth() - ((DIAM * 3) + (SPACER * 2))) / 2;GOval oval1 = new GOval(startx, cy, DIAM, DIAM);oval1.setFilled(true);add(oval1);GOval oval2 = new GOval(startx + DIAM + SPACER, cy, DIAM, DIAM);oval2.setFilled(true);add(oval2);GOval oval3 = new GOval(startx + ((DIAM + SPACER) * 2), cy, DIAM,DIAM);oval3.setFilled(true);add(oval3);}// If use clicked on a object unselect current selection (if one exists) // and keep track of the new selection.public void mouseClicked(MouseEvent e) {GObject obj = getElementAt(e.getX(), e.getY());if (obj != null) {if (selected != null) {selected.setColor(Color.BLACK);}selected = obj;selected.setColor(Color.RED);}}private GObject selected = null; // Used to keep track of selected circle }Another possible solution keeps track of all three circles as instance variables. Whenever a circle is clicked, it unselects all the circles and then selects the newly selected circle. This code is stylistically less nice than the previous example, and is much less efficient (imagine if the user could select among one of 20 or 100 circles), but it still works for the problem we gave you./* File: RadioButtonsProgram.java */import import import import acm.graphics.*; acm.program.*; java.awt.*;java.awt.event.*;public class AnotherCircleSelect extends GraphicsProgram {private static final double DIAM = 100;private static final double SPACER = 120;public void run() {drawInitialCircles();addMouseListeners();}// Draw three circles centered in the graphics window.private void drawInitialCircles() {double cy = (getHeight() - DIAM) / 2;double startx = (getWidth() - ((DIAM * 3) + (SPACER * 2))) / 2;oval1 = new GOval(startx, cy, DIAM, DIAM);oval1.setFilled(true);add(oval1);oval2 = new GOval(startx + DIAM + SPACER, cy, DIAM, DIAM);oval2.setFilled(true);add(oval2);oval3 = new GOval(startx + ((DIAM + SPACER) * 2), cy, DIAM, DIAM);oval3.setFilled(true);add(oval3);}// If user clicks a circle, then unselect all the circles and select// the newly clicked circle.public void mouseClicked(MouseEvent e) {GObject obj = getElementAt(e.getX(), e.getY());if (obj != null) {oval1.setColor(Color.BLACK);oval2.setColor(Color.BLACK);oval3.setColor(Color.BLACK);obj.setColor(Color.RED);}}private GOval oval1; // Instance variables used to keep track of allprivate GOval oval2; // three circles that a user could select.private GOval oval3;}Problem 5: Strings and characters (15 points)// Returns true is ch is an end-of-sentence punctuation character private boolean isPunctuation(char ch) {return (ch == '.' || ch == '!' || ch == '?');}private String cleanUpPunctuation(String str) {String result = "";// Keep track of whether we are currently in a sequence of// punctuation marks.boolean droppingPunctuation = false;for (int i = 0; i < str.length(); i++) {char ch = str.charAt(i);// If we find punctuation, then keep the character is we are// // if not already in a punctuation sequence.are now in a punctuation sequence.(isPunctuation(ch)) {In any case, weif (!droppingPunctuation) {result += ch;droppingPunctuation = true;}} else {// If character is not punctuation, then we keep it and we cannot// be in a punctuation sequence.result += ch;droppingPunctuation = false;}}return result;}。
《斯坦福大学开放课程:编程方法》讲义#14
Mehran Sahami CS 106AHandout #14October 8, 2007 MethodsBased on a handout by Eric RobertsChapter 5 introduces the concept of methods in Java, which are analogous to those you created in Karel. In contrast to the topics of expressions and control statements, the material in Chapter 5 involves far fewer details. On the other hand, the ideas introduced in this chapter are far more important. If you plot overall importance on a scale of 1 to 10, the switch statement probably weighs in somewhere around 2 (and I'm being very generous here... poor old switch statement); methods are definitely a 10.The common idea that links methods in Karel and Java is that both provide a service to other, higher-level parts of the program and therefore act as tools. In both languages, therun method can call subsidiary methods to accomplish parts of the overall task. Those methods in turn call other methods that perform simpler operations, and so on. The caller views the method in terms of the effect it accomplishes. The method supplies all the details about how that operation is done. By hiding the details of complex operations, methods simplify the conceptual structure of a program considerably and allow you as a programmer to view it at varying levels of detail.The fundamental difference between methods in Karel and their counterparts in Java is that Java makes it possible for data to pass back and forth between the caller and the method. Callers supply information to the method by supplying arguments; methods give information back to their callers by returning results. The entire process of passing this data between the two levels is in many respects the most important issue for you to understand in Chapter 5. In particular, you should take note of the following:· Methods can be applied to other objects. In this case, the syntax of the call is (arguments)· Arguments in the calling method are assigned to the corresponding formal parameters in the callee according to their position in the argument list. Thus, the first argument is assigned to the first parameter name, the second to the second, and so on. The names of the variables are completely irrelevant to this process.· Arguments are copied rather than shared. If you change the value of a formal parameter, the corresponding actual argument—even if it is a variable with the same name—is unaffected.· The return statement causes a method to return immediately to its caller and also indicates the value to be returned as a result.Methods can return values of any of the types you have encountered so far. Most of you will have little trouble with methods that return numeric data because you are familiar with this concept from high-school algebra. For some reason, methods that return objects or Boolean data seem harder, although the basic idea is precisely the same. Methods that return Boolean values, which are usually called predicate methods, are extremely important to programming.。
MIT open courses
在中国,多数老师有时还是单方面的传声筒,学生是被排除在外的。
名校公开课,今天你淘了吗不用点名,不用占座,没有考试,没有学分,想上就上的国外名校课程让中国的高校学生、白领阶层趋之若鹜,大声宣称——以前爱逃课,现在爱“淘”课!你知道2006年哈佛大学最受欢迎的讲师是谁,去年最火爆的新生公共课又是哪门吗?你知道耶鲁大学那个半仙一样盘腿坐在讲台上大谈死亡哲学的大胡子老头吗?你知道即便不能坐在鼎鼎大名的常青藤院校课堂里,在家照样能够免费聆听大师的授课、理化工商文哲医史任君选择吗?2001年,美国麻省理工学院率先拉开了网络公开课程的序幕,计划将该学院的全部课程资料都在网上公布,让全世界任何一个角落里的任一网络使用者都可以免费取用。
嗅觉敏锐的人惊呼:高高在上的象牙塔正在卸下门锁、拆掉围墙,这是教学史上继远程函授之后又一令人激动的创举!果然,麻省理工不是一个人在战斗。
耶鲁、哈佛、剑桥、牛津等世界名校以及财力丰厚的基金会的陆续加入,犹如水滴汇成浪花,将“公开教育资源”(Open Educational Resources,O.E.R)运动推向了正轨,并且一发不可收。
不用点名,不用占座,没有考试,没有学分,想上就上的国外名校课程让中国的高校学生、白领阶层趋之若鹜,大声宣称——以前爱逃课,现在爱“淘”课!大家都来OER2005年以来,全球已经有150万人次在YouTube上浏览过戴蒙德教授的网络课程“综合生物”。
除了她以外,还有许多世界顶级学校的大师——比如耶鲁大学经济学教授、当代行为金融学主要创始人罗伯特·希勒、哈佛大学“积极心理学——幸福课”的讲授者泰勒·本沙-哈尔、耶鲁大学的哲学“大仙”雪莱·卡根等,都成了走出校园、走向世界的网络新一代学术明星。
麻省理工学院72岁的物理学教授瓦尔特·勒温同样因为网络开放课程成为千万学子顶礼膜拜的对象。
这位身高188厘米,满头白发的教授,为了介绍钟摆的周期与吊挂物体的质量无关,曾躺在从天花板垂下的吊索上,让自己像钟摆一样摆荡。
《斯坦福大学开放课程:编程方法》讲义#13
Mehran Sahami CS 106A Handout #12 October 5, 2007Assignment #2: Simple Java ProgramsDue: 3:15pm on Monday, October 15thBased on a handout by Eric Roberts Your job in this assignment is to write programs to solve each of these six problems.1. Write a GraphicsProgram subclass that draws a pyramid consisting of bricksarranged in horizontal rows, so that the number of bricks in each row decreases by one as you move up the pyramid, as shown in the following sample run:The pyramid should be centered at the bottom of the window and should use constants for the following parameters:BRICK_WIDTH BRICK_HEIGHT BRICKS_IN_BASE The width of each brick (30 pixels) The height of each brick (12 pixels) The number of bricks in the base (14)The numbers in parentheses show the values for this diagram, but you must be able to change those values in your program.2. Suppose that you’ve been hired to produce a program that draws an image of an archery target —or, if you prefer commercial applications, a logo for a national department store chain —that looks like this:This figure is simply three GOval objects, two red and one white, drawn in the correct order. The outer circle should have a radius of one inch (72 pixels), the white circle has a radius of 0.65 inches, and the inner red circle has a radius of 0.3 inches. The figure should be centered in the window of a GraphicsProgram subclass.3. Write a GraphicsProgram subclass that draws a partial diagram of the acm.program class hierarchy, as follows: The only classes you need to create this picture are GRect , GLabel , and GLine . The major part of the problem is specifying the coordinates so that the different elementsa b of the picture are aligned properly. The aspects of the alignment for which you are responsible are:· The width and height of the class boxes should be specified as named constants so that they are easy to change.· The labels should be centered in their boxes. You can find the width of a label by calling label.getWidth() and the height it extends above the baseline by calling label.getAscent(). If you want to center a label, you need to shift its origin by half of these distances in each direction.· The connecting lines should start and end at the center of the appropriate edge of the box.· The entire figure should be centered in the window. 4. In high-school geometry, you learned the Pythagorean theorem for the relationship of the lengths of the three sides of a right triangle:a 2 +b 2 =c 2which can alternatively be written as:c = 2 2Most of this expression contains simple operators covered in Chapter 3. The one piece that’s missing is taking square roots, which you can do by calling the standard function Math.sqrt . For example, the statement double y = Math.sqrt(x);sets y to the square root of x .Write a ConsoleProgram that accepts values for a and b as int s and then calculates the solution of c as a double . Your program should be able to duplicate the following sample run:5. Write a ConsoleProgram that reads in a list of integers, one per line, until a sentinel value of 0 (which you should be able to change easily to some other value). When the sentinel is read, your program should display the smallest and largest values in the list, as illustrated in this sample run: Your program should handle the following special cases: · If the user enters only one value before the sentinel, the program should report that value as both the largest and smallest. · If the user enters the sentinel on the very first input line, then no values have been entered, and your program should display a message to that effect.6. Douglas Hofstadter’s Pulitzer -prize-winning book Gödel, Escher, Bach contains many interesting mathematical puzzles, many of which can be expressed in the form of computer programs. In Chapter XII, Hofstadter mentions a wonderful problem that is well within the scope of the control statements from Chapter 4. The problem can be expressed as follows:Pick some positive integer and call it n .If n is even, divide it by two. If n is odd, multiply it by three and add one. Continue this process until n is equal to one.On page 401 of the Vintage edition, Hofstadter illustrates this process with the following example, starting with the number 15:1546 23 70 35 106 53 is odd, so I make 3n + 1: is even, so I take half: is odd, so I make 3n + 1: is even, so I take half: is odd, so I make 3n + 1: is even, so I take half: is odd, so I make 3n + 1: 46 23 70 35 106 53 160160 80 40 20 10 5 16 8 4 2 is even, so I take half:is even, so I take half:is even, so I take half:is even, so I take half:is even, so I take half:is odd, so I make 3n + 1:is even, so I take half:is even, so I take half:is even, so I take half:is even, so I take half:804020105168421As you can see from this example, the numbers go up and down, but eventually—at least for all numbers that have ever been tried—comes down to end in 1. In some respects, this process is reminiscent of the formation of hailstones, which get carried upward by the winds over and over again before they finally descend to the ground. Because of this analogy, this sequence of numbers is usually called the Hailstone sequence, although it goes by many other names as well.Write a ConsoleProgram that reads in a number from the user and then displays the Hailstone sequence for that number, just as in Hofstadter’s book, followed by a line showing the number of steps taken to reach 1. For example, your program should be able to produce a sample run that looks like this:The fascinating thing about this problem is that no one has yet been able to prove that it always stops. The number of steps in the process can certainly get very large. How many steps, for example, does your program take when n is 27?。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
可编辑Mehran Sahami CS 106AHandout #9September 28, 2007 Example Karel ProblemsPortions of this handout by Eric RobertsRunning a steeple chaseIn class on Wednesday, we examined a SteepleChase program that allows Karel to run a "Steeple Chase" (like a hurdles race, but with arbitrarily large hurdles) where:Karel starts at position (1, 1), facing East.The steeple chase is guaranteed to be 9 avenues long.There can be arbitrarily many hurdles that can be of arbitrary size, located between any two avenues in the world.Karel should "jump" each hurdle one at a time.For example, if you were to execute the SteepleChase program, you would seesomething like the following before-and-after diagram:Before AfterBelow is the program listing of the SteepleChase program, which provides an exampleof various control structures in Karel, program decomposition, and comments (including the specification of pre- and post-conditions).– 2 –/** File: SteepleChase.java* -----------------------* Karel runs a steeple chase the is 9 avenues long.* Hurdles are of arbitrary height and placement.*/import stanford.karel.*;public class SteepleChase extends SuperKarel {/** To run a race that is 9 avenues long, we need to move* forward or jump hurdles 8 times.*/public void run() {for (int i = 0; i < 8; i++) {if (frontIsClear()) {move();} else {jumpHurdle();}}}/** Pre-condition:Facing East at bottom of hurdle* Post-condition: Facing East at bottom in next avenue*after hurdle*/private void jumpHurdle() {ascendHurdle();move();descendHurdle();}/** Pre-condition:Facing East at bottom of hurdle* Post-condition: Facing East immediately above hurdle*/private void ascendHurdle() {turnLeft();while (rightIsBlocked()) {move();}turnRight();}– 3 –/** Pre-condition:Facing East above and immediately after hurdle* Post-condition: Facing East at bottom of hurdle*/private void descendHurdle() {turnRight();moveToWall();turnLeft();}/** Pre-condition:none* Post-condition: Facing first wall in whichever direction* Karel was facing previously*/private void moveToWall() {while (frontIsClear()) {move();}}}Creating a line of beepersConsider the problem of writing a method createBeeperLine, which creates a line ofbeepers beginning at Karel’s current corner and proceeding forward to the next wall. For example, if you were to execute createBeeperLine in an empty world, you would see something like the following before-and-after diagram:4 3 2 1Before4321After 123456123456The problem is slightly harder than it looks. Unless you think carefully about the problem, it is easy to find yourself making a common programming error that keeps the program from working as you’d like. For example, we might initially be inclined to solve the problem as follows:private void createBeeperLine() {while (frontIsClear()) {putBeeper();可编辑move();}}可编辑– 4 –The problem here (as indicated by the "bug" picture next to the code), is that Karel will not place a beeper on the last corner he encounters. When he reaches the final corner of the row he's in, his front will no longer be clear, so the while loop will immediately exit before a beeper is placed on that final corner. This is perhaps easier to see when looking at the Karel's world after he executes the code above:Note that in the picture above, there is no beeper on the corner that Karel is standing on. To solve this example of a "fence-post" problem (such problems are further discussed in the Karel course reader), we must make one more putBeeper() method call than calls to move(), as shown below:private void createBeeperLine() {while (frontIsClear()) {putBeeper();move();}putBeeper();}Cleaning up scattered beepersUnfortunately, sometimes Karel's world gets a little messy, with beepers strewn around at various corners. We want to help Karel clean up his world by writing a program that has Karel go through the world and pick up any beepers that may be scattered about. We assume that:Karel starts at corner (1, 1) facing EastEach corner of Karel's world may either be empty or contain at most one beeper, and when Karel is done there should be no more beepers on any cornerKarel can finish his task at any location and orientationIf you were to execute your program, you would see something like the following before-可编辑and-after diagram on the next page.– 5 –Before AfterBelow is the program listing of the CleanupKarel program./** File: CleanupKarel.java* -----------------------* Karel starts at (1, 1) facing East and cleans up any* beepers scattered throughout his world.*/import stanford.karel.*;public class CleanupKarel extends SuperKarel {/* Cleans up a field of beepers, one row at a time */public void run() {cleanRow();while (leftIsClear()) {repositionForRowToWest();cleanRow();if (rightIsClear()) {repositionForRowToEast();cleanRow();} else {/** In rows with an even number of streets, we want* Karel's left to be blocked after he cleans the last* row, so we turn him to the appropriate orientation.*/turnAround();}}}– 6 –/* Cleans up a row in whichever direction Karel is facing */private void cleanRow() {if (beepersPresent()) {pickBeeper();}while (frontIsClear()) {move();if (beepersPresent()) {pickBeeper();}}}/* Reposition Karel at far East wall to face West on next row */private void repositionForRowToWest() {turnLeft();move();turnLeft();}/* Reposition Karel at far West wall to face East on next row */private void repositionForRowToEast() {turnRight();move();turnRight();}}Doubling the number of beepers in a pileInterestingly enough, Karel can also do various kinds of math. For example, we can ask Karel to double the number of beepers on some corner in the world. We'd like to write a program where there is a pile of some (finite) number of beepers on the corner directly in front of Karel. We want Karel to double the number of beepers in that pile and return to his original location and orientation. You can assume that Karel begins with an infinite number of beepers in his beeper bag.For example, if you were to execute your program in the sample Before world shown below, you would expect to see the corresponding After world (note that the number of beepers on corner (2, 1) has been doubled):Before After– 7 –Below is the program listing of the DoubleBeepers program./** File: DoubleBeepers.java* ------------------------* Karel doubles the number of beepers on the corner directly* in front of him in the world. He then returns to his* original position/orientation.*/import stanford.karel.SuperKarel;public class DoubleBeepers extends SuperKarel {public void run() {move();DoubleBeepersInPile();moveBackward();}/** For every beeper on the current corner, Karel places* two beepers on the corner immediately ahead of him.*/private void DoubleBeepersInPile() {while (beepersPresent()) {pickBeeper();PutTwoBeepersNextDoor();}MovePileNextDoorBack();}/** Place two beepers on corner one avenue ahead of Karel* and move back to starting position/orientation*/private void PutTwoBeepersNextDoor() {move();putBeeper();putBeeper();moveBackward();}/** Move all the beepers on the corner in front of Karel* the the corner Karel is currently on.*/private void MovePileNextDoorBack() {move();while (beepersPresent()) {MoveOneBeeperBack();}moveBackward();}– 8 –/** Move one beeper from the current corner back one avenue* and return to the original position/orientation.*/private void MoveOneBeeperBack() {pickBeeper();moveBackward();putBeeper();move();}/** Move Karel back one avenue, but have the same* final orientation.*/private void moveBackward() {turnAround();move();turnAround();}}。