Transcript Unit 7

Introduction to Programming
G50PRO
University of Nottingham
Unit 7 : Methods
Paul Tennent
http://paultennent.wordpress.com/G50PRO.html
[email protected]
Room C7
Methods
1.
Most problems naturally break down into sub-problems.
2.
Large problems must be implemented by a team, not an
individual.
3.
Reusability of the parts, is highly appreciated
 For the program itself
 For other programs
Defining Methods

The only required elements of a method
declaration are:




the method's return type
the method's Name
a pair of parentheses, ( )
a body between braces, { }
Return_type methodName(optional_parameters) {
//method Body here
}
Method declarations
components
1.
Modifiers, such as public, private, and others you will learn about
later.
2.
return type, the data type of the value returned by the method, or
void if the method does not return a value.
3.
Method name
4.
The parameter list in parenthesis. a comma-delimited list of input
parameters, preceded by their data types, enclosed by parentheses,
().
5.
An exception list (more details later)
6.
The method body, enclosed between braces—the method's code,
including the declaration of local variables.
Naming a Method




a method name can be any legal identifier
By convention, method names should be a verb in
lowercase or a multi-word name that begins with a
verb
In multi-word names, the first letter of each of the
second and following words should be capitalized
Examples:




addNumbers
moveShape
isFound
print
Examples of method
declarations
class Count {
public static void count(int maxNum){
int count=0;
do{
System.out.println("Count is: " + count);
count++;
} while (count < maxNum)
}//count method end
}//class end

This code will do nothing so far, we defined
the method, However, we must have a call
statement to execute it
Method Call
class Count {
public static void count(int maxNum){
int count=0;
do{
System.out.println("Count is: " + count);
count++;
} while (count < maxNum)
}//count method end
public static void main(String[] args){
count(10);
}//main end
}//class end

For now, all methods we use have to be
static (more on that latter)
Method Flow of Control


The main method is invoked by the system
when you run your program
Each method call returns to the place that
called it
main
method1
Method2();
method1();
method2
The method definition

we need to identify each of the parameters (if needed), so that
we can refer to them and use them from within the code which
forms the body of the method.

it is conventional to declare any local variables at the start of the
body (apart from loop variables). a new copy of them is created
every time a method is called (invoked).

The rest of the body of the method is dedicated to implementing
the logic of the method so that it performs the job we want it to.
This can include any java legal statements.

At any point we can exit the method using a return statement
Example

Read a list of numbers from the user and
print only the highest number.

Method needed:



readNumbers
findMax
printMax
printMax
public static void printMax(int max){
System.out.println("The maximum value entered was " + max);
}//printMax end
findMax
public static int findMax(int num1, int num2) {
int max=0;
if(num1>num2){
max=num1;
} else{
max=num2;
}
return max;
}
readNumber
public static int readNumber() {
count++;
System.out.println("Enter number " + count + ": ");
Scanner scan = new Scanner(System.in);
return (Scan.nextInt());
}
Max Program
public class Max {
static int count=0;
………………………..//methods here
public static void main(String[] args){
int number=0;
int max=0;
while(number!=-1) {
number = readNumber();
max = findMax(max,number);
}
printMax(max);
}
}
Example 2

Write a program to print the Mean Value of a
set of numbers entered by the user

We can Reuse readNumber Method

Other Method needed:


clacMean
printMean
readNumber
public static int readNumber() {
count++;
System.out.println("Enter number " + count + ": ");
Scanner scan = new Scanner(System.in);
return (Scan.nextInt());
}
calcMean
public static int clacMean(int total, int count) {
return total/count;
}
printMean
public static void printMean(int mean){
System.out.println("The mean value is " + mean);
}//printMean end
Mean Program
public class Mean {
static int count=0;
static final int COUNTMAX=5;
……….//methods here
public static void main(String[] args){
int total=0;
int mean=0;
do{
total+= readNumber();
}while(count<COUNTMAX);
mean = clacMean(total, count);
printMean(mean );
}
}
Method Local variables

Visibility: Only in defining method
No code outside a method can see the local variables inside
another method.

Lifetime: From method call to method return
Local variables are created on the call stack when the method is
entered, and destroyed when the method is exited. You can't
save values in local variables between calls. For that you have to
use instance variables, which you'll learn about a little later.

Initial value: None
Local variables don't have initial values by default -- you can't try
to use their value until you assign a value. It's therefore common
to assignment a value to them when they're declared.
Method Local variables

Parameters are pre-initialized local
variables
Method parameters are basically
implemented as local variables.
They have the same visibility and lifetime.
Recursion

Simply, recursion is when a function calls itself.

The arguments passed to the recursion take us closer to the
solution with each call

The key to thinking recursively is to see the solution to the
problem as a smaller version of the same problem

Every recursion should have the following characteristics.
 A simple base case which we have a solution for and a return
value.

A way of getting our problem closer to the base case.

A recursive call which passes the simpler problem back into the
method.
Factorial
class Factorial {
int fact(int n) {
int result;
if ( n ==1) return 1; //stop condition
result = fact (n-1) * n;
return result;
}
}

Assume we call the fact method with value 5

fact(5);
Tracing Factorial
5
4
n=1
result= 1
n=1
result= 1
n=2
result= ?
n=2
result= 2
6
if ( n ==1) return 1;
//base case
Return 1
7
Return 2
3
n=3
result= ?
n=3
result=6
8
Return 6
2
1
n=4
result=?
n=4
result=24
n=5
result=?
n=5
result=120
9
Return 24
10
Return 120
result = fact (n-1) * n;
//recursive call
Tracing Factorial
5
4
n=1
result= 1
n=1
result= 1
n=2
result= ?
n=2
result= 2
6
Return 1
7
Return 2
3
n=3
result= ?
n=3
result=6
8
Return 6
fact (n-1)
2
n=4
result=?
n=4
result=24
9
Return 24
1
n=5
result=?
n=5
result=120
10
Return 120
result = methodReturn * n;
Summary





Defining Methods
Method declarations
Naming a Method
Method Call
Recursion