29
Methods

Draft timetable has the same times as this semester: - ◦ Monday 9:00 am to 12:00 noon, 1:00 pm to 3:00 pm. ◦ Tuesday 9:00 am to 12:00 noon, 1:00 pm

Embed Size (px)

Citation preview

Methods

Draft timetable has the same times as this semester: -◦ Monday 9:00 am to 12:00 noon, 1:00 pm to 3:00 pm.◦ Tuesday 9:00 am to 12:00 noon, 1:00 pm to 3:00 pm.◦ Thursday 9:00 am to 12:00 noon, 1:00 pm to 3:00 pm.

Not necessarily lectures in the afternoons.◦ Some modules have lectures during the morning and

workshops/tutorials in the afternoons. Module classes are mostly on the same day (but

not always). It depends on which modules that you are

taking.

Semester 2

To be able write larger programs◦ By breaking them down into smaller parts and

passing data between the parts.

To understand the concepts of Methods◦ To be able to write programs that use Methods

from Library classes.◦ To be able to write Methods for use in your

programs.◦ To develop an active understanding of the

different kinds of method and their uses

Lecture Outcomes

We have looked at developing algorithms for solving problems.

We saw how the problem could be broken down into separate stages, then each stage was further broken down into more detailed steps.◦ We repeat this process until we have single

instructions. This is Stepwise Refinement. We can regard the first level stages as separate

(smaller) programs.◦ Similarly, we can regard any group of (related) single

instructions as a small program.

Stepwise Refinement

5

Example – making a cup of tea

1. Put leaves in the pot2. Boil some water

3. Add water to the pot4. Wait 5 minutes

5. Pour tea into cup

We are programming a robot to make a cup of tea using tea leaves and a tea pot. This can take several steps: -

6

1. Put leaves in the pot

2. Boil some water

3. Add water to the pot

1.1. Open tea caddy

1.2. Scoop out a spoonful of tea1.3. Tip the spoon into the pot1.4. Close tea caddy

2.1. Fill kettle with water

2.2. Switch on the kettle

2.3. Wait until water is boiled2.4. Switch off kettle

Many of the steps can be broken down into smaller steps.

7

1. Put leaves in the pot

2. Boil some water

1.1. Open tea caddy

1.2. Scoop out a spoonful of tea1.3. Tip the spoon into the pot1.4. Close tea caddy

1.1.1. Take caddy from cupboard1.1.2. Remove lid from caddy

1.4.1. Put lid on caddy

1.4.2. Return caddy to cupboard

2.1. Fill kettle with water

2.1. Take kettle to the water tap

The small programs (or SubPrograms) described are known as Methods.

The main program making tea then becomes a series of smaller SubPrograms or Methods.

Methods

Making Tea

1. Put leaves in pot

2. Boil some water

3. Add water to pot

4. Wait

5. Pour tea into cup

Methods

In the tea-making example, each method would most likely just involve a fixed-movement by the robot. Even if sensors were required, this could all be dealt with inside the method.

Methods of this kind, which ◦ do not need any data, and◦ do not give us any results

are just one of four main types…

Types of method

Four Types of Method exist:1. Those which ‘do something’ but don’t require any

data from the main program and which don’t return any data to the main program (no data in or out).

2. Those which ‘do something’ where the ‘something’ depends on data supplied by the main program but don’t return any data to the main program (data in).

3. Those which ‘do something’ and then do return resulting data to the main program (data out).

4. A combination of the last 2 – Require data from the main program and return data back to the main program (data in and out).

Method Types

No data in, no data out◦ e.g. the methods for the tea-making robot

Data in, no data out◦ e.g. telling the robot to move a certain distance:

robot.moveForward(50)

No data in, data out◦ e.g. getting information from the computer’s operating system:

int t = currentTimeMillis() // t would contain the current time in milliseconds after this code is run

Data in, data out◦ e.g. a method to square a given number:

int result = square(3); // result would contain 9 after this code is run

Types of method (summary)

You may not have realised it at the time but you have already used some methods…

◦ main () belongs to the class in which it is declared.

◦ println () belongs to the System.out class

◦ showInputDialog () belongs to the JOptionPane class

◦ parseDouble () belongs to the Double class

Methods You have already used

The data passed into a method when it is called are known as parameters

If the method gives us some data back, this is known as the return value

Parameters and Return Values

A Method may require more than one Input parameter◦ or none at all

A Method can only return a single Output return value◦ or none at all

Some Methods may have Optional input parameters◦ these will take Default values if not supplied

Data IN and Data OUT

Looking at our example methods…◦ main() has a single (optional) input

parameter… an array of Strings (supplied when calling the program) we will look at arrays later on.

◦ println() has a single (optional) input parameter… a String which will be printed out on the console e.g. System.out.println("Hello World");

Calls & Parameters

Input Parameter

showInputDialog() requires a single Input parameter and returns a single parameter…◦ both parameters are Strings◦ e.g.

◦ This will show the Input Dialog with the message from the Input parameter…

◦ When the user clicks the OK button the text they typed will be returned and stored in the String variable sWidth.

Calls & Parameters

sWidth = JOptionPane.showInputDialog(null,"Enter width.");

Input ParameterOutput Variable

parseDouble() requires a single Input parameter and returns a single value…◦ the input parameter is a String◦ the output is a double (a number)◦ e.g.

◦ This will convert the text in the String sWidth into a number◦ and return this number which will be stored in the double

variable dWidth

Calls & Parameters

dWidth = Double.parseDouble(sWidth);

Input ParameterOutput Variable

Consider the following code:

Programming with Methods

public class MethodDemo {public static void main (String args[]) {

sayHello();int result = square(2);

System.out.println(result);}

public static void sayHello() {System.out.println("Hello! ");

}

public static int square(int x) {return x * x;

}}

‘main’ method: the entry point of our code

methods that the ‘main’ method will call

our method does not require any parameters

The sayHello() method in more detail:

Programming with Methods

public static void sayHello() {

System.out.println("Hello! ");

}

nothing is returned

name of method

empty parameter list ‘()’

The square() method in more detail:

Programming with Methods

public static int square(int x) {

return x * x;

}

name of method

this method requires an integer

an integer is returned...

… and the value of that integer is given by this expression

In our main method, we have the following code:

◦ The program will: output the word Hello calculate the result of 2 * 2 output the result

Programming with Methods

public static void main(String args[]) {sayHello();int result = square(2);System.out.println(result);

}

Anatomy of a Method

int calculateArea(int w, int h) {

int area = w * h;

return area;

}

Parameters

Used for passing data to a method

Return type

Defines the type of data to be passed from the method.

Keyword void is used here if method returns no data.

Return statement

Used for passing data from the method.

Omitted for void methods.

Calling a Methodint calculateArea(int w, int h) { int area = w * h; return area;}

int area;

area = calculateArea(2, 5);

System.out.println( "Area = " + area);

Parameters values

Are used to transfer data to a method.

Return value

Contains the data passed from the method.

Here it is copied into a variable.

A non-void method can be called anywhere an expression of the same type is permitted. e.g. from within calculations.

A call to a method called calculateArea

Consider these two methods:

Both calculate the square of the number that is supplied by the input parameter.

The first simply prints out the computed value.◦ i.e. the value is lost

The second returns the computed value◦ i.e. the value can be used by the program that

called the method

Return Types

public void square1 (int y){ System.out.println(y * y);}

public int square2 (int y){ return (y * y);}

Variables passed TO a method as Parameters are passed by VALUE only.

The name they are given in the method parameters is unique to the method◦ even if it is the same as a variable in the main

program Changes to the value of such a variable in

the method are NOT ‘seen’ by the main program.◦ consider the program and method on the next

slide…

Parameters & Variables

Parameters and Variables

…int y, result;

y = 3;result = square(y);…

public static int square(int x){

x = x * x;return x;

}

When square() is called, the parameter x takes on the value of variable y in the main program

Inside the computer’s memory however, x and y are totally separate

Method to square a number:

Main method…

What would be the output?

Variables and scope

public static int square(int x) {x = x * x;return x;

}

…int x, y;x = 2;y = square(x);System.out.println(x + " squared = " + y);…

2 squared = 4

In addition to variables passed in as parameters a method may also declare Local Variables◦ These only exist in the method.◦ They cease to exist when the method terminates.◦ The ‘main’ program cannot ‘see’ them.

Example…

Local Variables

int highest(int x, int y){

int temp;if( x > y) {

temp = x;} else {

temp = y;}return temp;

}

Local variable

Read Chapter 8 of Currie Workshop 8 on Wolf

Homework