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

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

CS 112 Introduction to Programming
Building Java Programs
1 MATH METHODS THAT RETURN VALUES. 2 JAVA'S MATH CLASS.
Return values.
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2,
1 Parameters. 2 Repetitive figures Consider the task of drawing the following figures: ************* ******* *********************************** **********
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
Numerical Data Recitation – 01/30/2009
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return; double ; System.out.printf reading: 3.2, 3.5, 4.4 videos: Ch.
Introduction to Computers and Programming Lecture 13: User defined methods Instructor: Evan Korth New York University.
1 Chapter 5 Methods. 2 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Lecture 7. Review Homework 1 (sample solution) Project 1 will be assigned next week –Draw a picture (whatever you want) in the world by using turtles.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return; double ; System.out.printf reading: 3.2, 3.5, 4.4 videos: Ch.
Introduction to Methods
Topic 10 return values, Math methods Based on slides bu Marty Stepp and Stuart Reges from " Thinking like a computer.
Using Object-Oriented JavaScript CST 200- JavaScript 4 –
Topic 12 more if/else, cumulative algorithms, printf Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
CS 112 Introduction to Programming Variable Scoping; Nested Loops; Parameterized Methods Yang (Richard) Yang Computer Science Department Yale University.
Copyright ©2005  Department of Computer & Information Science Using Number & Math Objects.
CSC Programming I Lecture 5 August 30, 2002.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
Java Program Components Java Keywords - Java has special keywords that have meaning in Java. - You have already seen a fair amount of keywords. Examples.
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 7: Return values, Math, and double reading: 3.2,
Building Java Programs Chapter 3 Parameters and Objects Copyright (c) Pearson All rights reserved.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
CS177 RECITATION WEEK 7 Input and Output (Text & Graphical)
CS 112 Introduction to Programming Graphics; Animation Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
1 Building Java Programs Chapter 3: Introduction to Parameters and Objects These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They.
CS 112 Introduction to Programming Variables; Type Casting; Using Variables in for Loops Yang (Richard) Yang Computer Science Department Yale University.
CS 112 Introduction to Programming Variable Scoping; Nested Loops; Parameterized Methods Yang (Richard) Yang Computer Science Department Yale University.
The Math Class Methods Utilizing the Important Math Operations of Java!
Math Class Mrs. C. Furman September 2, Math frequently used methods NameUse floor()rounds down ceil()rounds up pow(x,y)returns x to the power of.
CS305j Introduction to Computing Parameters and Methods 1 Topic 8 Parameters and Methods "We're flooding people with information. We need to feed it through.
CS 112 Introduction to Programming Loop Examples; Variable Scoping; Nested Loops; Yang (Richard) Yang Computer Science Department Yale University 208A.
CS 112 Introduction to Programming Nested Loops; Parameterized Methods Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
CS 112 Introduction to Programming Java Graphics Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2,
CS 112 Introduction to Programming Summary of Method Definition and Invocation; printf/format Formatting Yang (Richard) Yang Computer Science Department.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
Lecture 8: Return values and math
Lecture 3: Method Parameters
Lecture 6: While Loops and the Math Class
Lecture 10: return values and math
CSCI 161 – Introduction to Programming I William Killian
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Math Methods that return values
Building Java Programs
Building Java Programs
Building Java Programs
Topic 10 return values, Math methods
Building Java Programs
Lecture 7: Graphics, return values and math
Java's Math class Method name Description Math.abs(value)
Building Java Programs
Topic 10 return values, Math methods
Chapter 5 Methods.
Lecture 6: While Loops and the Math Class
Lecture 3: Method Parameters
CS 200 Primitives and Expressions
Building Java Programs
Building Java Programs
CSE 142 Lecture Notes Global Constants, Parameters, Return Values
Building Java Programs
Lecture 11: return values and math
Presentation transcript:

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) buffer Next 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 N’s 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 =>