Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 112 Introduction to Programming Animations; Methods with return Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:

Similar presentations


Presentation on theme: "CS 112 Introduction to Programming Animations; Methods with return Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:"— Presentation transcript:

1 CS 112 Introduction to Programming Animations; Methods with return Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

2 Outline  Admin and recap  Animations  Methods with return 2

3 Admin  PS3 due tonight  PS4 to be posted later today m Walk-through?  Debugging session? 3

4 Recap: Parameterized Drawing  Write method drawCar(x0, y0, size): 100 50 15 r=10 30 20 (x0, y0) Center: (x0 + 0.5 size, y0 + 0.25 size) Size: 0.5 size,.25 size Center: (x0 + (.15 +.10) size, y0) Radius:.10 size Center: (x0 + (1.00-.15-.10) size, y0) Radius:.10 size Center: (x0 + (1.00-.30/2) size, y0+.50/2 size) Size:.15 size,.10 size

5 drawCar 5 public static void drawCar(double x0, double y0, double size) { StdDraw.setPenColor(Color.BLACK); StdDraw.filledRectangle(x0 + 1.00/2*size, y0 +.50/2*size, 1.00/2*size,.50/2*size); // draw wheels StdDraw.setPenColor(Color.RED); StdDraw.filledCircle(x0 + (.15 +.10)*size, y0,.10*size); StdDraw.filledCircle(x0 + (1.00 -.15 -.10)*size, y0,.10*size); // draw window StdDraw.setPenColor(Color.CYAN); StdDraw.filledRectangle(x0 + (1.00 -.30/2)*size, y0 +.25*size,.15*size,.10*size); } Criticism of the method?

6 Method Design Heuristics 1. The main method should read as a concise summary of the overall set of tasks performed by the program. 2. Each method should have a clear set of responsibilities. 3. No method should do too large a share of the overall task. 4. Use method with parameters to remove redundancy with generalization, but do not over generalize 5. Use named constants (final) whenever possible to make the program easier to read/maintain 6. Data should be declared/used at the lowest level possible (localized data).

7 Outline  Admin and recap  Animations 7

8 Motivation: Car Launch  Two cars launching from different heights, at diff speed, which one lands further? m Car 1:initial height: 600 m, horizontal speed: 30 m/sec, vertical speed: 20 m/sec m Car 2:initial height: 500 m, horizontal speed: 40 m/sec, vertical speed: 30 m/sec  Write a program to visualize their trajectories in 10 sec

9 Background: Physics  In physics, for each dimension (x or y), given initial velocity v 0 in m/s, acceleration a in m/s 2, and elapsed time t in s m the speed of the moving body at time t: V = v0 + a t m The displacement of the moving body at time t: Displacement = v 0 t + ½ a t 2 m The position of the moving body at time t: Pos = initial position + displacement

10 Position  p 0 + v 0 t + ½ a t 2  Horizontal (x): m v x0 * t  Vertical (y):  g ≅ 9.81 m/s 2, downward m h 0 + v y0 t - ½ g t 2

11 CarLaunchV1 // You must have StdAudio.java and race-car.wav in the // same directory and first compile StdAudio.java. StdAudio.loop("race-car.wav"); // set up the initial state of the two cars int h1 = 600, v1x = 30, v1y = 20; int h2 = 500, v2x = 40, v2y = 30; // Simulate time from 0 to 10 sec. for (double t = 0; t < 10; t += 0.1) { // Compute car 1's position double x1 = v1x * t; double y1 = h1 + v1y * t - 0.5 * 9.81 * t * t; // Compute car 2's position double x2 = v2x * t; double y2 = h2 + v2y * t - 0.5 * 9.81 * t * t; // Used the method defined in Car.java // You can also define the method in this file Car.drawCar(x1, y1, CAR1_SIZE); Car.drawCar(x2, y2, CAR2_SIZE); } // end of for

12 CarLaunchV1 // You must have StdAudio.java and race-car.wav in the // same directory and first compile StdAudio.java. StdAudio.loop("race-car.wav"); // set up the initial state of the two cars int h1 = 600, v1x = 30, v1y = 20; int h2 = 500, v2x = 40, v2y = 30; // Simulate time from 0 to 10 sec. for (double t = 0; t < 10; t += 0.1) { // Compute car 1's position double x1 = v1x * t; double y1 = h1 + v1y * t - 0.5 * 9.81 * t * t; // Compute car 2's position double x2 = v2x * t; double y2 = h2 + v2y * t - 0.5 * 9.81 * t * t; // Used the method defined in Car.java // You can also define the method in this file StdDraw.picture(x1, y1, "angry-bird-b.png”); Car.drawCar(x2, y2, CAR2_SIZE); } // end of for It does not matter what you draw. What if we do not want the trace?

13 CarLaunchV1 // Simulate time from 0 to 10 sec. for (double t = 0; t < 10; t += 0.1) { // Compute car 1's position double x1 = v1x * t; double y1 = h1 + v1y * t - 0.5 * 9.81 * t * t; // Compute car 2's position double x2 = v2x * t; double y2 = h2 + v2y * t - 0.5 * 9.81 * t * t; // Used the method defined in Car.java // You can also define the method in this file StdDraw.picture(x1, y1, "angry-bird-b.png”); Car.drawCar(x2, y2, CAR2_SIZE); StdDraw.clear(); } // end of for

14 Measure Time Elapsed 14 long T0 = System.currentTimeMillis(); … // computation long diff = System.currentTimeMillis() – T0; http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#currentTimeMillis()

15 CarLaunch using StdDraw.show(T) … int h1 = 600, v1x = 30, v1y = 20; int h2 = 500, v2x = 40, v2y = 28; for (double t = 0; t < 10; t += 0.03) { double x1 = v1x * t; double x2 = v2x * t; double y1 = h1 + v1y * t - 9.81 * t * t / 2; double y2 = h2 + v2y * t - 9.81 * t * t / 2; Car.drawCar(x1, y1, CAR1_SIZE ); Car.drawCar(x2, y2, CAR2_SIZE ); StdDraw.show(30); // hold the image for 30 ms StdDraw.clear(); // now clear up }

16 CarLaunch using StdDraw.show(T) … int h1 = 600, v1x = 30, v1y = 20; int h2 = 500, v2x = 40, v2y = 28; for (double t = 0; t < 10; t += 30/1000.0 ) { double x1 = v1x * t; double x2 = v2x * t; double y1 = h1 + v1y * t - 9.81 * t * t / 2; double y2 = h2 + v2y * t - 9.81 * t * t / 2; Car.drawCar(x1, y1, CAR1_SIZE ); Car.drawCar(x2, y2, CAR2_SIZE ); StdDraw.show(30); // hold the image for 30 ms StdDraw.clear(); // now clear up }

17 CarLaunch using StdDraw.show(T) … int h1 = 600, v1x = 30, v1y = 20; int h2 = 500, v2x = 40, v2y = 28; for (double t = 0; t < 10; t += FRAME_T/1000.0 ) { double x1 = v1x * t; double x2 = v2x * t; double y1 = h1 + v1y * t - 9.81 * t * t / 2; double y2 = h2 + v2y * t - 9.81 * t * t / 2; Car.drawCar(x1, y1, CAR1_SIZE ); Car.drawCar(x2, y2, CAR2_SIZE ); StdDraw.show(FRAME_T); // hold image for 30 ms StdDraw.clear(); // now clear up }

18 StdDraw.show(): Details  StdDraw.show(int t) m Display on screen, pause for t milliseconds, and turn on animation mode: subsequent calls to drawing methods such as line(), circle(), and square() will not be displayed on screen until the next call to show().  StdDraw.show() m Display on-screen and turn off animation mode: subsequent calls to drawing methods such as line(), circle(), and square() will be displayed on screen when called. 18

19 Screen (Video Memory) and Drawing (Double) Buffer In animation mode, drawing is in the (double) buffer http://www.brackeen.com/vga/unchain.html Next show(t) statement copies to screen

20 Exercise: Add a Countdown Scene  Count down from 10 to 0 and then start the race 20

21 Exercise: Add a Countdown Scene  Count down from 10 to 0 and then start the race 21 public static void sceneStart(int h1, int h2) { for (int t = 10; t>= 0; t--) { Car.drawCar(0, h1, CAR1_SIZE); Car.drawCar(0, h2, CAR2_SIZE); StdDraw.text( WIDTH/2, HEIGHT/2, ""+t ); StdDraw.show( 1000 ); StdDraw.clear(); }

22 CarLaunch: Remaining Problem … int h1 = 600, v1x = 30, v1y = 20; int h2 = 500, v2x = 40, v2y = 28; … for (double t = 0; t < 10; t += FRAME_TIME/1000.0) { double x1 = v1x * t; double x2 = v2x * t; double y1 = h1 + v1y * t - 9.81 * t * t / 2; double y2 = h2 + v2y * t - 9.81 * t * t / 2; Car.drawCar( x1, y1, CAR1_SIZE ); Car.drawCar( x2, y2, CAR2_SIZE ); StdDraw.show(FRAME_TIME); // hold image for 30 ms StdDraw.clear(); // now clear up } Same expression. How to abstract?

23 Outline  Admin and recap  Animations  Methods with return 23

24 Different Styles of Methods 24 “Action-oriented methods”: External effects (print, drawing, audio), e.g., drawCar(0,0,10), drawCar(10, 10, 20), … “Answer-oriented methods”: e.g., how much is sqrt(2), sqrt(10)? “Mixed methods”: do both

25 Method with Return  Math methods are good examples of “answer-oriented” methods: they do useful work by returning values 25 method

26 Example: Math Methods Method nameDescription Math.abs( value ) absolute value Math.ceil( value ) rounds up Math.floor( value ) rounds down Math.log10( value ) logarithm, base 10 Math.max( value1, value2 ) larger of two values Math.min( value1, value2 ) smaller of two values Math.pow( base, exp ) base to the exp power Math.random() random double between 0 and 1 Math.round( value ) nearest whole number Math.sqrt( value ) square root Math.sin( value ) Math.cos( value ) Math.tan( value ) sine/cosine/tangent of an angle in radians Math.toDegrees( value ) Math.toRadians( value ) convert degrees to radians and back ConstantDescription Math.E 2.7182818... Math.PI 3.1415926...

27 Math Methods  Simply calling math methods produces no visible result. m Math.pow(3, 4); // no output  To see the result, we must print or store the returned value: m System.out.println( Math.pow(3, 4) ); // 81.0 m double result = Math.pow(3, 4); m System.out.println(result); // 81.0

28 Why return and not print?  It might seem more useful for the Math methods to print their results rather than returning them. Why don't they?  Answer: Returning is more flexible than printing. m We can compute several things before printing: double pow1 = Math.pow(3, 4); double pow2 = Math.pow(10, 6); System.out.println("Powers are " + pow1 + " and " + pow2); m We can combine the results of many computations: double k = 13 * Math.pow(3, 4) + 5 - Math.sqrt(17.8);

29 Math Questions  Evaluate the following expressions: m Math.abs(-1.23) m Math.toRadians( 180 ) m Math.round(Math.PI) + Math.round(Math.E) m Math.abs(Math.min(-3, -5)) m Math.random()  Consider an int variable named age. m What expression would replace negative ages with 0? Math.max(age, 0) m What expression would cap the maximum age to 25? Math.min(age, 25) http://download.oracle.com/javase/6/docs/api/java/lang/Math.html

30 Defining a Method Returning a Value public static type name ( parameters ) { statements ;... return expression ; } methodname returntype parameter list properties

31 Exercise: Fahrenheit -> Celsius  Write method f2cDouble that converts from Fahrenheit to Celsius, both in double  Write method f2cInt that converts from Fahrenheit to Celsius, both in int

32 Return Example // Converts degrees Fahrenheit to Celsius. public static double fToC(double degreesF) { double degreesC = (degreesF - 32) * 5.0 / 9.0 ; return degreesC; }  You can shorten the example by returning an expression: public static double fToC(double degreesF) { return (degreesF - 32) * 5.0 / 9.0 ; }

33 33 More return  The return type of a method indicates the type of value that the method sends back to the calling location  a method that does not return a value has a void return type  The return statement specifies the value that will be returned m its expression must conform to the return type  if you define a non- void method, you must return a valid type expression  there can be multiple return statements to return (finish running) at multiple points

34 A Common Error  Many people incorrectly think that a return statement sends a variable's name back to the calling method. public static void main(String[] args) { fToC(60); System.out.println(“60F = " + result); } public static double fToC(double degreesF) { double result = 5.0 / 9.0 * (degreesF - 32); return result; } // ERROR: result not defined

35 Fixing the Common Error  Instead, returning sends the variable's value back. m The returned value must be stored into a variable or used in an expression to be useful to the caller. public static void main(String[] args) { double c = fToC(65); System.out.println(“65F = " + c + “C”); System.out.println(“Again, 65F = " + fToC(65) + “C”); } public static double fToC(double degreesF) { double result = 5.0 / 9.0 * (degreesF - 32); return result; }

36 Return vs Paremeter  Return is the opposite of a parameter: m Parameters send information in from the caller to the method. m Return value sends information out from a method to its caller. main Math.abs(-42) -42 Math.round(2.71) 2.71 42 3

37 Exercise: Revise CarLaunch  Revise CarLaunchV2 to use a method with return

38 Exercise Solution public static double pos(double initPos, double speed, double a, double t) { return initPos + speed * t + a * t * t / 2; }

39 (Offline) Practice: Loan Calculator  Design a loan program to compute the monthly amortization table of a fixed-rate loan 39 Loan.java http://www.bankrate.com/calculators/mortgages/amortization-calculator.aspx http://en.wikipedia.org/wiki/Mortgage_calculator

40 Rules of Fixed-Rate Loan  Assume N periods (e.g., 120 months)  For each period, borrower pays interest on the remaining owed (principal) at the fixed rate  At the end of N’s period, the remaining principal goes to 0 40

41 Fixed-Rate Loan Calculation Alg.  Alg. focuses on owed (principal) Owed at initiation: Owed after 1 month: Owed after 2 month: Owed after 3 month:

42 Mapping Loop Variable Owed after N month: apply Owed after N month: Payoff loan after N month =>


Download ppt "CS 112 Introduction to Programming Animations; Methods with return Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:"

Similar presentations


Ads by Google