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.

Slides:



Advertisements
Similar presentations
Introduction to Eclipse. Start Eclipse Click and then click Eclipse from the menu: Or open a shell and type eclipse after the prompt.
Advertisements

Java Programming, 3e Concepts and Techniques Chapter 3 Section 63 – Manipulating Data Using Methods – Day 2.
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
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:
Java: How to Program Methods Summary Yingcai Xiao.
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 Functions. Computer Programming 2 Objectives Take a first look at building functions Study how a function is called Investigate.
Computer Programming 1 Problem Solving and Software Engineering.
Problem Solving and Software Engineering Chapter 1.
Chapter 6: User-Defined Functions I
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Writing methods. Calling Methods nameOfMethod(parameters) if method returns something, use that value Math.pow(2, 3) returns 8 System.out.println(Math.pow(2,
Writing Methods. Create the method Methods, like functions, do something They contain the code that performs the job Methods have two parts.
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.
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.
Problem Solving and Software Engineering Chapter 1.
Classes, Objects, and Methods
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
1 Introduction to Java Brief history of Java Sample Java Program Compiling & Executing Reading: => Section 1.1.
Chapter 6: User-Defined Functions
Class Example - Rationals Rational numbers are represented by the ratio of two integers, a numerator and a denominator, e.g., 2/3. This is opposed to irrational.
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.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) public static void main(String[]
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
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 Simple Methods Chap. 4 Study Sections 4.1 – 4.4 Writing Reusable Formulas.
1 CSE1340 Class 4. 2 Objectives Write a simple computer program in Java Use Swing components to build the GUI Use proper naming conventions for classes.
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
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Java methods Methods break down large problems into smaller ones Your program may call the same method many times saves writing and maintaining same code.
Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
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.
1 Simple Methods Chap. 4 Study Sections 4.1 – 4.4 Writing Reusable Formulas.
Creating a Java Application and Applet
Chapter 3: User-Defined Functions I
Unit Testing Part 2: Drivers and Stubs
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.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 6 - More About Problem Domain Classes1 Chapter 6 More About Problem Domain Classes.
Methods CSCI 1301 What is a method? A method is a collection of statements that performs a specific task. Pre-Defined methods: available in Java library.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Methods.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
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.
CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.
Creating Java Applications (Software Development Life Cycle) 1. specify the problem requirements - clarify 2. analyze the problem - Input? Processes? Output.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Review – Primitive Data What is primitive data? What are 3 examples of primitive data types? How is a piece of primitive data different from an object?
More About Objects and Methods
Chapter 7 User-Defined Methods.
Chapter 6: User-Defined Functions I
Chapter 10: Void Functions
Writing Reuseable Formulas
Writing Methods.
Classes, Objects, and Methods
CHAPTER 6 GENERAL-PURPOSE METHODS
Building Java Programs
Classes, Objects and Methods
Methods/Functions.
Presentation transcript:

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 ball (sphere) of wound twine? Object-Centered DesignObject-Centered Design — display prompt for radius — read value for radius — compute weight of sphere — display results on screen Note this is generalized for sphere of arbitrary sizeNote this is generalized for sphere of arbitrary size

2 Objects

3 Operations Display a String (prompt) on the screenDisplay a String (prompt) on the screen Read a number from keyboard, store it in radiusRead a number from keyboard, store it in radius Compute weight using radiusCompute weight using radius Display a number ( weight ) on screenDisplay a number ( weight ) on screen

4 New Class Required Java has no predefined operation for volume or weight of a sphereJava has no predefined operation for volume or weight of a sphere Also no predefined sphere objectAlso no predefined sphere object Solution:Solution: — build methods to calculate volume & weight — create a sphere class (module)to store the methods class Sphere { // method definitions } We will need an additional variable objectWe will need an additional variable object — density (weight = density * volume)

5 Volume Method – Objects Volume = 4  r 3 / 3Volume = 4  r 3 / 3 NoteNote — r is the only variable — 4, 3, and  are constants These (along with the result, volume) are the objects of this methodThese (along with the result, volume) are the objects of this method

6 Volume Method – Operations and Algorithm Receive real value ( radius ) from callerReceive real value ( radius ) from caller Cube the real value ( radius 3 )Cube the real value ( radius 3 ) Multiply by 4.0 and by Multiply by 4.0 and by  Divide by 3.0Divide by 3.0 Return result 4.0 *  * radius 3 /3.0Return result 4.0 *  * radius 3 /3.0

7 Defining the Class and Method class Sphere extends Object { } Can start with an empty class class Sphere extends Object { public static double volume(double radius) public static double volume(double radius) { } } } } and add a method stub Compiler error – "no return statement" – will result. If this is the only error, we know the rest is okay. Or we could could add a temporary "return 0" to method stub to avoid this.

8 class Sphere extends Object { public static double volume(double radius) public static double volume(double radius) { return 4.0 * Math.PI * Math.pow(radius, 3)/3.0; { return 4.0 * Math.PI * Math.pow(radius, 3)/3.0; } } } } Then code the method's algorithm in the body of the method:

9 And test the code with a simple driver like we did for our ellipse class: //-- In same directory as the Sphere class import ann.easyio.*; class SphereDriver extends Object { public static void main(String [] args) { Screen theScreen = new Screen(); Keyboard theKeyboard = new Keyboard(); theScreen.print("Enter radius of a sphere: "); double radius = theKeyboard.readDouble(); theScreen.println("\nThe volume is " + Sphere.volume(radius)); }

10 Mass Method mass = density * volume(radius)mass = density * volume(radius) — density and radius are the values received by the method — volume is a call to the volume method — mass is the result to be returned These are the objects of the methodThese are the objects of the method

11 Mass Algorithm Receive:Receive: — radius — density Multiply density times value returned by call to volume methodMultiply density times value returned by call to volume method Return these resultsReturn these results

12 Define the Mass Method class Sphere extends Object { public static double volume(double radius) public static double volume(double radius) {... } {... } public static double mass (double radius, double density) public static double mass (double radius, double density) { return density * volume(radius); } } { return density * volume(radius); } }

13 Algorithm for Main Method Construct theKeyboard, theScreenConstruct theKeyboard, theScreen theScreen displays prompt for radiustheScreen displays prompt for radius theKeyboard reads double value into radiustheKeyboard reads double value into radius theScreen displays prompt for densitytheScreen displays prompt for density theKeyboard reads a double into densitytheKeyboard reads a double into density Compute weight, using mass() method from class SphereCompute weight, using mass() method from class Sphere theScreen displays weight and descriptive texttheScreen displays weight and descriptive text

14 Test the Mass Method //-- In same directory as the Sphere class import ann.easyio.*; class SphereDriver extends Object { public static void main(String [] args) { Screen theScreen = new Screen(); Keyboard theKeyboard = new Keyboard(); theScreen.print("Enter radius of a sphere: "); double radius = theKeyboard.readDouble(); theScreen.println("\nThe volume is " + Sphere.volume(radius)); theScreen.print("Enter density: "); double density = theKeyboard.readDouble(); theScreen.println("\nThe mass is " + Sphere.mass(radius, density)); }

15 Code and Teste SphereWeigher Class for Original Problem Note source code in Figure 4.5Note source code in Figure 4.5 – Delete import Sphere class ; Put Sphere class in same directory as the client program – How it uses methods from Sphere class

16 /** SphereWeigher.java computes the weight of an arbitrary sphere. * Input: radius and density, both doubles. * Output: the weight of the sphere. */ import ann.easyio.*; // Keyboard, Screen,... import Sphere; class SphereWeigher extends Object { public static void main(String [] args) { Screen theScreen = new Screen(); theScreen.print("\nTo compute the weight of a sphere," + "\n enter its radius (in feet): "); Keyboard theKeyboard = new Keyboard(); double radius = theKeyboard.readDouble(); theScreen.print(" enter its density (in pounds/cubic foot): "); double density = theKeyboard.readDouble(); double weight = Sphere.mass(radius, density); theScreen.print("\nThe sphere's weight is approximately ").printFormatted(weight).println(" pounds."); }

17 /** Sphere.java provides a class to represent Sphere objects. * Contains static methods volume() and mass(). */ class Sphere extends Object { /** Static method to compute sphere's volume * Receive: radius, a double. * Precondition: radius > 0 * Return: the volume of a sphere of the given radius */ public static double volume(double radius) { return 4.0 * Math.PI * Math.pow(radius, 3) / 3.0; } /** Static method to compute sphere's volume * Receive: radius, a double. * Precondition: radius > 0 * Return: the volume of a sphere of the given radius */ public static double mass(double radius, double density) { return density * volume(radius); }

18 Sample run: To compute the weight of a sphere, enter its radius (in feet): 6.5 enter its radius (in feet): 6.5 enter its density (in pounds/cubic foot): 14.6 enter its density (in pounds/cubic foot): 14.6 The sphere's weight is approximately 16, pounds. The sphere's weight is approximately 16, pounds.

Methods: A Summary Specify a parameter for each value received by the methodSpecify a parameter for each value received by the method Value supplied to the parameter when method invoked is called an argumentValue supplied to the parameter when method invoked is called an argument Arguments matched with parameters from left to rightArguments matched with parameters from left to right — must be same number of arguments — types must match (be compatible)

20 If argument is a reference type, address is copied to parameterIf argument is a reference type, address is copied to parameter — both parameter and argument refer to same object Instance (object) methods defined without the static modifierInstance (object) methods defined without the static modifier — messages invoking them are sent to an instance of the class When method1() calls method2(), control returns to method1() when method2( ) finishesWhen method1() calls method2(), control returns to method1() when method2( ) finishes

21 Local objects are defined only while method containing them is executingLocal objects are defined only while method containing them is executing void is use to specify return type of a method which returns no valuesvoid is use to specify return type of a method which returns no values Value is returned from a method to the call using the return statementValue is returned from a method to the call using the return statement