CS 112 Introduction to Programming

Slides:



Advertisements
Similar presentations
For(int i = 1; i
Advertisements

Introduction to Computer Science Robert Sedgewick and Kevin Wayne Copyright © Recursive GCD Demo public class.
Introduction to Computer Science Robert Sedgewick and Kevin Wayne Recursive Factorial Demo pubic class Factorial {
Template Implicit function overload. Function overload Function overload double ssqq(double & a, double & b) { return(a*b);} float ssqq(float & a, float.
CS107 Introduction to Computer Science Lecture 3, 4 An Introduction to Algorithms: Loops.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
Introduction to Programming Lecture 31. Operator Overloading.
Branch Predictor Animations Bi-modal, Local, Global CS450/650 Andrew Morton.
© 2003 Mark D. HillCS & ECE, University of Wisconsin-Madison Harnessing Moore’s Law (with Selected Implications) Mark D. Hill Computer Sciences Department.
Georgia Department of Education. Information Technology Pathways.
CS 106 Introduction to Computer Science I 11 / 20 / 2006 Instructor: Michael Eckmann.
1 10/20/08CS150 Introduction to Computer Science 1 do/while and Nested Loops Section 5.5 & 5.11.
CS 595N Winter 2006 Faculty Colloquium Faculty: Heather Zheng Wed. 1-2pm CS conference room Class website
1 CSIT 462 Computer Graphics Instructor: Dr. Reneta Barneva Department of Computer Science Office: Fenton 110 Phone:
1 CS150 Introduction to Computer Science 1 Exponents & Output page & Section 3.8.
1 9/26/07CS150 Introduction to Computer Science 1 Exponents & Output page & Section 3.8.
CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods 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.
CS 106 Introduction to Computer Science I 04 / 20 / 2007 Instructor: Michael Eckmann.
computer
CS 235: User Interface Design September 22 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
Department of Computer Science 1 Last Class on Chapter 6 1. HW 1 and HW 2 2. Greatest Common Devisor 3. Sudoku App 4. Chapter 6 Summary 5. Chapter 6 Questions.
1 3/2/05CS250 Introduction to Computer Science II Composition and friend Functions.
CS 112 Introduction to Programming Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
CS 112 Introduction to Programming Graphics; Animation Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
Reusing computations Jordi Cortadella Department of Computer Science.
CS 112 Introduction to Programming Design Good Classes: Encapsulation and OOP Analysis 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.
A: A: double “4” A: “34” 4.
1 10/15/04CS150 Introduction to Computer Science 1 Reading from and Writing to Files Part 2.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
CS 112 Introduction to Programming Animations; Methods with return Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
Functions Jordi Cortadella Department of Computer Science.
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:
CS 112 Introduction to Programming Array Reference Semantics; 2D Arrays Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
親愛的吉姆舅舅: 今天吃完晚餐後,奶奶說,在家 裡情況變好以前,您要我搬到城裡跟 您住。奶奶有沒有跟您說,爸爸已經 好久沒有工作,也好久沒有人請媽媽 做衣服了? 我們聽完都哭了,連爸爸也哭了, 但是媽媽說了一個故事讓我們又笑了。 她說:您們小的時候,她曾經被您追 得爬到樹上去,真的嗎? 雖然我個子小,但是我很強壯,
CS 112 Introduction to Programming Summary of Method Definition and Invocation; printf/format Formatting Yang (Richard) Yang Computer Science Department.
CS 112 Introduction to Programming Object Relationship Analysis: Composition, Association, Inheritance Yang (Richard) Yang Computer Science Department.
CS 112 Introduction to Programming Class Inheritance Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
1.5.3 Walkthrough #4 bouncing_ball.py wrapping_ball.py
Computer Science Department Sonoma State University.
Computer Science Department Sonoma State University
Phone: + 40 (728) | +40 (733)
Review Operation Bingo
Animation of Bubble Sort
Jordi Cortadella Department of Computer Science
Cs212: DataStructures Computer Science Department Lab 3 : Recursion.
First and last name D E P T O F L First and last name A B R Y M
Introduction to Digital Libraries Assignment #2
Department of Computer Science & Engineering, HITEC University, Taxila
Date, location, department
Energy-Efficient Storage Systems
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
Date, location, department
Introduction to Digital Libraries Assignment #2
Department | Website | Phone Number
Instance Method – CSC142 Computer Science II
CS148 Introduction to Programming II
Apply And Return Assets Process
CS150 Introduction to Computer Science 1
Unit-1 Introduction to Java
NAME OF EVENT Name of Speaker Date, location, department
CS150 Introduction to Computer Science 1
CS148 Introduction to Programming II
Presentation transcript:

CS 112 Introduction to Programming Animation (sleep and double buffering); Methods with Return; Method Overload Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

Admin Questions on PS3 A second walkthrough on ps3 today 6 pm at DL 120

repeats: Without Method int N = 5; for (int line = 1; line <= N; line++) { for (int j = 1; j <= (-1 * line + N); j++) { System.out.print("."); } System.out.print(line); for (int j = 1; j <= (line - 1); j++) { System.out.println(); ....1 ...2. ..3.. .4... 5....

repeats: Using Method public static void repeats(int n, String p) { for (int i = 1; i <= n; i++) { System.out.print( p ); } public static void main(String[] args) { int N = 5; for (int line = 1; line <= N; line++) { repeats( -1 * line + N, “.” ); System.out.print(line); repeats( line – 1, “.” ); System.out.println(); } // end of outer for loop }

Recap: drawCar (Many Magic Numbers) public static void drawCar(int x0, int y0) { StdDraw.setPenColor(Color.BLACK); StdDraw.filledRectangle(x0 + 100/2, y0 + 50/2, 100/2, 50/2); // draw wheels StdDraw.setPenColor(Color.RED); StdDraw.filledCircle(x0 + 15 + 10, y0, 10); StdDraw.filledCircle(x0 + 100 - 15 - 10, y0, 10); // draw window StdDraw.setPenColor(Color.CYAN); StdDraw.filledRectangle(x0 + 100 - 30 / 2, y0 + 25, 15, 10); }

Recap: drawCar (Use Variable Names) public static void drawCar(int x0, int y0) { // Define the variables to avoid magic numbers // A more general version of drawCar may make // some into method parameters final int CAR_WIDTH = 100, CAR_HEIGHT = 50; final int WHEEL_MARGIN = 15, WHEEL_RADIUS = 10; final int WINDOW_WIDTH = 30, WINDOW_HEIGHT = 20; // Black body StdDraw.setPenColor(Color.BLACK); StdDraw.filledRectangle(x0 + CAR_WIDTH / 2, y0 + CAR_HEIGHT / 2, CAR_WIDTH / 2, CAR_HEIGHT / 2); // Two wheels StdDraw.setPenColor(Color.RED); StdDraw.filledCircle(x0 + WHEEL_MARGIN + WHEEL_RADIUS, y0, WHEEL_RADIUS); StdDraw.filledCircle(x0 + CAR_WIDTH - WHEEL_MARGIN - WHEEL_RADIUS, y0, WHEEL_RADIUS); // Window StdDraw.setPenColor(Color.CYAN); StdDraw.filledRectangle(x0 + CAR_WIDTH - WINDOW_WIDTH / 2, y0 + CAR_HEIGHT / 2, WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2); }

Recap: CarLaunch // 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((int) x1, (int) y1); Car.drawCar((int) x2, (int) y2); } // end of for

Recap: CarLaunch What if we do not want the trace? // 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((int) x2, (int) y2); } // end of for It does not matter what you draw.

Problem(s) of the display? Recap: CarLaunch // 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((int) x2, (int) y2); StdDraw.clear(); } // end of for

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

CarLaunch: Fixing Flickering and timing using StdDraw.show(T) Display Draw A Draw B Draw C T vertical retrace vertical retrace vertical retrace Buffer Draw A Draw B Draw C Display

CarLaunch … int h1 = 600, v1x = 30, v1y = 20; 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( (int)x1, (int)y1 ); Car.drawCar( (int)x2, (int)y2 ); StdDraw.show(30); // hold the image for 30 ms StdDraw.clear(); // now clear up }

Exercise: Add a Countdown Scene Count down from 10 to 0 and then start the race public static void sceneStart(int h1, int h2) { for (int t = 10; t>= 0; t--) { Car.drawCar(0, h1); Car.drawCar(0, h2); 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 += 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( (int)x1, (int)y1 ); Car.drawCar( (int)x2, (int)y2 ); StdDraw.show(30); // hold the image for 30 ms StdDraw.clear(); // now clear up } Same expression. How to abstract?

Different Styles of Methods “Action oriented methods”: External effects, e.g., print, drawing, audio “Question oriented methods”: e.g., what is user’s input of speed? How much is sqrt(2)? “Mixed methods”: do both

Method with Return: Examples Interactive program The Scanner class provides many methods to return input to your program Math computation The Math class defines many methods to compute values of common functions method

Example: Math Class Methods Method name Description 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 Constant Description Math.E 2.7182818... Math.PI 3.1415926...

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

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

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. 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); We can combine the results of many computations: double k = 13 * Math.pow(3, 4) + 5 - Math.sqrt(17.8);

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

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

Return Example You can shorten the example by returning an expression: // 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: return (degreesF - 32) * 5.0 / 9.0 ;

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 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. 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;

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; }

Parameter type mismatch. Can we use the method? Method “Puzzle”: int h1 = 600, v1x = 30, v1y = 20; int h2 = 500, v2x = 40, v2y = 28; for (double t = 0; t < 10; t += 0.1) { … double y1 = pos(h1, v1y, -9.81, t); Parameter type mismatch. Can we use the method? public static double pos(double initPos, double speed, double a, double t) { return initPos + speed * t + a * t * t / 2; }

Two definitions of same method name? Method “Puzzle” II: System.out.print( Math.round(10.3) ); Two definitions of same method name? // Math.round() has two definitions // definition 1 static long round(double a) // definition 2 static int round(float a)

Method Definition/Invocation Rules Definition rule: You can define multiple methods with the same name in a class. This is called method overloading To distinguish different overloaded methods, these methods must have different signatures The signature is the sequential list of the type of each parameter Invocation rule: Java compiler picks the best matched method allowed by implicit conversion.

Overloaded Methods double tryMe (int x, double y) { return x * y; } Version 2: signature: int_double double tryMe (int x) { return x + .375; } Version 1: signature: int double tryMe (double x, int y) { return x * y; } Version 3: signature: double_int result = tryMe (25, 4.32) Invocation double tryMe (double x, double y) { return x * y; } Version 4: signature: double_double

Overloading Picks the Best Match allowed by Implicit Conversion double tryMe ( int x ) { return x + 5; } Which tryMe will be called? tryMe( 1 ); tryMe( 1.0 ); tryMe( 1.0, 2); tryMe( 1, 2); tryMe( 1.0, 2.0); double tryMe ( double x ) { return x * .375; } double tryMe (double x, int y) { return x + y; }

Overload Matching only Signature int x = Math.round(10.3); int x = (int)Math.round(10.3); ERROR: Type mismatch. Best match. I know 10 will fit as an int: how do I change from long to int? // Math.round() has two definitions // definition 1 static long round(double a) // definition 2 static int round(float a)