Download presentation
Presentation is loading. Please wait.
Published byRodger Logan Modified over 8 years ago
1
CS 112 Introduction to Programming Summary of Method Definition and Invocation; printf/format Formatting Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone: 432-6400 Email: yry@cs.yale.edu
2
Outline Admin and recap Summary of method definitions and invocation m Method overloading m printf and String.format 2
3
Admin PS4 posted yesterday m There was some revision (Part 2 was changed) to PS4. Please be sure to reload the page 3
4
Recap: Animation … 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 }
5
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. 5
6
Without Animation http://www.brackeen.com/vga/unchain.html
7
Animation: Use Both Screen (Video Memory) and (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
8
Example: AnimationShow.java Try running the example in Debug mode m Right click first line and toggle breakpoint m Execute in Debug mode m Execute (step over) each statement 8
9
Recap: Defining a Method Returning a Value public static type name ( parameters ) { statements ;... return expression ; } methodname returntype parameter list properties public static double fToC(double degreesF) { return (degreesF - 32) * 5.0 / 9.0 ; }
10
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
11
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; }
12
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
13
Exercise: Revise CarLaunch Revise CarLaunchV2 to use a method with return
14
Exercise Solution public static double pos(double initPos, double speed, double a, double t) { return initPos + speed * t + a * t * t / 2; }
15
Outline Admin and recap Summary of method definitions and invocation 15
16
16 Summary: Method Definition Why define methods? m Denote structure, eliminate redundancy m A method with parameters solves an entire class of similar problems m A method with return gives back an answer on a question
17
Method “Puzzle” System.out.print( Math.round(10.3) ); // Math.round() has two definitions // definition 1 static long round(double a) // definition 2 static int round(float a) Two definitions of same method name? Many methods in Math has multiple definitions: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html
18
18 Method Definition and Invocation Rules Definition rule: m You can define multiple methods with the same name in a class. This is called method overloading m 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: m Java compiler picks the method with the best match in signature, allowed by implicit conversion.
19
19 Overloaded Methods double tryMe (int x) { return x +.375; } Version 1: signature: int double tryMe (int x, double y) { return x * y; } Version 2: signature: int_double result = tryMe (25, 4.32)Invocation double tryMe (double x, int y) { return x * y; } Version 3: signature: double_int double tryMe (double x, double y) { return x * y; } Version 4: signature: double_double
20
20 Overloading Picks the Best Match allowed by Implicit Conversion double tryMe ( int x ) { return x + 5; } double tryMe ( double x ) { return x *.375; } double tryMe (double x, int y) { return x + y; } tryMe( 1 ); tryMe( 1.0 ); tryMe( 1.0, 2); tryMe( 1, 2); tryMe( 1.0, 2.0); Which tryMe will be called?
21
Overload Matching only Signature int x = Math.round(10.3); // Math.round() has two definitions // definition 1 static long round(double a) // definition 2 static int round(float a) Best match. ERROR: Type mismatch. I know 10 will fit as an int: how do I change from long to int? int x = (int)Math.round(10.3);
22
22 Method Invocation and Parameter Passing Corresponding actual argument in the invocation is assigned to the corresponding formal argument public static void printNumber(int number, int count) { for (int i = 1; i <= count; i++) { System.out.print(number); } System.out.println(); } int line = 3; printNumber(line-1,5); // equiv: number = 2; count = 5;
23
23 Formal Arguments are Local Variables In Java, a formal argument is a local variable of a method The formal argument and the actual argument are different variables, with different memory locations, even if they have the same name. When a primitive variable is passed as the actual argument to a formal argument, the value is copied m Value copying implies value semantic m Implication: modifying the parameter inside the method will not affect the variable passed in.
24
Value Semantics int a = 100; double x = 45.12; 24 100 a 45.12 x A value variable stores a value of the type of the variable.
25
25 Value Variables int a = 100; double x = 45.12; int aa; 100 a 45.12 x aa
26
26 Value-Variable Assignment int a = 100; double x = 45.12; int aa; aa = a; 100 a 45.12 x aa An assignment of one value variable to another value variable copies the value. 100
27
27 Value-Variable Assignment int a = 100; double x = 45.12; int aa; aa = a; a = 200; 100 a 45.12 x aa 100 Change the value of one value variable will not change the other. 200
28
Exercise: “Parameter Mystery” public static void strange(int x) { x = x + 1; System.out.println("1. x = " + x); } public static void main(String[] args) { int x = 23; strange(x); System.out.println("2. x = " + x);... } Output: 1. x = 24 2. x = 23
29
Explanation: main() start 29 public static void main(String[] args) { int x = 23; strange(x); System.out.println("2. x = " + x); } 23 args x
30
Explanation: Invocation 30 public static void strange(int x) { x = x + 1; System.out.println("1. x = " + x); } public static void main(String[] args) { int x = 23; strange(x); System.out.println("2. x = " + x); } 23 args x x compiler declares formal argument x and copies value from the actual argument 23
31
Explanation: Local update 31 public static void strange(int x) { x = x + 1; System.out.println("1. x = " + x); } public static void main(String[] args) { int x = 23; strange(x); System.out.println("2. x = " + x); } 23 args x 23 x 24
32
Explanation: Method return 32 public static void strange(int x) { x = x + 1; System.out.println("1. x = " + x); } public static void main(String[] args) { int x = 23; strange(x); System.out.println("2. x = " + x); } 23 args x x compiler un-declares formal argument 24
33
Explanation: Method return 33 public static void main(String[] args) { int x = 23; strange(x); System.out.println("2. x = " + x); } 23 args x
34
Exercise: "Parameter Mystery” public class ParameterMystery { public static void main(String[] args) { int x = 9; int y = 2; int z = 5; mystery(z, y, x); mystery(y, x, z); } public static void mystery(int x, int y, int z) { System.out.println(z + " and " + (y - x)); }
35
(Offline) Practice: Loan Calculator Design a loan program to compute the monthly amortization table of a fixed-rate loan 35 Loan.java http://www.bankrate.com/calculators/mortgages/amortization-calculator.aspx http://en.wikipedia.org/wiki/Mortgage_calculator
36
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 36
37
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:
38
Mapping Loop Variable Owed after N month: apply Owed after N month: Payoff loan after N month =>
39
Flexible (Variable) Number of Method Arguments In the most general case, Java allows flexible (variable) method signature, e.g., We will not learn how to define such methods, but will use some: printf() and format() (avoided by Java before 1.5 but available in C; typically preferred by many programmers) 39 public static type name ( param1, … param2 )
40
Formatting Text with printf System.out.printf(" format string ", parameters ); A format string can contain placeholders to insert parameters, e.g., %d integer %f real number %s string these placeholders are used instead of + concatenation m Example: int x = 3; int y = -17; System.out.printf("x is %d and y is %d!\n", x, y); printf does not drop to the next line unless you write \n https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html // x is 3 and y is -17!
41
printf Width % W d integer, W characters wide, right-aligned %- W d integer, W characters wide, left-aligned % W f real number, W characters wide, right-aligned ... for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 10; j++) { System.out.printf("%4d", (i * j)); } System.out.println(); // to end the line } Output: 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30
42
printf Precision %. D f real number, rounded to D digits after decimal % W. D f real number, W chars wide, D digits after decimal %- W. D f real number, W wide (left-align), D after decimal double gpa = 3.253764; System.out.printf("your GPA is %.1f\n", gpa); System.out.printf("more precisely: %8.3f\n", gpa); Output: your GPA is 3.3 more precisely: 3.254 8 3
43
printf Formatting Many more formatting control options supported by printf, e.g., using the comma (,) to display numbers with thousands separator 43 System.out.printf("%,d\n", 58625); System.out.printf("%,.2f\n", 12345678.9); Output: 58,625 12,345,678.90
44
System.out.printf and String.format String.format has the same formatting capability as printf, except that printf outputs and String.format returns: 44 System.out.printf("%,.2f\n", 12345678.9); String s = String.format("%,.2f\n", 12345678.9); System.out.print( s ); Output: 12,345,678.90
45
Exercise: F2C Revise F2C print 2 decimal digits.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.