CS 112 Introduction to Programming Summary of Method Definition and Invocation; printf/format Formatting Yang (Richard) Yang Computer Science Department.

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

BUILDING JAVA PROGRAMS CHAPTER 3 PARAMETERS AND OBJECTS.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
BUILDING JAVA PROGRAMS CHAPTER 6.4 FILE OUTPUT. 22 PrintStream : An object in the java.io package that lets you print output to a destination such as.
1 Parameters. 2 Repetitive figures Consider the task of drawing the following figures: ************* ******* *********************************** **********
Copyright 2008 by Pearson Education Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs Lecture 3-1: Parameters (reading: 3.1)
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
Copyright 2006 by Pearson Education 1 reading: 4.1 Cumulative sum.
Copyright 2008 by Pearson Education 1 Class constants and scope reading: 2.4 self-check: 28 exercises: 11 videos: Ch. 2 #5.
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.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
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 7 parameters Based on slides bu Marty Stepp and Stuart Reges from "We're flooding people with information. We.
11 Chapter 3 DECISION STRUCTURES CONT’D. 22 FORMATTING FLOATING-POINT VALUES WITH THE DecimalFormat CLASS We can use the DecimalFormat class to control.
Topic 12 more if/else, cumulative algorithms, printf Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
1 Text Processing. 2 Type char char : A primitive type representing single characters. –A String is stored internally as an array of char String s = "Ali.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Building Java Programs Chapter 3 Parameters and Objects Copyright (c) Pearson All rights reserved.
CS 112 Introduction to Programming Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Procedural programming in Java Methods, parameters and return values.
CS 112 Introduction to Programming Graphics; Animation Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Building Java Programs Parameters and Objects. 2 Redundant recipes Recipe for baking 20 cookies: –Mix the following ingredients in a bowl: 4 cups flour.
Building Java Programs Chapter 3 Lecture 3-1: Parameters reading: 3.1.
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.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
CS 112 Introduction to Programming Animations; Methods with return Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
CS 112 Introduction to Programming Summary of Methods; User Input using Scanner Yang (Richard) Yang Computer Science Department Yale University 308A Watson,
Copyright 2010 by Pearson Education Building Java Programs Chapter 3 Lecture 3-1: Parameters reading: 3.1.
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 2009 by Pearson Education Building Java Programs Chapter 3 Lecture 3-1: Parameters reading: 3.1 self-check: #1-6 exercises: #1-3 videos: Ch.
CCSA 221 Programming in C CHAPTER 3 COMPILING AND RUNNING YOUR FIRST PROGRAM 1 ALHANOUF ALAMR.
Building Java Programs Chapter 3
Lecture 3: Method Parameters
Chapter 7 User-Defined Methods.
Building Java Programs
CSCI 161 – Introduction to Programming I William Killian
Building Java Programs
Building Java Programs
Methods.
OUTPUT STATEMENTS GC 201.
Building Java Programs
Topic 7 parameters "We're flooding people with information. We need to feed it through a processor. A human must turn information into intelligence or.
Building Java Programs
Redundant recipes Recipe for baking 20 cookies:
Building Java Programs
Building Java Programs
Lecture 3: Method Parameters
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
CSE 142 Lecture Notes Global Constants, Parameters, Return Values
Scope scope: The part of a program where a variable exists. From its declaration to the end of the { } braces A variable declared in a for loop exists.
Building Java Programs
Building Java Programs
Building Java Programs
Corresponds with Chapter 5
Presentation transcript:

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:

Outline  Admin and recap  Summary of method definitions and invocation m Method overloading m printf and String.format 2

Admin  PS4 posted yesterday m There was some revision (Part 2 was changed) to PS4. Please be sure to reload the page 3

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/ ) { 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. 5

Without Animation

Animation: Use Both Screen (Video Memory) and (Double) Buffer In animation mode, drawing is in the (double) buffer Next show(t) statement copies to screen

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

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

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

Outline  Admin and recap  Summary of method definitions and invocation 15

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

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:

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 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 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?

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

Value Semantics int a = 100; double x = 45.12; a x A value variable stores a value of the type of the variable.

25 Value Variables int a = 100; double x = 45.12; int aa; 100 a x aa

26 Value-Variable Assignment int a = 100; double x = 45.12; int aa; aa = a; 100 a x aa An assignment of one value variable to another value variable copies the value. 100

27 Value-Variable Assignment int a = 100; double x = 45.12; int aa; aa = a; a = 200; 100 a x aa 100 Change the value of one value variable will not change the other. 200

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 = x = 23

Explanation: main() start 29 public static void main(String[] args) { int x = 23; strange(x); System.out.println("2. x = " + x); } 23 args x

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

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

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

Explanation: Method return 33 public static void main(String[] args) { int x = 23; strange(x); System.out.println("2. x = " + x); } 23 args x

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

(Offline) Practice: Loan Calculator  Design a loan program to compute the monthly amortization table of a fixed-rate loan 35 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 36

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 =>

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 )

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 // x is 3 and y is -17!

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:

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 = ; 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:

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", ); Output: 58,625 12,345,678.90

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", ); String s = String.format("%,.2f\n", ); System.out.print( s ); Output: 12,345,678.90

Exercise: F2C  Revise F2C print 2 decimal digits.