CS 112 Introduction to Programming Animations; Methods with return Yang (Richard) Yang Computer...

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

If you can't read please download the document

description

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

Transcript of CS 112 Introduction to Programming Animations; Methods with return Yang (Richard) Yang Computer...

CS 112 Introduction to Programming Animations; Methods with return Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone: Outline Admin and recap Animations Methods with return 2 Admin PS3 due tonight PS4 to be posted later today m Walk-through? Debugging session? 3 Recap: Parameterized Drawing Write method drawCar(x0, y0, size): r= (x0, y0) Center: (x size, y size) Size: 0.5 size,.25 size Center: (x0 + ( ) size, y0) Radius:.10 size Center: (x0 + ( ) size, y0) Radius:.10 size Center: (x0 + ( /2) size, y0+.50/2 size) Size:.15 size,.10 size drawCar 5 public static void drawCar(double x0, double y0, double size) { StdDraw.setPenColor(Color.BLACK); StdDraw.filledRectangle(x /2*size, y0 +.50/2*size, 1.00/2*size,.50/2*size); // draw wheels StdDraw.setPenColor(Color.RED); StdDraw.filledCircle(x0 + ( )*size, y0,.10*size); StdDraw.filledCircle(x0 + ( )*size, y0,.10*size); // draw window StdDraw.setPenColor(Color.CYAN); StdDraw.filledRectangle(x0 + ( /2)*size, y0 +.25*size,.15*size,.10*size); } Criticism of the method? 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). Outline Admin and recap Animations 7 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 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 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 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 * 9.81 * t * t; // Compute car 2's position double x2 = v2x * t; double y2 = h2 + v2y * t * 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 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 * 9.81 * t * t; // Compute car 2's position double x2 = v2x * t; double y2 = h2 + v2y * t * 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? 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 * 9.81 * t * t; // Compute car 2's position double x2 = v2x * t; double y2 = h2 + v2y * t * 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 Measure Time Elapsed 14 long T0 = System.currentTimeMillis(); // computation long diff = System.currentTimeMillis() T0; 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 * t * t / 2; double y2 = h2 + v2y * t * 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 } 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/ ) { double x1 = v1x * t; double x2 = v2x * t; double y1 = h1 + v1y * t * t * t / 2; double y2 = h2 + v2y * t * 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 } 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/ ) { double x1 = v1x * t; double x2 = v2x * t; double y1 = h1 + v1y * t * t * t / 2; double y2 = h2 + v2y * t * 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 } 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 Screen (Video Memory) and Drawing (Double) Buffer In animation mode, drawing is in the (double) bufferNext show(t) statement copies to screen Exercise: Add a Countdown Scene Count down from 10 to 0 and then start the race 20 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(); } 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 * t * t / 2; double y2 = h2 + v2y * t * 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? Outline Admin and recap Animations Methods with return 23 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 Method with Return Math methods are good examples of answer-oriented methods: they do useful work by returning values 25 method 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 Math.PI 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 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) Math.sqrt(17.8); 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) Defining a Method Returning a Value public static type name ( parameters ) { statements ;... return expression ; } methodname returntype parameter list properties 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 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 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 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 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; } 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) Exercise: Revise CarLaunch Revise CarLaunchV2 to use a method with return Exercise Solution public static double pos(double initPos, double speed, double a, double t) { return initPos + speed * t + a * t * t / 2; } (Offline) Practice: Loan Calculator Design a loan program to compute the monthly amortization table of a fixed-rate loan 39 Loan.java 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 Ns period, the remaining principal goes to 0 40 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: Mapping Loop Variable Owed after N month: apply Owed after N month: Payoff loan after N month =>