04slide
TRANSCRIPT
Chapter 5 Methods Introducing Methods Declaring Methods
Calling Methods
Passing Parameters
Pass by Value
Overloading Methods
Method Abstraction
local variable, global variable
The Math Class (library functions)
Java Documentation
Introducing Methods
Method StructureA method is a collection of statements that are grouped together to perform an operation.
public static int max(int num1, int num2){
int result = 0;
if (num1 > num2) result = num1;else result = num2;
return result;}
modifier
returnValueType
methodName
parameters
return value
methodbody
methodheading
Declaring Methods
public static int max(int num1, int num2)
{ if (num1 > num2) return num1; else return num2;}
Calling Methods
Example 4.1 Testing the max method
This program demonstrates calling a method max to return the largest of the int values
TestMaxTestMax Run
Passing ParametersYou pass arguments to the corresponding
parameters in the method signatureFor e.g:
void nPrintln(String message, int n){ for (int i=0; i<n; i++) System.out.println(message);}
To call the above method:nPrintln(m, i); //where m is String and i is int
message and n are parametersm and i are arguments
Pass by ValuePass by value: the parameter is allocated the required memory storage and the value of the argument is copied to the parameter. There are 2 separate copies of the same values.
Example 4.2 Testing Pass by value
This program demonstrates passing values to the methods.
TestPassByValueTestPassByValue Run
Overloading MethodsMethods defined with the same name are overloaded. The
parameter lists are different, the return type is not relevant.
Example 4.3 Overloading the max Methoddouble max(double num1, double num2) { if (num1 > num2) return num1; else return num2;}
TestMethodOverloadingTestMethodOverloading Run
The scope of variables
Local variable
Global variable
Scope of variable
Method Abstraction
You can think of the method body as a black box that contains the detailed implementation for the method.
Method Signature
Method body
Black Box
Optional Input Optional returnvalue
The Math Class
Class constants:– PI– E (the base of natural logarithms)
Class methods: – Trigonometric Methods – Exponent Methods– Miscellaneous
Trigonometric Methods sin(double a)
cos(double a)
tan(double a)
acos(double a)
asin(double a)
atan(double a)
Exponent Methods exp(double a)
Returns e raised to the power of a.
log(double a)
Returns the natural logarithm of a.
pow(double a, double b)
Returns a raised to the power of b.
sqrt(double a)
Returns the square root of a.
Rounding Methods double ceil(double x)
Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.
double floor(double x) Returns the largest (closest to positive infinity) double value that is
less than or equal to the argument and is equal to a mathematical integer.
double rint(double x)Returns the double value that is closest in value to the argument and is
equal to a mathematical integer. int round(float x)
Returns the closest int to the argument. Long round(double x)
Returns the closest long to the argument.
min, max, abs, and random max(a, b)and min(a, b)
Returns the maximum or minimum of two parameters.
abs(a)Returns the absolute value of the parameter.
random()Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returns a random double value in the range [0.0, 1.0).
Java Documentation
http://java.sun.com/javase/6/docs/api/
Using Math Methods
Example 4.4 Computing Mean and Standard Deviation
Generate 10 random numbers and compute the mean and standard deviation
ComputeMeanDeviationComputeMeanDeviation Run
n
xmean
n
ii
1
1
)(
1
2
12
nn
xx
deviation
n
i
n
ii
i
Case Studies
Example 4.5 Displaying Calendars
The program reads in the month and year and displays the calendar for a given month of the year.
PrintCalendarPrintCalendar Run
Design DiagramprintCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumberOfDays
getNumberOfDaysInMonth
isLeapYear
Recursion
E.g. 4.6 Factorial
Factorial(0)=1; Factorial(n)=n*factorial(n-1)
Recursion
E.g. 4.7 fibonacci numbers
Fib(0)=1; Fib(1)=1; Fib(n)=Fib(n-2)+Fib(n-1), n>=2
Recursion
E.g. 4.8 Towers of Hanoi 3 Poles and n disks
– Move n disks from pole A to pole B.
– One disk can be moved at any time
– Big disk can’t placed on top of small disk
Recursion
Towers of Hanoi Solution
– If n=1, move disk 1 from A to B
– Else Move n-1 disks from A to C, B as temporary Move disk n from A to B Move n-1 disks from C to B, A as temporary