1.21k likes | 1.26k Vues
Learn about creating and using methods in Java programming, including passing parameters, returning values, and method overloading. Discover the benefits of methods and how they contribute to program organization and complexity reduction. Examples demonstrate basic arithmetic operations and complex calculations.
E N D
Programming Logic and DesignFifth Edition, Comprehensive Chapter 7 Using Methods
Objectives • Use a simple method with local variables & constants • Create a method that requires a single parameter • Create a method that requires multiple parameters • Create a method that returns a value • Pass an array to a method Programming Logic and Design, Fifth Edition, Comprehensive
Objectives (continued) • Create Overloaded methods • Learn how to avoid ambiguous methods (methods that have the same signature because the compiler cannot determine which method to use) See p. 316 • Use prewritten, built-in methods such as: • rootNum = Math.sqrt (36); // In Java • newNum = Math.pow (2, 10); // In Java • rand = Math.random( ); // In Java Programming Logic and Design, Fifth Edition, Comprehensive
Benefits of Methods • You can write a method once and reuse it many times in a program. • Methods reduce the complexity of a program. • Methods support “Information hiding” -- • Hides the details & implementation from the user. • The user does not care how the SquareRoot method works; he just wants a correct answer Programming Logic and Design, Fifth Edition, Comprehensive
Review of Simple Methods • Method: A programming module that contains a series of statements to perform a task • Can invoke a method from another program or method • Program can contain unlimited number of methods • Method can be called unlimited number of times • A Method must include these attributes: • Header • Body • Return statement Programming Logic and Design, Fifth Edition, Comprehensive
Review of Simple Methods (continued) • Simple methods require no arguments and send no return values • Variables are in scope (local) to the method in which they are declared • Two or more methods may access the same data • Methods can pass data from one method to another Programming Logic and Design, Fifth Edition, Comprehensive
Simple Methods (as in Java) public static double sumNumbers ( double n1, double n2) { double result; result = n1 + n2; System.out.println( “Sum of ” + n1 + “ & ”+ n2 “ : ” + result); return result; } // Return result to calling method public static double subNumbers ( double n1, double n2) { double result; result = n1 - n2; System.out.println( “Diff of ” + n1 + “ & ” + n2, “: ” + result); return result; } // Return result to calling method
Simple Methods (as in Java) public static double multumbers ( double n1, double n2) { double result; result = n1 * n2; System.out.println( “Product of ” + n1 + “ * ”+ n2 “ : ” + result); return result; } // Return result to calling method public static double divNumbers ( double n1, double n2) { double result = 0; if (n2 != 0) result = n1 / n2; System.out.println( “Quotient of ” + n1 + “ / ” + n2, “: ” + result); return result; } // Return result to calling method
Examples: Methods double areaCircle (double radius) { double area; double pi = 3.14159; area = radius * radius * pi; return area; } Programming Logic and Design, Fifth Edition, Comprehensive
Examples: Methods double areaRectangle (double length, double width) { double area; area = length * width; return area; } double perimeterRectangle (double length, double width) { double perimeter; perimeter = 2 * (length + width); return perimeter; } Programming Logic and Design, Fifth Edition, Comprehensive
Examples: Methods double volumeSphere (double radius) { double volume; volume = (4./3.) * pi * radius * radius * radius; return volume; } Programming Logic and Design, Fifth Edition, Comprehensive
Examples: Methods double calcInterest (double amt, double, rate, int yrs) { double newBal, interest; newBal = amt; for (int i = 0; i < yrs; i++) newBal = newBal * (1 + rate); interest = newBal - amt; return interest; // Return interest amt to calling method } Programming Logic and Design, Fifth Edition, Comprehensive
Using Methods in Java public class ComputeLetterGrade { // Java main method public static void main (String[ ] args) { float s1 = 70.0; float s2 = 80.0; float s3 = 95.0; float avg = computeAvergage(s1, s2, s3); char grade = letterGrade(avg); System.out.println(“Average = “ + avg + “ Grade = “ + grade); } // End of main method public static float computeAverage(float s1, float s2, float s3) { float average = (s1 + s2 + s3 ) /3.0; return (average); } } // End of class ComputeLetterGrade
Using Methods in Java public static char letterGrade(float score) { if(score >= 90) return ('A'); else if(score >= 80) return ('B'); else if(score >= 70) return ('C'); else if(score >= 60) return ('D'); else return ('F'); } // End of method letterGrade
Using Methods in Java public static void computeBMI(double weight, double height) { final double KILOGRAMS_PER_POUND = 0.45359237; // Constant final double METERS_PER_INCH = 0.0254; // Constant // Compute BMI double bmi = weight * KILOGRAMS_PER_POUND / ((height * METERS_PER_INCH) * (height * METERS_PER_INCH)); // Display result System.out.println("Your BMI is " + bmi); if (bmi < 16) System.out.println("You are seriously under weight: Eat more!"); else if (bmi < 18) System.out.println("You are under weight: Eat a little more!"); else if (bmi < 24) System.out.println("You are normal weight"); else if (bmi < 29) System.out.println("You are over weight: Start a diet"); else if (bmi < 35) System.out.println("You are seriously over weight: Start a diet !"); else System.out.println("You are deathly & gravely over weight: See a doctor"); } // End of computeBMI method
Creating Methods That Require a Single Parameter • Some methods require outside information. • Parameters: communications received by a method • Argument: value in parentheses when calling a method • Implementation hiding: Encapsulation of method details means that: • Program does NOT need to know how method works internally • Interface to the method is the only part of the method the client program sees Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-3 Moon weight program that passes an argument to a method Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-3 Moon weight program that passes an argument to a method (continued) Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-4 Typical execution of moon weight program in Figure 7-3 Programming Logic and Design, Fifth Edition, Comprehensive
Creating Methods That Require a Single Parameter (continued) • Method declaration must include • Type of the parameter • Local name for the parameter • Parameters in parentheses hold values that are “dropped in” to the method • Variable declared in method header is a local variable • Goes out of scope when method ends • Variables passed to a method are passed by value • Copy of the value sent to the method • Stored in a new memory location Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-5 Alternate version of the moon weight program in which the programmer uses the same identifier for two variables Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-5 Alternate version of the moon weight program in which the programmer uses the same identifier for two variables (continued) Programming Logic and Design, Fifth Edition, Comprehensive
Creating Methods That Require Multiple Parameters • Method can require more than one parameter • List data types and local identifiers in method header • Parameters are separated by commas in the header • Any number of parameters in any order • When calling a method, arguments must match in order and in type Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-6 A program that calls a computeTax() method that requires two parameters Programming Logic and Design, Fifth Edition, Comprehensive
Creating Methods That Return Values • Variables declared within a method go out of scope when method ends • Retain a value that exists in a method, return the value from the method • Methods that return a value must have a return type • Return type can be any data type • Void method returns nothing Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-7 A payroll program that calls a method that returns a value Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-8 A program that uses a method’s returned value without storing it Programming Logic and Design, Fifth Edition, Comprehensive
Creating Methods That Return Values (continued) • Method’s return type is known as the method’s type • Value in a return statement sent from called method to calling method • Method’s type must match return type • Most programming languages allow multiple return statements Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-9 Unrecommended approach to returning one of several values Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-10 Recommended approach to returning one of several values Programming Logic and Design, Fifth Edition, Comprehensive
Passing an Array to a Method • Array: is a list of elements int [ ] number =new int[10]; • Single element used in same manner as single variable of the same type • Single array element passed by value • A copy of the array element passed to the method • Entire array is passed by reference (address) • Method receives memory address of the array • Accesses values in array elements • Changes to array elements within the method are permanent and are reflected that way outside the method. Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-11PassArrayElement program Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-11PassArrayElement program (continued) Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-12 Output of PassArrayElement program Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-13PassEntireArray program Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-13PassEntireArray program (continued) Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-13PassEntireArray program (continued) Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-14 Output of PassEntireArray program Programming Logic and Design, Fifth Edition, Comprehensive
Overloading Methods • Overloading: supplying diverse meanings for a single identifier • Examples: • Overloaded English words: • “break a window” • “break bread” • “break an egg” • “break some ground” • Operators such as + • Overload a method: write multiple methods with the same name, but different parameter lists Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-15 The printBill() method with a numeric parameter Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-16 The printBill() method with two numeric parameters Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-17 The printBill() method with a numeric parameter and a string parameter Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-18 The printBill() method with two numeric parameters and a string parameter Programming Logic and Design, Fifth Edition, Comprehensive
Overloading Methods (continued) • More natural for methods’ clients to use single method name for similar tasks • Overloading never required • Could create multiple methods with unique identifiers • Overloading methods does not reduce the work of programming • Advantage: one appropriate name for all related tasks Programming Logic and Design, Fifth Edition, Comprehensive
Overloaded Methods (Java) public static int maxMethod( int x, int y) { int largest = 0; if( x > y) largest = x; else largest = y; return largest; } Programming Logic and Design, Fifth Edition, Comprehensive
Overloaded Methods (Java) public static float maxMethod( float x, float y) { float largest = 0.0f; if( x > y) largest = x; else largest = y; return largest; } Programming Logic and Design, Fifth Edition, Comprehensive
Overloaded Methods (Java) public static double maxMethod( double x, double y) { double largest = 0.0d; if( x > y) largest = x; else largest = y; return largest; } Programming Logic and Design, Fifth Edition, Comprehensive
Avoiding Ambiguous Methods • When overloading a method, you risk creating ambiguous methods • If compiler cannot determine which method to use, it generates an error message • Methods may be valid individually, but not valid when together in the same program • Need to provide different parameter lists for methods with the same name (overloading) • Illegal methods have identical names and identical parameter lists Programming Logic and Design, Fifth Edition, Comprehensive
Ambiguous Methods in JavaJava compiler gets confused ! public static double max(int num1, double num2) { if (num1 > num2) return num1; else return num2; } public static double max(double num1, int num2) { if (num1 > num2) return num1; else return num2; } } Programming Logic and Design, Fifth Edition, Comprehensive
Figure 7-19 Program that contains ambiguous method call Programming Logic and Design, Fifth Edition, Comprehensive