Chapter 4: Methods
Chapter 4: Methods
) IntroducingMethods
) Declaring Methods
) Calling Methods
) Passing Parameters
) Pass by Value
) Overloading Methods
) Method Abstraction
) The Math Class
) Recursion (Optional)
Introducing Methods
Method Structure
A method is a modifier methodName
to perform an body
i f (num1 > num2)
resul t = num1;
operation. el se
resul t = num2;
Method Signature
Method body
Black Box
The Math Class
) Class constants:
PI
E
) 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.
Miscellaneous Methods
) 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 random double value
in the range [0.0, 1.0).
Using Math Methods
Example 4.4 Computing Mean and Standard
Deviation
Generate 10 random numbers and compute
the mean and standard deviation
n n
x i i mean
x 2
mean = i =1
deviation = i =1
n n 1
// ComputeMeanDeviation.java: Demonstrate using the math methods
public class ComputeMeanDeviation
{
// Main method
public static void main(String[] args)
{
int number = 0; // Store a random number
double sum = 0; // Store the sum of the numbers
double squareSum = 0; // Store the sum of the squares
// Display result
System.out.println("The mean is " + mean);
System.out.println("The standard deviation is " + deviation);
}
}
Case Studies
readInput printMonth
isLeapYear
// PrintCalendar.java: Print a calendar for a given month in a year
public class PrintCalendar
{
// Main method
public static void main(String[] args)
{
// The user enters year and month
System.out.print("Enter full year: ");
int year = MyInput.readInt();
System.out.print("Enter month in number between 1 and 12: ");
int month = MyInput.readInt();
// Print headings
printMonthTitle(year, month);
// Print body
printMonthBody(startDay, numOfDaysInMonth);
}
// Get the start day of the first day in a month
static int getStartDay(int year, int month)
{
// Get total number of days since 1/1/1800
int startDay1800 = 3;
long totalNumOfDays = getTotalNumOfDays(year, month);
// Add days from Jan to the month prior to the calendar month
for (int i = 1; i < month; i++)
total = total + getNumOfDaysInMonth(year, i);
return total;
}
// Get the number of days in a month
static int getNumOfDaysInMonth(int year, int month)
{
if (month == 1 || month==3 || month == 5 || month == 7 ||
month == 8 || month == 10 || month == 12)
return 31;
if (month == 2)
if (isLeapYear(year))
return 29;
else
return 28;
return 0; // If month is incorrect.
}
// Determine if it is a leap year
static boolean isLeapYear(int year)
{
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))
return true;
return false;
}
if ((i + startDay) % 7 == 0)
System.out.println();
}
System.out.println();
}
// Print the month title, i.e. May, 1999
static void printMonthTitle(int year, int month)
{
System.out.println(" "+getMonthName(month)+", "+year);
System.out.println("-----------------------------");
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
}
return monthName;
}
}
Recursion (Optional)
Example 4.6 Computing Factorial
0!=1
1!=1
2!=2x1!=1
3!=3x2x1=6
4!=4x3!=4x3x2x1=24
N!=Nx(N-1)!=Nx(N-1)x(N-2)!=Nx(N-1)x(N-2)2x1
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
// ComputeFactorial.java: Compute factorial of an integer
public class ComputeFactorial
{
public static void main(String[] args)
{
// Prompt the user to enter an integer
System.out.println("Please enter a nonnegative integer");
int n = MyInput.readInt();