Introduction to Computers and Programming Lecture 11: Introduction to Methods Professor: Evan Korth New York University.

Slides:



Advertisements
Similar presentations
Procedural programming in Java
Advertisements

JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
PAC Introduction to Methods Professor: Evan Korth New York University.
Introduction to Computers and Programming Lecture 11: Introduction to Methods Professor: Evan Korth New York University.
1 Lecture 4: Chapter 6 - Methods Outline Introduction Program Modules in Java Math -Class Methods Method Declarations Java API Packages Random-Number Generation.
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
 2003 Prentice Hall, Inc. All rights reserved. 7.1 Introduction Arrays –Data structures which reference one or more value –All items must have same data.
Introduction to Computers and Programming Introduction to Methods in Java.
Overloading methods review When is the return statement required? What do the following method headers tell us? public static int max (int a, int b)
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
Introduction to Computers and Programming Lecture 12: Math.random() Professor: Evan Korth New York University.
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Introduction to Computers and Programming Lecture 16: Arrays (cont) Professor: Evan Korth New York University.
Math class methods & User defined methods Math class methods Math.sqrt(4.0) Math.random() java.lang is the library/package that provides Math class methods.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
 2007 Pearson Education, Inc. All rights reserved C Functions.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using.
1 Introduction to Computers and Programming Quick Review What is a Function? A module of code that performs a specific job.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Review for Midterm 2 Nested loops & Math class methods & User defined methods.
Introduction to Computers and Programming Lecture 13: User defined methods Instructor: Evan Korth New York University.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Functions Part I.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
 2003 Prentice Hall, Inc. All rights reserved Introduction Modules –Small pieces of a problem e.g., divide and conquer –Facilitate design, implementation,
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
1 Lecture 3 Part 1 Functions with math and randomness.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
1 Introduction Modules  Most computer programs solve much larger problem than the examples in last sessions.  The problem is more manageable and easy.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
 2005 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Introduction to Computers and Programming Lecture 14: User defined methods (cont) Professor: Evan Korth New York University.
Programming in C++ Language ( ) Lecture 5: Functions-Part1 Dr. Lubna Badri.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
Procedural programming in Java Methods, parameters and return values.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions Outline 5.1Introduction 5.2Program Modules.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Using Java MINISTRY OF EDUCATION & HIGHER EDUCATION COLLEGE OF SCIENCE AND TECHNOLOGY KHANYOUNIS- PALESTINE Lecture 15,16 Java’s Methods.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
Review for Nested loops & Math class methods & User defined methods.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "___________________" in Java Purpose –Reuse code –Modularize.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 – Methods Part I.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Methods Outline 6.1 Introduction 6.2 Program Modules in Java 6.3 Math -Class Methods 6.4.
Introduction Modules Small pieces of a problem ▴ e.g., divide and conquer Facilitate design, implementation, operation and maintenance of large programs.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Functions and an Introduction to Recursion
“Form Ever Follows Function” Louis Henri Sullivan
Methods Chapter 6.
CSC113: Computer Programming (Theory = 03, Lab = 01)
Introduction to Methods
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions Declarations CSCI 230
Chapter 6 Methods: A Deeper Look
Java Methods: A Deeper Look Academic 2019 Class: BIT23/BCS10 Chapter 06 Abdulaziz Yasin Nageye Faculty of Computing Java How to Program, 10/e 1 © Co py.
6 Functions.
Presentation transcript:

Introduction to Computers and Programming Lecture 11: Introduction to Methods Professor: Evan Korth New York University

Road Map Introduction to Methods –Divide and Conquer –Abstraction Using Pre-Packaged Modules –Understanding Method signatures –Understanding java.lang.math methods Creating your own methods Reading: –Liang 5: Chapter 4: Sections 4.1 – 4.3; – –Liang 6: Chapter 5: Sections ;

Introduction to Methods

 2003 Prentice Hall, Inc. All rights reserved. 6.1 Introduction Modules –Small pieces of a problem e.g., divide and conquer –Facilitate design, implementation, operation and maintenance of large programs

 2003 Prentice Hall, Inc. All rights reserved. 6.2 Program Modules in Java Modules in Java –Methods (procedural programming) –Classes (object oriented programming) Java API provides several modules Programmers can also create modules –e.g., programmer-defined methods Methods –Invoked by a method call –Returns a result to calling method (caller) –Similar to a boss (caller) asking a worker (called method) to complete a task. The boss method delegates certain jobs to specific methods. Modified by Evan Korth

 2003 Prentice Hall, Inc. All rights reserved. Fig. 6.1 Hierarchical boss-method/worker-method relationship. boss worker1worker2worker3 worker4worker5

Examples of methods A method that determines the maximum of two numbers. A method that sorts a list of names A method that opens a file from the file system. A method that reads from the open file. A method that opens a new socket to the internet. A method that reads from that socket. A method that parses an integer value from a String. A method that gets a String from the user.

Important concept #1 Divide and Conquer: Break large programs into a series of smaller modules –Helps manage complexity –Makes it easier to build large programs –Makes it easier to debug programs

Important concept #2 Abstraction: Most of the time, you need to know what a method does, but not how it actually does it. –Also helps manage complexity –You use other people’s code without knowing how it does it’s job.

Using Static methods in the Java API

 2003 Prentice Hall, Inc. All rights reserved. 6.3 Math -Class Methods Class java.lang.Math –Provides common mathematical calculations –Calculate the square root of : Math.sqrt( ) –Method sqrt belongs to class Math Dot (. ) allows access to method sqrt –The argument is located inside parentheses

 2003 Prentice Hall, Inc. All rights reserved.

6.4 Methods Declarations Methods –Allow programmers to modularize programs Makes program development more manageable Software reusability Avoid repeating code –Local variables Declared in method declaration –Parameters Communicates information between methods via method calls

 2003 Prentice Hall, Inc. All rights reserved. 6.4 Method Declarations (Cont.) Programmers can write customized methods

Line 9: method call to square line 16: header for method square. States that we have a method that accepts one integer as a parameter and returns one integer line 18: returns the value y * y 1// Fig. 6.3: SquareIntegers.java 2// Creating and using a programmer-defined method. 3public class SquareIntegers { 4public static void main (String args[]) 5{ 6int result; // store result of call to method square 7// loop 10 times 8for ( int counter = 1; counter <= 10; counter++ ) { 9result = square( counter ); // method call 10// print the result of one call to the method 11System.out.println ("The square of " + counter + " is " + 12result ); 13} // end for 14} // end method main() 15// square method declaration 16public static int square( int y ) 17{ 18return y * y; // return square of y 19} // end method square 20} // end class SquareIntegers Method square returns int that result stores Modified by Evan Korth  2003 Prentice Hall, Inc. All rights reserved. Method square returns the square of y y is the parameter of method square

 2003 Prentice Hall, Inc. All rights reserved. 6.4 Method Declarations (cont.) General format of method declaration: modifiers return-value-type method-name ( parameter1, …, parameterN ) { declarations and statements } Method can also return values: return expression ;

Introduction to Computers and Programming Lecture 12: Math.random() Professor: Evan Korth New York University

Road Map Math.random Reading: –Liang 5: Chapter 4: Section –Liang 6: Chapter 5: Section 5.9.5

review What is a method? What information can you learn about a method from its header? What does it mean to invoke a method? What is the difference between a formal parameter and an actual parameter? Why don’t we have to import the Math class? What is abstraction in computer science?

random numbers Often we want our programs to generate random numbers. –games of chance –testing without user interaction java.lang.Math provides a method which can be used to generate random numbers

 2003 Prentice Hall, Inc. All rights reserved. Random-Number Generation Java random-number generators –Math.random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. –What if we want to generate random integers?

 2003 Prentice Hall, Inc. All rights reserved. Random-Number Generation –( int ) ( Math.random() * 6 ) Produces integers from 0 - 5

 2003 Prentice Hall, Inc. All rights reserved. Outline RandomIntegers. java Line 16 Produce integers in range 1-6 Line 16 Math.random returns double s. We cast the double as an int 1 // Fig. 6.7: RandomIntegers.java 2 // Shifted, scaled random integers. 3 import javax.swing.JOptionPane; 4 5 public class RandomIntegers { 6 7 public static void main( String args[] ) 8 { 9 int value; 10 String output = ""; // loop 20 times 13 for ( int counter = 1; counter <= 20; counter++ ) { // pick random integer between 1 and 6 16 value = 1 + ( int ) ( Math.random() * 6 ); output += value + " "; // append value to output // if counter divisible by 5, append newline to String output 21 if ( counter % 5 == 0 ) 22 output += "\n"; } // end for 25 Produce integers in range 1-6 Math.random returns double s. We cast the double as an int

 2003 Prentice Hall, Inc. All rights reserved. Outline RandomIntegers. java 26 JOptionPane.showMessageDialog( null, output, 27 "20 Random Numbers from 1 to 6", 28 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class RandomIntegers

 2003 Prentice Hall, Inc. All rights reserved. Outline RollDie.java Line 14 Produce integers in range 1-6 Lines Increment appropriate frequency counter, depending on randomly generated number 1 // Fig. 6.8: RollDie.java 2 // Roll a six-sided die 6000 times. 3 import javax.swing.*; 4 5 public class RollDie { 6 7 public static void main( String args[] ) 8 { 9 int frequency1 = 0, frequency2 = 0, frequency3 = 0, 10 frequency4 = 0, frequency5 = 0, frequency6 = 0, face; // summarize results 13 for ( int roll = 1; roll <= 6000; roll++ ) { 14 face = 1 + ( int ) ( Math.random() * 6 ); // determine roll value and increment appropriate counter 17 switch ( face ) { case 1: 20 ++frequency1; 21 break; case 2: 24 ++frequency2; 25 break; case 3: 28 ++frequency3; 29 break; 30 Produce integers in range 1-6 Increment appropriate frequency counter, depending on randomly generated number

 2003 Prentice Hall, Inc. All rights reserved. Outline RollDie.java 31 case 4: 32 ++frequency4; 33 break; case 5: 36 ++frequency5; 37 break; case 6: 40 ++frequency6; 41 break; } // end switch } // end for JTextArea outputArea = new JTextArea(); outputArea.setText( "Face\tFrequency" + "\n1\t" + frequency "\n2\t" + frequency2 + "\n3\t" + frequency "\n4\t" + frequency4 + "\n5\t" + frequency "\n6\t" + frequency6 ); JOptionPane.showMessageDialog( null, outputArea, 55 "Rolling a Die 6000 Times", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class RollDie This is different from the example I showed in the compiler. I left it this way to show you that showMessageDialog() can take other objects besides String for the message. Remember the API. You do not need to know JTextArea for this class!

 2003 Prentice Hall, Inc. All rights reserved.

Introduction to Computers and Programming Lecture 13: User defined methods Instructor: Evan Korth New York University

Road Map Method abstraction Divide and conquer Examine parameters Examine return types Argument promotion Reading: –Liang 5: , part 4.4, 4.7 –Liang 6:

review What information can you learn about a method from its header? What is the difference between a formal parameter and an actual parameter? What does Math.random() return?

Benefits of Methods Experience has shown that the best way to develop and maintain large programs is to build it from smaller components or modules. In Java, one such module is the method. Each module is generally simpler and more manageable than the entire program. This concept is known as Divide and Conquer, also with Abstraction in the mix.

Divide and Conquer Divide and Conquer: break large programs into a series of smaller methods. –Helps manage complexity –Makes it easier to build large programs –Makes is easier to debug programs

Abstraction Abstraction: most of the time, you need to know what a method does, but not how it actually does it. –Also helps manage complexity. –You can use other people’s code, without understanding how it works. If you have code that would appear more than once, put it in a method and call that method multiple times –Reduces length and complexity of code –Reduces likelihood of errors in code

 2003 Prentice Hall, Inc. All rights reserved. User defined Method Declarations General format of method declaration: modifiers return-value-type method-name ( parameter1, …, parameterN ) { declarations and statements } Method can also return values: return expression ;

Naming your methods As with variables naming methods is important You should give your methods names which clearly describe what the function is doing –helps debugging –helps others read your code Same rules as naming variables –E.g. public static double calculateTax( int sale ) When you write about a method in an explanation use the parenthesis to indicate you are referencing a method (as opposed to a regular variable): –E.g. //call squareInteger() to calculate the square

Good programming with methods A method should do one and only one useful action –If you see names for your method that suggest multiple actions then it’s time to break it up into separate functions; for example, calculateTaxAndPrintReturnAndSaveFile(); -ugh If you do something more than once in a program, you should write a method for that action.

More Good Programming If you have written a method to do something in one project, and you need to do the same action in another project, you should reuse the method. –In Java this is usually accomplished by using classes which we will not cover this semester.

Return Value Types You can only return one value from a method. Returning void –void : means nothing –A method that returns void therefore returns nothing. –Hence, there is no need for the optional return statement. But using one can force early exit from the method. –Example: public static void printIntro (int n);

Parameter Data Types Unlike return values, you can pass as many parameters as you like. To pass more than one parameter, you need to separate the parameters with commas. public static int maximum (int x, int y) { /*body*/ }

Warning Unlike declaring variables, you must specifically state the type for multiple variables –For example takeTwoFloats( float x, y ) is incorrect –Instead you must write takeTwoFloats(float x, float y)

No parameters You can also have a method that accepts no parameters. In such case, you would just have an empty parameter list. E.g. public static int rollDie () public static void printIntro ()

 2003 Prentice Hall, Inc. All rights reserved. 6.5 Argument Promotion Coercion of arguments –Forcing arguments to appropriate type to pass to method e.g., System.out.println( Math.sqrt( 4 ) ); –Evaluates Math.sqrt( 4 ) –Then evaluates System.out.println() Promotion rules –Specify how to convert types without data loss

 2003 Prentice Hall, Inc. All rights reserved.

Exercise 5.24 Implement the following methods –Method convertToCelsius returns the Celsius equivalent of a Fahrenheit temperature (( 5.0 / 9.0 * ( fTemp - 32 ) ) –Method convertToFahrenheit returns the Fehrenheit equivalent of a Celsius temperature ( 9.0 / 5.0 * cTemp + 32 ) –Use these methods to write a program that prints charts showing the Fahrenheit equivalent of all Celsius temperatures from 0 to 100 degrees, and the Celsius equivalents of all Fahrenheit temperatures from 32 to 212 degrees. Print the output in a neat tabular format.  2000 Prentice Hall, Inc. All rights reserved.

Exercise 2 Write a method that will print a line of stars. The method should take one parameter which will determine the number of stars to print. Write a main() method which calls the star printing method 5 times using random numbers from

Introduction to Computers and Programming Lecture 14: User defined methods (cont) Professor: Evan Korth New York University

Road Map Method Overloading Scope Pass-by-value Style: methods Reading: –Liang 5: chapter 4: 4.4 – 4.6 –Liang 6: chapter 5: , 5.8

review When is the return statement required? What do the following method headers tell us? public static int max (int a, int b) public static void nPrintln (String s, int n) public static void main (String args[]) public static int max (int a, n) public static String pickLine ()

review Given the following method headers: public static int max (int x, int y) public static double min (double x, double y) Which of the following method calls are legal? max (1,2); min (1,2); max (1.0, 2.0); min (1.0, 2.0);

 2003 Prentice Hall, Inc. All rights reserved Method Overloading Method overloading –Several methods of the same name –Different parameter set for each method Number of parameters Parameter types –The Java compiler determines which method to use based on the parameters. –Can also be used in conjunction with argument coercion. The combination can lead to ambiguous invocation which is an error

Understanding Scope

Scope Determines where the variable can be referenced in a program. By understanding scope, you can make your programs: –more modular –easier to debug

 2003 Prentice Hall, Inc. All rights reserved. 6.9 Scope of Declarations Scope –Portion of the program that can reference an entity by its name –Basic scope rules Scope of a parameter declaration –The entire method Scope of a local-variable declaration –From where it is declared until the end of the block it is declared in Scope of a local-variable declaration that appears in the initialization section of a for statement’s header –The entire code block of the for loop Modified by Evan Korth

pass by value In Java when a parameter is passed to a method and the variable is modified by that method, the value does not change upon return to the calling method (there are exceptions to this including passing arrays and passing object references) This is not true in all programming languages.

Document your methods An acceptable way is to precede the declaration with the following: /** *Returns the tax due based on the parameters. *Both parameters must be non-negative * income dollar amount of sale * taxRate tax rate for sale the tax due */ public static double calculateTax (double income, double taxRate) { … code…. } /* end method calculateTax */

Good Programming Habits Pick a method name that strongly, completely and clearly describes what the function does or returns –E.g. verb-plus-object or description of returned value (getters, setters, predicates are object orientated naming conventions) Make sure your actual parameters (i.e. the actual data you pass to a method) matches the data type the method expects. Make sure you use all the parameters in your method; if not, lose the ones you don’t use. Document any assumptions about your parameters!

More Good Programming Habits Limit the number of a method’s parameters to approximately seven –Studies have shown that people can’t keep track of more than seven pieces of info at once –(e.g. 7 digit phone numbers for a reason) If a method is to return a value, make sure it returns something under all possible circumstances. Actually, Java will enforce this for you.

Superman program Superman needs a program to print S’s of various size. You should have one method that prints the horizontal lines and one method that prints the vertical lines. Write the whole program. –Vertical lines can be in the first or last column and are width/2 – 1 characters tall. –For example, an S of size 6 would look like : SSSSSS S SSSSSS S SSSSSS

RaiseIntToPower Write a method raiseIntToPower that takes two integers, n and k, and returns n k. For example the method call: raiseIntToPower (2, 4); would return 16 Hints: –What value should you use to initialize the return value? –2 4 = 2 X 2 X 2 X 2 –You can assume n and k are non-negative