Chapter 4 Methods - University of North Carolina at Pembroke
Download
Report
Transcript Chapter 4 Methods - University of North Carolina at Pembroke
Chapter 5 Methods
Spring 2013
Motivations
A method is a construct for grouping statements together to perform
a function. Using a method, you can write the code once for
performing the function in a program and reuse it by many other
programs. For example, often you need to find the maximum
between two numbers. Whenever you need this function, you would
have to write the following code:
int result;
if (num1 > num2)
result = num1;
else
result = num2;
If you define this function for finding a
maximum number between any two
numbers in a method, you don’t have to
repeatedly write the same code. You
need to define it just once and reuse it by
any other programs.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
2
Objectives
To define methods, invoke methods, and pass arguments to a method (§5.25.5).
To develop reusable code that is modular, easy-to-read, easy-to-debug, and
easy-to-maintain. (§5.6).
To use method overloading and understand ambiguous overloading (§5.7).
To design and implement overloaded methods (§5.8).
To determine the scope of variables (§5.9).
To know how to use the methods in the Math class (§§5.10-5.11).
To learn the concept of method abstraction (§5.12).
To design and implement methods using stepwise refinement (§5.12).
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
3
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
D efine a m ethod
m o d ifie r
return va lue
type
Invoke a m e thod
m ethod
na m e
form a l
para m eters
int z = max(x, y);
m ethod
header
public static int max(int num1, int num2) {
actua l para m eters
(argum e nts)
int result;
m ethod
bod y
if (num1 > num2)
result = num1;
else
result = num2;
return result;
para m eter list
m ethod
signature
return va lue
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
4
Method Signature
Method signature is the combination of the method name and the
parameter list.
D efine a m ethod
m o d ifie r
return va lue
type
Invoke a m e thod
m ethod
na m e
form a l
para m eters
int z = max(x, y);
m ethod
header
public static int max(int num1, int num2) {
actua l para m eters
(argum e nts)
int result;
m ethod
bod y
if (num1 > num2)
result = num1;
else
result = num2;
return result;
para m eter list
m ethod
signature
return va lue
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
5
Formal Parameters
The variables defined in the method header are known as
formal parameters.
D efine a m ethod
m o d ifie r
return va lue
type
Invoke a m e thod
m ethod
na m e
form a l
para m eters
int z = max(x, y);
m ethod
header
public static int max(int num1, int num2) {
actua l para m eters
(argum e nts)
int result;
m ethod
bod y
if (num1 > num2)
result = num1;
else
result = num2;
return result;
para m eter list
m ethod
signature
return va lue
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
6
Actual Parameters
When a method is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.
D efine a m ethod
m o d ifie r
return va lue
type
Invoke a m e thod
m ethod
na m e
form a l
para m eters
int z = max(x, y);
m ethod
header
public static int max(int num1, int num2) {
actua l para m eters
(argum e nts)
int result;
m ethod
bod y
if (num1 > num2)
result = num1;
else
result = num2;
return result;
para m eter list
m ethod
signature
return va lue
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
7
Actual Parameters and Formal Parameters
Location of actual parameter or argument to formal parameter is important.
•Number of actual parameters must equal number of formal parameters.
•Type of actual parameter must match type of formal parameter.
D efine a m ethod
m o d ifie r
return va lue
type
Invoke a m e thod
m ethod
na m e
form a l
para m eters
int z = max(x, y);
m ethod
header
public static int max(int num1, int num2) {
actua l para m eters
(argum e nts)
int result;
m ethod
bod y
if (num1 > num2)
result = num1;
else
result = num2;
return result;
para m eter list
m ethod
signature
return va lue
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
8
Return Value Type
A method may return a value. The returnValueType is the data type
of the value the method returns. If the method does not return a
value, the returnValueType is the keyword void. For example, the
returnValueType in the main method is void.
D efine a m ethod
m o d ifie r
return va lue
type
Invoke a m e thod
m ethod
na m e
form a l
para m eters
int z = max(x, y);
m ethod
header
public static int max(int num1, int num2) {
actua l para m eters
(argum e nts)
int result;
m ethod
bod y
if (num1 > num2)
result = num1;
else
result = num2;
return result;
para m eter list
m ethod
signature
return va lue
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
9
Example Return Value Types
Return
type int
– public static int max(int a, int b) {
Returns
type integer
– public static double max(int a, int b) {
Returns
type double
– public static void printn(String c) {
not return a value, so no return statement in
this method.
Does
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
10
Method body
The method body is the code executed to produce the results.
D efine a m ethod
m o d ifie r
return va lue
type
Invoke a m e thod
m ethod
na m e
form a l
para m eters
int z = max(x, y);
m ethod
header
public static int max(int num1, int num2) {
actua l para m eters
(argum e nts)
int result;
m ethod
bod y
if (num1 > num2)
result = num1;
else
result = num2;
return result;
para m eter list
m ethod
signature
return va lue
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
11
Modifiers
Identifies how the method is used:
•public: any other program has access to this method
•static: static methods can be called without creating an instance of the class
D efine a m ethod
m o d ifie r
return va lue
type
Invoke a m e thod
m ethod
na m e
form a l
para m eters
int z = max(x, y);
m ethod
header
public static int max(int num1, int num2) {
actua l para m eters
(argum e nts)
int result;
m ethod
bod y
if (num1 > num2)
result = num1;
else
result = num2;
return result;
para m eter list
m ethod
signature
return va lue
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
12
Modifiers
Java
modifiers
– public: all methods have access to the method
– protected: only methods in the same package
have access to the method
– private: only methods in the same class has
access to the method
Java
structure
– Package: contains one or more classes
– Class: contains one or more methods
– Subclass: derived from a class
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
13
Calling Methods
Listing 5.1 Testing the max method
This program demonstrates calling a method max
to return the largest of the int values
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
14
TestMax
public class TestMax {
/** Main method */
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
System.out.println("The maximum between " + i + " and " + j + " is " + k);
}
/** Return the max between two numbers */
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
15
animation
Calling Methods, cont.
pass the value of i
pass the value of j
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
}
public static int max(int num1, int num2 ) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
return result;
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
16
animation
Trace Method Invocation
i is now 5
i
5
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
17
animation
Trace Method Invocation
j is now 2
i
5
j
2
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
18
animation
Trace Method Invocation
invoke max(i, j)
i
5
j
2
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
19
animation
Trace Method Invocation
invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2
i
5
j
2
num1 num2
5
2
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
20
animation
Trace Method Invocation
declare variable result
i
5
j
2
num1 num2 result
5
2
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
21
animation
Trace Method Invocation
(num1 > num2) is true since num1
is 5 and num2 is 2
i
5
j
2
num1 num2 result
5
2
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
22
animation
Trace Method Invocation
result is now 5
i
5
j
2
num1 num2 result
5
2
5
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
23
animation
Trace Method Invocation
return result, which is 5
i
5
j
2
num1 num2 result
5
2
5
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
24
animation
Trace Method Invocation
return max(i, j) and assign the
return value to k
i
5
j
2
k
5
num1 num2 result
5
2
5
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
25
animation
Trace Method Invocation
Execute the print statement
i
5
j
2
k
5
num1, num2, and result no
longer exist
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
26
CAUTION
A return statement is required for a value-returning method. The method shown
below in (a) is logically correct, but it has a compilation error because the Java
compiler thinks it possible that this method does not return any value.
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else if (n < 0)
return –1;
}
(a)
S ho uld be
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else
return –1;
}
(b)
To fix this problem, delete if (n < 0) in (a), so that the compiler will see a
return statement to be reached regardless of how the if statement is
evaluated.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
27
Reuse Methods from Other Classes
NOTE: One of the benefits of methods is for reuse. The max method can
be invoked from any class besides TestMax. If you create a new class
Test, you can invoke the max method using ClassName.methodName
(e.g., TestMax.max).
public class Test {
public static void main(String[] args) {
int a = 4;
int b = 8;
int c = TestMax.max(a,b);
System.out.println("The largest of " + a + " and " + b + " is " + c);
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
28
Call Stacks
Spa c e r equ ir e d for
th e m a x m e th o d
nu m 2 :
nu m 1 :
2
5
Spa c e r equ ir e d for
th e m a x m e th o d
r e su lt: 5
nu m 2 : 2
nu m 1 : 5
Spa c e r equ ir e d for
th e m a in m etho d
k:
2
j:
5
i:
Spa c e r equ ir e d for
th e m a in m etho d
k:
2
j:
5
i:
Spa c e r equ ir e d for
th e m a in m etho d
k:
2
j:
5
i:
(a ) T he m a in
m etho d is inv ok ed .
(b) T h e m a x
m etho d is inv ok ed .
(c) T h e m a x m etho d
is b ein g ex e cu ted .
Spa c e r equ ir e d for
th e m a in m etho d
5
k:
2
j:
5
i:
(d) T h e m a x m etho d is
finish ed a n d th e r etu r n
va lu e is sen t to k .
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
Sta ck is e m p ty
(e) T h e m a in
m etho d is finish ed .
29
animation
Trace Call Stack
i is declared and initialized
i: 5
T h e m ain m eth od
is in vok ed .
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
30
animation
Trace Call Stack
j is declared and initialized
j: 2
i: 5
T h e m ain m eth od
is in vok ed .
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
31
animation
Trace Call Stack
Declare k
S p ace requ ired for th e
m ain m eth od
k:
j: 2
i: 5
T h e m ain m eth od
is in vok ed .
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
32
animation
Trace Call Stack
Invoke max(i, j)
S p ace requ ired for th e
m ain m eth od
k:
j: 2
i: 5
T h e m ain m eth od
is in vok ed .
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
33
animation
Trace Call Stack
pass the values of i and j to num1
and num2
num2: 2
num1: 5
S p ace requ ired for th e
m ain m eth od
k:
j: 2
i: 5
T h e m ax m eth od is
in vok ed.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
34
animation
Trace Call Stack
pass the values of i and j to num1
and num2
resu lt:
num2: 2
num1: 5
S p ace requ ired for th e
m ain m eth od
k:
j: 2
i: 5
T h e m ax m eth od is
in vok ed.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
35
animation
Trace Call Stack
(num1 > num2) is true
resu lt:
num2: 2
num1: 5
S p ace requ ired for th e
m ain m eth od
k:
j: 2
i: 5
T h e m ax m eth od is
in vok ed.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
36
animation
Trace Call Stack
Assign num1 to result
S p ace requ ired for th e
m ax m eth od
resu lt: 5
num2: 2
num1: 5
S p ace requ ired for th e
m ain m eth od
k:
j: 2
i: 5
T h e m ax m eth od is
in vok ed.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
37
animation
Trace Call Stack
Return result and assign it to k
S p ace requ ired for th e
m ax m eth od
resu lt: 5
num2: 2
num1: 5
S p ace requ ired for th e
m ain m eth od
k :5
j: 2
i: 5
T h e m ax m eth od is
in vok ed.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
38
animation
Trace Call Stack
Execute print statement
S p ace requ ired for th e
m ain m eth od
k :5
j: 2
i: 5
T h e m ain m eth od
is in vok ed .
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
39
void Method Example
This type of method does not return a value. The method
performs some actions.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
40
TestVoidMethod
public class TestVoidMethod {
public static void main(String[] args) {
System.out.print("The grade is ");
printGrade(78.5);
}
public static void printGrade(double score) {
if (score >= 90.0) {
System.out.println('A');
}
else if (score >= 80.0) {
System.out.println('B');
}
else if (score >= 70.0) {
System.out.println('C');
}
else if (score >= 60.0) {
System.out.println('D');
}
else {
System.out.println('F');
}
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
41
Passing Parameters
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
Suppose you invoke the method using
nPrintln(“Welcome to Java”, 5);
What is the output?
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
Suppose you invoke the method using
nPrintln(“Computer Science”, 15);
What is the output?
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
42
Pass by Value
• Pass the value of the variable, not the memory
location
• Make changes to value will not change the
value in the original variable
Listing 5.2 Testing Pass by value
This program demonstrates passing values to the
methods.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
43
TestPassByValue
public class TestPassByValue {
/** Main method */
public static void main(String[] args) {
// Declare and initialize variables
int num1 = 1;
int num2 = 2;
System.out.println("Before invoking the swap method, num1 is " + num1 +
" and num2 is " + num2);
// Invoke the swap method to attempt to swap two variables
swap(num1, num2);
System.out.println("After invoking the swap method, num1 is " + num1 +
" and num2 is " + num2);
}
/** Swap two variables */
public static void swap(int n1, int n2) {
System.out.println("\tInside the swap method");
System.out.println("\t\tBefore swapping n1 is " + n1 + " n2 is " + n2);
// Swap n1 with n2
int temp = n1;
n1 = n2;
n2 = temp;
System.out.println("\t\tAfter swapping n1 is " + n1 + " n2 is " + n2);
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
44
Pass by Value, cont.
T h e valu es of n u m 1 an d n u m 2 are
p assed to n 1 an d n 2 . E xecu tin g sw ap
d oes n ot a ffect n u m 1 an d n u m 2 .
S p ace req u ired for th e
sw ap m eth od
tem p :
n2: 2
n1: 1
S p ace req u ired for th e
m ain m eth od
num 2: 2
num 1: 1
T h e m ain m eth od
is in vok ed
S p ace req u ired for th e
m ain m eth od
num 2: 2
num 1: 1
T h e sw ap m eth od
is in vok ed
S p ace req u ired for th e
m ain m eth od
num 2: 2
num 1: 1
T h e sw ap m eth od
is fin ish ed
S tack is em p ty
T h e m ain m eth od
is fin ish ed
After the swap, n2 = 1 and n1 = 2
But the values in num1 and num2
do not change
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
45
Modularizing Code
Methods can be used to reduce redundant coding
and enable code reuse. Methods can also be used to
modularize code and improve the quality of the
program.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
46
GreatestCommonDivisorMethod
import java.util.Scanner;
public class GreatestCommonDivisorMethod {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter first integer: ");
int n1 = input.nextInt();
System.out.print("Enter second integer: ");
int n2 = input.nextInt();
System.out.println("The greatest common divisor for " + n1 + " and " + n2 +
" is " + gcd(n1, n2));
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
47
GreatestCommonDivisorMethod (cont.)
/** Return the gcd of two integers */
public static int gcd(int n1, int n2) {
int gcd = 1;
// Initial gcd is 1
int k = 1;
// Possible gcd
while (k <= n1 && k <= n2) {
if (n1 % k == 0 && n2 % k == 0)
gcd = k;
// Update gcd
k++;
}
return gcd;
// Return gcd
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
48
PrimeNumberMethod
public class PrimeNumberMethod {
public static void main(String[] args) {
final int NUMBER_OF_PRIMES = 50;
// Number of primes to display
final int NUMBER_OF_PRIMES_PER_LINE = 10;
// Display 10 per line
int count = 0;
// Count the number of prime numbers
int number = 2;
// A number to be tested for primeness
System.out.println("The first 50 prime numbers are \n");
// Repeatedly find prime numbers
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
49
PrimeNumberMethod (cont)
while (count < NUMBER_OF_PRIMES) {
// Print the prime number and increase the count
if (isPrime(number)) {
count++;
// Increase the count
if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
// Print the number and advance to the new line
System.out.printf("%-5s\n", number);
}
else
System.out.printf("%-5s", number);
}
// Check if the next number is prime number++;
number++;
}
}
/** Check whether number is prime */
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
50
PrimeNumberMethod (cont)
public static boolean isPrime(int number) {
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) {
// If true, number is not prime
return false;
// number is not a prime
}
}
return true;
// number is prime
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
51
Overloading Methods
Listing 5.3 Overloading the max Method
public static double max(double num1, double
num2) {
if (num1 > num2)
return num1;
else
return num2;
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
52
TestMethodOverload
public class TestMethodOverloading {
/** Main method */
public static void main(String[] args) {
// Invoke the max method with int parameters
System.out.println("The maximum between 3 and 4 is " + max(3, 4));
// Invoke the max method with the double parameters
System.out.println("The maximum between 3.0 and 5.4 is " + max(3.0, 5.4));
// Invoke the max method with three double parameters
System.out.println("The maximum between 3.0, 5.4, and 10.14 is " + max(3.0, 5.4, 10.14));
}
/** Return the max between two int values */
public static int max(int num1, int num2) {
if (num1 > num2)
return num1;
else return num2;
}
/** Find the max between two double values */
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
53
TestMethodOverload (cont)
public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
/** Return the max among three double values */
public static double max(double num1, double num2, double num3) {
return max(max(num1, num2), num3);
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
54
Ambiguous Invocation
Sometimes there may be two or more possible
matches for an invocation of a method, but the
compiler cannot determine the most specific
match. This is referred to as ambiguous
invocation. Ambiguous invocation is a
compilation error.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
55
Ambiguous Invocation
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
}
public static double max(int num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
Compiler cannot
determine if 1 is
an integer or a
double value and
if 2 is an int or
double value.
This will produce
a compile error.
public static double max(double num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
56
Scope of Local Variables
A local variable: a variable defined inside a
method.
Scope: the part of the program where the variable
can be referenced.
The scope of a local variable starts from its
declaration and continues to the end of the block
that contains the variable. A local variable must
be declared before it can be used.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
57
Scope of Local Variables, cont.
You can declare a local variable with the same
name multiple times in different non-nesting blocks
in a method, but you cannot declare a local variable
twice in nested blocks.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
58
Scope of Local Variables, cont.
A variable declared in the initial action part of a for loop header
has its scope in the entire loop. But a variable declared inside a for
loop body has its scope limited in the loop body from its
declaration and to the end of the block that contains the variable.
The scope of i
The scope of j
public static void method1() {
.
.
for (int i = 1; i < 10; i++) {
.
.
int j;
.
.
.
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
59
Scope of Local Variables, cont.
It is fine to declare i in two
non-nesting blocks
public static void method1() {
int x = 1;
int y = 1;
It is wrong to declare in
two nesting blocks
public static void method2()
{
int i = 1;
int sum = 0;
for (int i = 1; i < 10; i++) {
x += i;
}
}
for (int i = 1; i < 10; i++) {
y += i;
}
for (int i = 1; i < 10; i++) {
sum += i;
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
60
Scope of Local Variables, cont.
// Fine with no errors
public static void correctMethod() {
int x = 1;
int y = 1;
// i is declared
for (int i = 1; i < 10; i++) {
x += i;
}
// i is declared again
for (int i = 1; i < 10; i++) {
y += i;
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
61
Scope of Local Variables, cont.
// With no errors
public static void incorrectMethod() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
int x = 0; //this x will go away when for ends
x += i;
}
System.out.println(“X = “ + x);
}
X=1
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
62
Method Abstraction
You can think of the method body as a black box
that contains the detailed implementation for the
method.
O ptio na l argu m e nts
fo r Input
O ptio na l return
va lue
M etho d H ead er
B la ck B o x
M etho d b o d y
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
63
Benefits of Methods
• Write a method once and reuse it anywhere.
• Information hiding. Hide the implementation
from the user.
• Reduce complexity.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
64
The Math Class
Java has predefined classes and methods
– Java API
Definition http://java.sun.com/j2se/1.5.0/docs/api/index.html
Example http://www.java2s.com/Code/JavaAPI/CatalogJavaAPI.htm
– java.lang contains Math class
import java.lang.Math;
Class constants:
– PI
– E
Class methods:
–
–
–
–
Trigonometric Methods
Exponent Methods
Rounding Methods
min, max, abs, and random Methods
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
65
Trigonometric Methods
sin(double a)
cos(double a)
tan(double a)
acos(double a)
asin(double a)
atan(double a)
a is in Radians
To convert degrees to Radians use
Examples:
Math.sin(0) returns 0.0
Math.sin(Math.PI / 6)
returns 0.5
Math.sin(Math.PI / 2)
returns 1.0
Math.cos(0) returns 1.0
Math.cos(Math.PI / 6)
returns 0.866
Math.cos(Math.PI / 2)
returns 0
a = Math.toRadians(degrees)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
66
Exponent Methods
exp(double a)
Returns e raised to the power of a.
log(double a)
Returns the natural logarithm of a.
log10(double a)
Returns the 10-based logarithm of
a.
pow(double a, double b)
Returns a raised to the power of b.
Examples:
Math.exp(1) returns 2.71
Math.log(2.71) returns 1.0
Math.pow(2, 3) returns 8.0
Math.pow(3, 2) returns 9.0
Math.pow(3.5, 2.5) returns
22.91765
Math.sqrt(4) returns 2.0
Math.sqrt(10.5) returns 3.24
sqrt(double a)
Returns the square root of a.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
67
Rounding Methods
double ceil(double x)
x rounded up to its nearest integer. This integer is returned as a double
value.
double floor(double x)
x is rounded down to its nearest integer. This integer is returned as a
double value.
double rint(double x)
x is rounded to its nearest integer. If x is equally close to two integers,
the even one is returned as a double.
int round(float x)
Return (int)Math.floor(x+0.5).
long round(double x)
Return (long)Math.floor(x+0.5).
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
68
Rounding Methods Examples
Math.ceil(2.1) returns 3.0
Math.ceil(2.0) returns 2.0
Math.ceil(-2.0) returns –2.0
Math.ceil(-2.1) returns -2.0
Math.floor(2.1) returns 2.0
Math.floor(2.0) returns 2.0
Math.floor(-2.0) returns –2.0
Math.floor(-2.1) returns -3.0
Math.rint(2.1) returns 2.0
Math.rint(2.0) returns 2.0
Math.rint(-2.0) returns –2.0
Math.rint(-2.1) returns -2.0
Math.rint(2.5) returns 2.0
Math.rint(-2.5) returns -2.0
Math.round(2.6f) returns 3
Math.round(2.0) returns 2
Math.round(-2.0f) returns -2
Math.round(-2.6) returns -3
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
69
min, max, and abs
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).
Examples:
Math.max(2, 3) returns 3
Math.max(2.5, 3) returns
3.0
Math.min(2.5, 3.6) returns
2.5
Math.abs(-2) returns 2
Math.abs(-2.1) returns 2.1
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
70
The random Method
Generates a random double value greater than or equal to 0.0 and less than 1.0 (0
<= Math.random() < 1.0).
Examples:
(int)(Math.random() * 10)
Returns a random integer
between 0 and 9.
50 + (int)(Math.random() * 50)
Returns a random integer
between 50 and 99.
In general,
a + Math.random() * b
Returns a random number between
a and a + b, excluding a + b.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
71
Case Study: Generating Random Characters
Computer programs process numerical data and characters. You
have seen many examples that involve numerical data. It is also
important to understand characters and how to process them.
As introduced in Section 2.9, each character has a unique Unicode
between 0 and FFFF in hexadecimal (65535 in decimal). To
generate a random character is to generate a random integer between
0 and 65535 using the following expression: (note that since 0 <=
Math.random() < 1.0, you have to add 1 to 65535.)
(int)(Math.random() * (65535 + 1))
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
72
Case Study: Generating Random Characters, cont.
Now let us consider how to generate a random
lowercase letter. The Unicode for lowercase letters
are consecutive integers starting from the Unicode
for 'a', then for 'b', 'c', ..., and 'z'. The Unicode for 'a'
is
(int)'a'
So, a random integer between (int)'a' and (int)'z' is
(int)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
73
Case Study: Generating Random Characters, cont.
Now let us consider how to generate a random
lowercase letter. The Unicode for lowercase letters
are consecutive integers starting from the Unicode
for 'a', then for 'b', 'c', ..., and 'z'. The Unicode for 'a'
is
(int)'a'
So, a random integer between (int)'a' and (int)'z' is
(int)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
74
Case Study: Generating Random Characters, cont.
As discussed in Section 2.9.4, all numeric operators
can be applied to the char operands. The char
operand is cast into a number if the other operand
is a number or a character. So, the preceding
expression can be simplified as follows:
'a' + Math.random() * ('z' - 'a' + 1)
So a random lowercase letter is
(char)('a' + Math.random() * ('z' - 'a' + 1))
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
75
Case Study: Generating Random Characters, cont.
To generalize the foregoing discussion, a random character between
any two characters ch1 and ch2 with ch1 < ch2 can be generated as
follows:
(char)(ch1 + Math.random() * (ch2 – ch1 + 1))
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
76
The RandomCharacter Class
// RandomCharacter.java: Generate random characters
public class RandomCharacter {
/** Generate a random character between ch1 and ch2 */
public static char getRandomCharacter(char ch1, char ch2) {
return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
}
/** Generate a random lowercase letter */
public static char getRandomLowerCaseLetter() {
return getRandomCharacter('a', 'z');
}
/** Generate a random uppercase letter */
public static char getRandomUpperCaseLetter() {
return getRandomCharacter('A', 'Z');
}
/** Generate a random digit character */
public static char getRandomDigitCharacter() {
return getRandomCharacter('0', '9');
}
/** Generate a random character */
public static char getRandomCharacter() {
return getRandomCharacter('\u0000', '\uFFFF');
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
77
RandomCharacter.java
public class RandomCharacter {
/** Generate a random character between ch1 and ch2 */
public static char getRandomCharacter(char ch1, char ch2) {
return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
}
/** Generate a random lowercase letter */
public static char getRandomLowerCaseLetter() {
return getRandomCharacter('a', 'z');
}
/** Generate a random uppercase letter */
public static char getRandomUpperCaseLetter() {
return getRandomCharacter('A', 'Z');
}
/** Generate a random digit character */
public static char getRandomDigitCharacter() {
return getRandomCharacter('0', '9');
}
/** Generate a random character */
public static char getRandomCharacter() {
return getRandomCharacter('\u0000', '\uFFFF');
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
78
TestRandomCharacter.java
public class TestRandomCharacter
{
/** Main method */
public static void main(String args[]) {
final int NUMBER_OF_CHARS = 175;
final int CHARS_PER_LINE = 25;
// Print random characters between 'a' and 'z', 25 chars per line
for (int i = 0; i < NUMBER_OF_CHARS; i++) {
char ch = RandomCharacter.getRandomLowerCaseLetter();
if ((i + 1) % CHARS_PER_LINE == 0)
System.out.println(ch);
else System.out.print(ch);
}
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
79
Stepwise Refinement (Optional)
The concept of method abstraction can be applied
to the process of developing programs. When
writing a large program, you can use the “divide
and conquer” strategy, also known as stepwise
refinement, to decompose it into subproblems. The
subproblems can be further decomposed into
smaller, more manageable problems.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
80
PrintCalender Case Study
Let us use the PrintCalendar example to demonstrate the stepwise
refinement approach.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
81
Design Diagram
p rin tC alen d ar
(m ain )
p rin tM on th
read Inp ut
p rin tM on th T itle
p rin tM on th B od y
/** Main method */
public static void main(String[] args) {
//readInput box
getS tartD ay
getM
on thyear
N am e
// Prompt the user
to enter
String yearString = JOptionPane.showInputDialog( "Enter full year (e.g., 2001):");
// Convert string into integer
int year = Integer.parseInt(yearString);
getT otalN u m O fD ays
// Prompt the user to enter month
String monthString = JOptionPane.showInputDialog(
"Enter month in number between 1 and 12:");
// Convert string into integer
getN um O fD aysInM onth
int month = Integer.parseInt(monthString);
//end of readInput box
// Print calendar for the month of the year
printMonth(year, month); //this is a call to printMonth method
isLeap Y ear
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
82
Design Diagram
p rin tC alen d ar
(m ain )
/** A stub for printMonth may look like this */
public static void printMonth(int year, int month) {
System.out.print(month + " " + year);
}
p rin tM on th
read Inp ut
p rin tM on th T itle
p rin tM on th B od y
/** A stub for printMonthTitle
getM may
on thlook
N amlike
e this */
public static void printMonthTitle(int year, int month) {
}
getS tartD ay
getT otalN u m O fD ays
getN um O fD aysInM onth
isLeap Y ear
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
83
Design Diagram
p rin tC alen d ar
(m ain )
p rin tM on th
read Inp ut
p rin tM on th T itle
getM on th N am e
/** A stub for getMonthName may look like this */
public static String getMonthName(int month) {
p rin tM on th B od y
getS tartD ay
getT otalN u m O fD ays
return "January"; // a dummy value
getN um O fD aysInM onth
}
isLeap Y ear
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
84
Design Diagram
p rin tC alen d ar
(m ain )
p rin tM on th
read Inp ut
p rin tM on th T itle
p rin tM on th B od y
getS tartD ay
getM on th N am e
/** A stub for getStartDay may getT
look like
this u*/m O fD ays
otalN
public static int getStartDay(int year, int month) {
return 1; // a dummy value
}
getN um O fD aysInM onth
/** A stub for getNumberOfDaysInMonth may look like this */
public static int getNumberOfDaysInMonth(int year, int month) {
isLeap Y ear
return 31; // a dummy value
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
85
Design Diagram
p rin tC alen d ar
(m ain )
p rin tM on th
read Inp ut
p rin tM on th T itle
getM on th N am e
p rin tM on th B od y
getS tartD ay
getT otalN u m O fD ays
/** A stub for getTotalNumberOfDays may look like this */
public static int getTotalNumberOfDays(int year, int month) {
getN um O fD aysInM onth
return 10000; // a dummy value
}
isLeap Y ear
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
86
Design Diagram
p rin tC alen d ar
(m ain )
p rin tM on th
read Inp ut
p rin tM on th T itle
getM on th N am e
p rin tM on th B od y
getS tartD ay
getT otalN u m O fD ays
getN um O fD aysInM onth
/** A stub for isLeapYear may look like this */
public static boolean isLeapYear(int year) {
return true; // a dummy value
}
isLeap Y ear
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
87
Implementation: Top-Down
Top-down approach is to implement one method in the
structure chart at a time from the top to the bottom. Stubs
can be used for the methods waiting to be implemented. A
stub is a simple but incomplete version of a method. The
use of stubs enables you to test invoking the method from
a caller. Implement the main method first and then use a
stub for the printMonth method. For example, let
printMonth display the year and the month in the stub.
Thus, your program may begin like this:
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
88
Skeleton for PrintCalendar
// PrintCalendar.java: Print a calendar for a given month in a year
import javax.swing.*;
public class PrintCalendar {
/** Main method */
public static void main(String[] args) {
//readInput box
// Prompt the user to enter year
String yearString = JOptionPane.showInputDialog( "Enter full year (e.g., 2001):");
// Convert string into integer
int year = Integer.parseInt(yearString);
// Prompt the user to enter month
String monthString = JOptionPane.showInputDialog(
"Enter month in number between 1 and 12:");
// Convert string into integer
int month = Integer.parseInt(monthString);
//end of readInput box
// Print calendar for the month of the year
printMonth(year, month); //this is a call to printMonth method
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
89
Skeleton for PrintCalendar cont.
/** A stub for printMonth may look like this */
public static void printMonth(int year, int month) {
System.out.print(month + " " + year);
}
/** A stub for printMonthTitle may look like this */
public static void printMonthTitle(int year, int month) {
}
/** A stub for getMonthName may look like this */
public static String getMonthName(int month) {
return "January"; // a dummy value
}
/** A stub for getStartDay may look like this */
public static int getStartDay(int year, int month) {
return 1; // a dummy value
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
90
Skeleton for PrintCalendar cont.
/** A stub for getNumberOfDaysInMonth may look like this */
public static int getNumberOfDaysInMonth(int year, int month) {
return 31; // a dummy value
}
/** A stub for getTotalNumberOfDays may look like this */
public static int getTotalNumberOfDays(int year, int month) {
return 10000; // a dummy value
}
/** A stub for isLeapYear may look like this */
public static boolean isLeapYear(int year) {
return true; // a dummy value
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
91
Implementation: Bottom-Up
Bottom-up approach is to implement one method in the
structure chart at a time from the bottom to the top. For
each method implemented, write a test program to test it.
Both top-down and bottom-up methods are fine. Both
approaches implement the methods incrementally and
help to isolate programming errors and makes debugging
easy. Sometimes, they can be used together.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
92
PrintCalendar.java
import java.util.Scanner;
public class PrintCalendar {
/** Main method */
public static void main(String[] args) {
// Prompt the user to enter year
Scanner input = new Scanner(System.in);
// Prompt the user to enter year
System.out.print("Enter full year (e.g., 2001): ");
int year = input.nextInt();
// Prompt the user to enter month
System.out.print("Enter month in number between 1 and 12: ");
int month = input.nextInt();
// Print calendar for the month of the year
printMonth(year, month);
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
93
PrintCalendar.java
/** Print the calendar for a month in a year */
static void printMonth(int year, int month) {
// Print the headings of the calendar
printMonthTitle(year, month);
// Print the body of the calendar
printMonthBody(year, month);
}
/** Print the month title, e.g., 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");
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
94
PrintCalendar.java
/** Get the English name for the month */
static String getMonthName(int month) {
String monthName = null;
switch (month) {
case 1: monthName = "January"; break;
case 2: monthName = "February"; break;
case 3: monthName = "March"; break;
case 4: monthName = "April"; break;
case 5: monthName = "May"; break;
case 6: monthName = "June"; break;
case 7: monthName = "July"; break;
case 8: monthName = "August"; break;
case 9: monthName = "September"; break;
case 10: monthName = "October"; break;
case 11: monthName = "November"; break;
case 12: monthName = "December";
}
return monthName;
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
95
PrintCalendar.java
/** Print month body */
static void printMonthBody(int year, int month) {
// Get start day of the week for the first date in the month
int startDay = getStartDay(year, month);
// Get number of days in the month
int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month);
// Pad space before the first day of the month
int i = 0; for (i = 0; i < startDay; i++)
System.out.print(“ “);
for (i = 1; i <= numberOfDaysInMonth; i++) {
if (i < 10)
System.out.print(“ “ + i);
else
System.out.print(“ “ + i);
if ((i + startDay) % 7 == 0)
System.out.println();
}
System.out.println();
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
96
PrintCalendar.java
/** Get the start day of month/1/year */
static int getStartDay(int year, int month) {
final int START_DAY_FOR_JAN_1_1800 = 3;
// Get total number of days from 1/1/1800 to month/1/year
int totalNumberOfDays = getTotalNumberOfDays(year, month);
// Return the start day for month/1/year
return (totalNumberOfDays + START_DAY_FOR_JAN_1_1800) % 7;
}
/** Get the total number of days since January 1, 1800 */
static int getTotalNumberOfDays(int year, int month) {
int total = 0;
// Get the total days from 1800 to 1/1/year
for (int i = 1800; i < year; i++)
if (isLeapYear(i))
total = total + 366;
else
total = total + 365;
// Add days from Jan to the month prior to the calendar month
for (int i = 1; i < month; i++)
total = total + getNumberOfDaysInMonth(year, i);
return total;
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
97
PrintCalendar.java
/** Get the number of days in a month */
static int getNumberOfDaysInMonth(int year, int month) {
if (month == 1 || month == 3 || month == 5 || month == 7
|| month == 8 || month == 10 || month == 12)
return 31;
if (month == 4 || month == 6 || month == 9 || month == 11)
return 30;
if (month == 2)
return isLeapYear(year) ? 29 : 28;
return 0; // If month is incorrect
}
/** Determine if it is a leap year */
static boolean isLeapYear(int year) {
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights
reserved. 0132130807
98