1 Simple Methods Chap. 4 Study Sections 4.1 – 4.4 Writing Reusable Formulas.

Slides:



Advertisements
Similar presentations
Chapter 2 Programming by Example. A Holistic Perspective Three sections separated by blank lines. Program comment File: FileName.java
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Alice in Action with Java
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Static Methods Chapter 4. Chapter Contents Objectives 4.1 Introductory Example: Old MacDonald Had a Farm … 4.2 Getting Started with Methods 4.3 Example:
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
©2004 Brooks/Cole Chapter 6 Methods. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Using Methods We've already seen examples of using methods.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
Some Java Fundamentals Chapter 2. Chapter Contents Chapter Objectives 2.1 Example: A Payroll Program 2.2 Types, Variables, and Constants Part of the Picture:
Computer Programming 1 Problem Solving and Software Engineering.
Chapter 2 storing numbers and creating objects Pages in Horstmann.
11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.
Introduction to Methods
Basic Elements of C++ Chapter 2.
Software Engineering 1 (Chap. 1) Object-Centered Design.
1 4.3 Example: Volume of a Sphere Given the radius r, what is the weight of a ball (sphere) of wound twine?Given the radius r, what is the weight of a.
Chapter 2 Classes and Methods I Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
CSCI 1730 January 17 th, 2012 © by Pearson Education, Inc. All Rights Reserved.
Classes, Objects, and Methods
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.
The Java Programming Language
Libraries Making Functions Globally Reusable (§ 6.4) 1.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Libraries 1 Making Functions Globally Reusable (§ 4.6)
1 Simple Functions Writing Reuseable Formulas. In Math Suppose f (x) = 2 x 2 +5Suppose f (x) = 2 x 2 +5 f(5)=?f(5)=? f(5) = 2* =55f(5) = 2*
CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.
1 An Example. Problem Using OCD, design and implement a program that computes the area and circumference of an Australian Rules Football field, which.
1 An Example. Problem Using OCD, design and implement a program that computes the area and circumference of an Australian Rules Football field, which.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
1 Operations Making Things Happen (Chap. 3) Expressions.
1 Simple Methods Chap. 4 Study Sections 4.1 – 4.4 Writing Reusable Formulas.
Alice in Action with Java Chapter 9 Methods. Alice in Action with Java2 Non- void vs. void Methods Alice messages –Methods: messages sent where a statement.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Identifiers Identifiers in Java are composed of a series of letters and digits where the first character must be a letter. –Identifiers should help to.
1 Building Java Programs Chapter 3: Introduction to Parameters and Objects These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Sections 5.1 – 5.4 © Copyright by Pearson Education, Inc. All Rights Reserved.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
1 Controlling Behavior Chap.5 Study Sections 5.1 – 5.3 The if and for Statements.
Simple Functions Writing Reuseable Formulas. Problem Using OCD, design and implement a program that computes the area and circumference of an Australian.
Chapter 3 : Top Down Design with Functions By Suraya Alias.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Libraries 1 Making Functions Globally Reusable (§ 6.4)
Invoking methods in the Java library. Jargon: method invocation Terminology: Invoking a method = executing a method Other phrases with exactly the same.
Software Engineering (Chap. 1) Object-Centered Design When we prepare a program, the experience can be just like composing poetry or music … My claim is.
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.
(C) 2010 Pearson Education, Inc. All rights reserved.  Best way to develop and maintain a large program is to construct it from small, simple pieces,
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
More About Objects and Methods
Chapter Topics The Basics of a C++ Program Data Types
Chapter 7 User-Defined Methods.
Introduction to Programmer-Defined Functions
Yanal Alahmad Java Workshop Yanal Alahmad
Methods Chapter 6.
Writing Reuseable Formulas
Classes, Objects, and Methods
Object Oriented Programming in java
Classes, Objects and Methods
Presentation transcript:

1 Simple Methods Chap. 4 Study Sections 4.1 – 4.4 Writing Reusable Formulas

Example Last time, we designed and implemented a program to compute the area and the circumference of an ellipse

Description Java Type Kind Name program new class -- Ellipse screen Screen variabletheScreen prompt String constant--none-- major axis double variablemajorAxis minor axis double variableminorAxis keyboard Keyboard variabletheKeyboard area double variablearea circumference double variablecircumference label String constant--none-- 3 π double half major axis double half minor axis double constantPI variablesemiMajor variablesemiMinor These were our objects:

Description Built-in/ClassName display strings Screenprint() read doubles KeyboardreadDouble() compute area – multiply doublesbuilt-in * compute circumference – multiply doublesbuilt-in * – add doublesbuilt-in + – divide doublesbuilt-in / – power – square root display doubles Screenprintln() 4 Math pow() Math sqrt() And these were our operations:

1. Ask theScreen to display a prompt for the length and width of an ellipse. 2. Ask theKeyboard to read majorAxis, minorAxis. 3. Check validity of data (both numbers are positive). 4. Compute semiMajor = majorAxis /2.0; semiMinor = minorAxis / Compute area = PI * semiMajor * semiMinor 6. Compute circumference = 2.0 * PI * sqrt((semiMajor 2 + semiMinor 2 ) / 2.0) 7. Display area and circumference with descriptive labels. 5 This was our algorithm:

6 /* Ellipse.java computes an ellipse's area and circumference. * Input: Ellipse's length and width * Output: Ellipse's area and circumference * Written by L. Nyhoff for CPSC 185 Project 99 on 9/23/2002 */ import ann.easyio.*; // Keyboard, Screen class Ellipse extends Object { public static void main(String [] args) { Screen theScreen = new Screen(); Keyboard theKeyboard = new Keyboard(); // Get the axes theScreen.print("To compute the area and circumference of an " + "ellipse,\n\tenter its major & minor axes: "); double majorAxis = theKeyboard.readDouble(); double minorAxis = theKeyboard.readDouble(); And this was our code:

7 // Check validity of the input values theScreen.println("Nonegative values? " + (majorAxis > 0 && minorAxis > 0) ); // Compute area and circumference double semiMajor = majorAxis / 2.0; double semiMinor = minorAxis / 2.0; double area = Math.PI * semiMajor * semiMinor; double circumference = 2.0 * Math.PI * Math.sqrt( ( Math.pow(semiMajor, 2) + Math.pow(semiMinor, 2) ) / 2.0 ) ; // Output area and circumference theScreen.println("\nThe area is " + area + "\nand the circumference is " + circumference); }

8 We executed it several times -- with test data and with other data; Here is the output produced to solve our original problem for an ellipse with major axis 165 and minor axis 135: To compute the area and circumference of an ellipse, enter its major & minor axes: enter its major & minor axes: The area is and the circumference is

9 After a program has been developed and tested, it may be necessary sometime later to modify it by changing features or adding new ones to meet new requirements, to satisfy a customer, etc. For example, for our problem, the values for the area and the circumference are each displayed with 13 decimal places. For this problem, this is probably more than necessary and/or may not be acceptable to the customer. (This would almost surely be the case if we were displaying monetary amounts!) So, how can we fix this? Maintenance

10 For output, we have used the print() and println() methods from the Screen class, which display numbers in a system-defined default manner. The Screen class also has several printFormatted() methods that allow us to specify our own formatting. The easiest one to use has the form: theScreen.printFormatted(dubValue, decimalDigits); theScreen.printFormatted(dubValue, decimalDigits); Other forms allow one to specify the number of integer digits (before the dec. point) and to specify a fill character (e.g., '*' to fill blank spaces). See pp.52-54

11 If we change our last output statement, to If we change our last output statement, // Output area and circumference theScreen.println("\nThe area is " + area + "\nand the circumference is " + circumference); to // Output area and circumference theScreen.print("\nThe area is ").printFormatted(area, 2).print("\nand the circumference is ").printFormatted(circumference, 2).println(); the output produced will be To compute the area and circumference of an ellipse, enter its major & minor axes: Nonegative values? true The area is 17, and the circumference is Nice... but there's a bigger issue...

12 We worked fairly hard to create the expressions for an ellipse's area and circumference, but we have no way to directly reuse that work if we ever need these ellipse-related formulas again. Solution: Encapsulate those formulas in methods (called functions in C++ and other languages). Problem Why use methods? Eliminate duplicate code Reuse code In OCD – implement new operations – implement new types packages (or libraries) large-scale reuse classes wider reuse

13 Methods often receive values in special variables known as parameters. Each parameter is given a name and a type (like any other variable). A method can also return one value known as its return value. This return value also has a type. (It is void if no value is returned.) A value is returned by means of a return statement: return expression; (Not used or expression is omitted for void methods.) Some Terminology We'll create our methods from the ground up, but first some definitions.

Example – Version 2 /* Method to find area of an ellipse * Receive: major and minor axes * Return: area of ellipse */ public static double EllipseArea(double major, double minor) { double semiMajor = major/2.0, semiMinor = minor/2.0; return Math.PI * semiMajor * semiMinor; } /* Ellipse.java computes an ellipse's area and circumference. * Input: Ellipse's length and width * Output: Ellipse's area and circumference * Written by L. Nyhoff for CPSC 185 Project 100 on 9/24/2002 */ import ann.easyio.*; // Keyboard, Screen class Ellipse extends Object { 14

/* Class method to find circumference of an ellipse * Receive: major and minor axes * Return: circumference of ellipse */ public static double EllipseCircumference (double major, double minor) { double semiMajor = major/2.0, semiMinor = minor/2.0; return 2.0 * Math.PI * Math.sqrt( (Math.pow(semiMajor, 2.0) + Math.pow(semiMinor, 2.0)) / 2.0 ); } 15 public static void main(String [] args) { Screen theScreen = new Screen(); Keyboard theKeyboard = new Keyboard();

// Get the axes theScreen.print("To compute the area and circumference of an " + "ellipse,\n\tenter its major & minor axes: "); double majorAxis = theKeyboard.readDouble(); double minorAxis = theKeyboard.readDouble(); // Check validity of the input values theScreen.println("Nonegative values? " + (majorAxis > 0 && minorAxis > 0) ); // Compute area and circumference // Output area and circumference theScreen.println("\nThe area is " + area + "\nand the circumference is " + circumference); } 16 double area = EllipseArea(majorAxis, minorAxis); double circumference = EllipseCircumference(majorAxis, minorAxis);

Parameters method method Parameters are method variables for which the caller can specify values. They are declared between the parentheses of a method’s heading. public static double EllipseArea(double major, double minor) { double semiMajor = major/2.0, semiMinor = minor/2.0; return Math.PI * semiMajor * semiMinor; } 17

Arguments which are stored in the method’s parameters. double area = EllipseArea(165, 135); The method then executes using its parameter values and sends its return value back to the caller public static double EllipseArea(double major, double minor) { } double semiMajor = major/2.0, semiMinor = minor/2.0; return Math.PI * semiMajor * semiMinor; When a method is called from another method, its caller can pass it values called arguments

General Form of Method Definition Syntax: modifiers returnType methodName(parameterDeclarations) { statements } modifiers : specify ( static, public, private, etc.) modifiers : specify various features of the method ( static, public, private, etc.) returnType : type of value returned by method, or void if it does not return a value methodName :identifier that names the method parameterDeclarations : list of parameters (separated by commas) for which values must be provided statements :specify the behavior of the method p. 169 heading body 19

public static double EllipseArea(double major, double minor) { double semiMajor = major/2.0, semiMinor = minor/2.0; return PI * semiMajor * semiMinor; } public : other classes can access itstatic: it's a class method; access it by sending message to the class, not to an object A good name describes and documents what the method does Returns a double value Parameters: Receives two double values In contrast to an instance method

When a method definition is placed inside a class definition, it can be called by other methods within that class with: methodName(argument_list) When a public static method definition is placed inside a class ClassName, it can be called by methods in another class with: ClassName.methodName(argument_list) void methods do not return a value but may have a return statement with no return value to return execution to the calling method. Notes 21

The number of arguments must match the number of parameters. The type of each argument must be compatible with (the same as or can be promoted to) the type of the corresponding parameter.The number of arguments must match the number of parameters. The type of each argument must be compatible with (the same as or can be promoted to) the type of the corresponding parameter. Variables like semiMajor and semiMinor that are declared in the body of a method are called ; they exist only while the. This means:Variables like semiMajor and semiMinor that are declared in the body of a method are called locals; they exist only while the method is executing. This means: –They can only be accessed within the method. –Other methods can use the same identifiers as locals without conflict. For primitive types, the value of an argument is to the corresponding parameter. Thus, changing the parameter's value in the method will not change the argument in the calling method.For primitive types, the value of an argument is copied to the corresponding parameter. Thus, changing the parameter's value in the method will not change the argument in the calling method. 22 Parameter Passing

For reference types, an argument is a ; it stores the of the memory location where the object it refers to is stored. For reference types, an argument is a handle; it stores the address of the memory location where the object it refers to is stored. 23 methodName(x, y, theScreen) public static methodName(int x, double y, Screen aScreen) abcdefghi jklmnopq rstuvwxyz x... Result: aScreen and theScreen are for the same object; i.e., they both. Result: aScreen and theScreen are aliases for the same object; i.e., they both refer to the same object. Alias Problem: 0x... This means that if methodName changes the object referred to by parameter aScreen, this also changes the object referred to by the argument theScreen. It is this address that gets copied to the corresponding parameter. It is this address that gets copied to the corresponding parameter.

1.Describe behavior of program 2.Identify the objects in the problem 3.Identify the operations needed to solve the problem. If one isn't provided in the programming language: a. Build a to perform it. If one isn't provided in the programming language: a. Build a method to perform it. b. Store the method in a for which it represents an operation. b. Store the method in a class for which it represents an operation. 4.Develop an algorithm OCD with Methods 24 Thus, for our ellipse problem, we really should store the area and circumference methods in a class of operations for ellipses.

An Ellipse Class /* Method to find area of an ellipse * Receive: major and minor axes * Return: area of ellipse */ public static double area(double major, double minor) { double semiMajor = major/2.0, semiMinor = minor/2.0; return Math.PI * semiMajor * semiMinor; } /* This ellipse class contains operations for ellipses: 1. Compute area 2. Compute circumference... other operations... Written by L. Nyhoff for CPSC 185 Project 100 on 9/24/2002 */ class Ellipse extends Object { 25

/* Class method to find circumference of an ellipse * Receive: major and minor axes * Return: circumference of ellipse */ public static double circumference(double major, double minor) { double semiMajor = major/2.0, semiMinor = minor/2.0; return 2.0 * Math.PI * Math.sqrt( (Math.pow(semiMajor, 2.0) + Math.pow(semiMinor, 2.0)) / 2.0 ); } } // end of Ellipse class definition 26 To test our methods, we usually write a that exercises each method with various sets of test data. To test our methods, we usually write a driver program that exercises each method with various sets of test data.

//--- Driver program to test the Ellipse class //--- Written by L. Nyhoff for CPSC 185 Project 100 on 9/24/2002 import ann.easyio.*; 27 class EllipseDriver extends Object { public static void main(String [] args) { Screen theScreen = new Screen(); Keyboard theKeyboard = new Keyboard(); theScreen.print("Enter major & minor axes of an ellipse: "); double majorAxis = theKeyboard.readDouble(); double minorAxis = theKeyboard.readDouble(); theScreen.println("\nThe area is " + Ellipse.area(majorAxis, minorAxis) + "\nand the circumference is " + Ellipse.circumference(majorAxis, minorAxis)); }

//--- Driver program to test the Ellipse class //--- Written by L. Nyhoff for CPSC 185 Project 100 on 9/24/2002 import ann.easyio.*; 28 class EllipseDriver extends Object { public static void main(String [] args) { Screen theScreen = new Screen(); Keyboard theKeyboard = new Keyboard(); theScreen.print("Enter major & minor axes of an ellipse: "); double majorAxis = theKeyboard.readDouble(); double minorAxis = theKeyboard.readDouble(); theScreen.println("\nThe area is " + Ellipse.area(majorAxis, minorAxis) + "\nand the circumference is " + Ellipse.circumference(majorAxis, minorAxis)); } // Insert definition of class Ellipse here We can insert the definition of class Ellipse into our program: See Fig. 4.1

//--- Driver program to test the Ellipse class //--- Written by L. Nyhoff for CPSC 185 Project 100 on 9/24/2002 import ann.easyio.*; 29 class EllipseDriver extends Object { public static void main(String [] args) { Screen theScreen = new Screen(); Keyboard theKeyboard = new Keyboard(); theScreen.print("Enter major & minor axes of an ellipse: "); double majorAxis = theKeyboard.readDouble(); double minorAxis = theKeyboard.readDouble(); theScreen.println("\nThe area is " + Ellipse.area(majorAxis, minorAxis) + "\nand the circumference is " + Ellipse.circumference(majorAxis, minorAxis)); } Or we can put the definition of class Ellipse in a separate file Ellipse.java, but in the same directory as the EllipseDriver.java, compile the two files separately, and then execute EllipseDriver with java EllipseDriver. See modified (next slide) Fig. 4.5

Some Typos/Changes in Chapter 4: Page 178: Figure 4.3 Change import ann.easyio. to import ann.easyio. *;Page 178: Figure 4.3 Change import ann.easyio. to import ann.easyio. *; Change EinsteinConvert to EinsteinConverter Page 190: Figure 4.5 Delete import Sphere;Page 190: Figure 4.5 Delete import Sphere; This was okay in earlier versions of Java, but in Java 1.4, import can be used only with packages, not with class files. 30

31 Work through the Volume of a Sphere example in Section 4.3. Not the use of OCD to design a solution to the original problem and how it is used in the same way to design the volume and mass methods. Note the photo on p. 184 Note the photo on p. 184 Also read the summary on methods in Sec. 4.4 & Chap. Summary (pp.196-7)