methods_samples

advertisement

User-Defined & Pre-Defined Methods

Some of the benefits of using methods and classes are:

It supports Procedural abstraction: allows us to separate how an operation is implemented from how it is used. To use a method we only need to know how to call it and what results to expect. We do not need to be concerned with it’s implementation.

To use

System.out.println(“Hello World”);

we only need to know that it will display the string contained in parenthesis, and perform a “new line”, but we don’t know or even care what the code implementing this module looks like.

Implementation hiding: Algorithms isolated within methods can later be modified by only changing the method, not the rest of the programs which use it. The implementation of println is hidden.

Modular programs: methods can be used to partition large programs into smaller pieces which can be more easily understood, implemented, and tested in isolation.

These modules can be implemented one at a time, without a programmer having to worry about the overall problem to be solved. Also, individual modules/methods can be implemented by different individuals.

Reuse : Creating standard collections of useful methods are a way of extending a language. It is possible to write utility/reusable methods and store them in libraries or classes (such as Math) for many users to use.

So, how do we use a method???

Remember there are two types of methods.. instance and static. Also, a method may or may not calculate and return a value. static double pow ( double a, double b)

This says that the method is

“static” and can be called without being invoked for a specific object instance

This is the return type of the method. This means that the method will calculate a value of type double and return it to the calling program. Not all methods will produce a value. If the method does not produce a value the “type” void is used

This is the formal parameter list for function pow. This tells me HOW many values we must supply to function pow for it to perform its calculations. Formal parameters act as local variable within pow. To use pow we must call it with two parameters of type double…

Since pow produces a value it must be called from with in an expression, or the return value will be lost….!!!!!!!!!!!!!!!!!!!!!! To call pow in our “main” method, we would: double square=0, arg1 = 3.0, arg2 = 2.0; square = Math.pow(arg1, arg2);

System.out.println(“The square of “ + arg1 + “ is “ + square);

With each call, an activation record is created for pow. Storage is allocated for the formal parameters and the return value inside the activation record.

The values in the arguments are then copied INTO the formal parameters

Arg1

3 pow

3 a

9 return value

2 b

2

Arg2

Control then transfers into the BODY of method pow. It is executed, and then

Writing User defined methods:

Lets look at a program using nested loops, that prints a triangle centered on the page.

The triangle produced would look something like:

#

###

#####

#######

#########

###########

#############

###############

1

}

} public class CenteredTriangle {

public static void main (String args[]) {

Centered Triangles

int num_rows, num_blanks = 39, num_chars = 1; char letter = '#';

4

2

3

System.out.println("To print a Triangle, please enter the number");

System.out.println(" of rows to print as an integer between 1 & 26. "); num_rows = (int) ReadItem.getLong();

// print one row at a time

System.out.println(); for (int i = 1; i <= num_rows; i++) {

// for each row we need to skip enough spaces to center

// the characters in the row.. In the first row there

// is one character. Assuming 80 characters per row

// we need to skip 39 blank spaces. In each subsequent

// row, we will print 2 more characters, and skip one

// fewer space.

}

// print out the required number of blanks for(int j = 1; j <= num_blanks; j++) {

System.out.print(' ');

}

// print out the required number of characters for (int k = 1; k <= num_chars; k++) {

System.out.print(letter);

}

// to go to a new line print the new line character

System.out.print('\n');

// decrement the number of blanks num_blanks--;

// increment the number of characters to print num_chars += 2;

System.out.println("\nAll done");

public class CenteredTriangle {

public static void main (String args[]) { int num_rows, num_blanks = 39, num_chars = 1; char letter = '#'; num_rows = 5; for (int i = 1; i <= num_rows; i++) {

// print out the required number of blanks

for(int j = 1; j <= num_blanks; j++) {

}

System.out.print(' ');

// print out the required number of characters

for (int k = 1; k <= num_chars; k++) {

}

System.out.print(letter);

// to go to a new line print the new line character

System.out.print('\n');

// decrement the number of blanks

num_blanks--;

// increment the number of characters to print

num_chars += 2;

} num_rows = 8; num_blanks = 39; num_chars = 1; for (int i = 1; i <= num_rows; i++) {

// print out the required number of blanks

for(int j = 1; j <= num_blanks; j++) {

}

System.out.print(' ');

// print out the required number of characters

for (int k = 1; k <= num_chars; k++) {

}

System.out.print(letter);

// to go to a new line print the new line character

System.out.print('\n');

// decrement the number of blanks

num_blanks--;

// increment the number of characters to print

num_chars += 2;

}

num_rows = 10; num_blanks = 39; num_chars = 1; for (int i = 1; i <= num_rows; i++) {

// print out the required number of blanks

for(int j = 1; j <= num_blanks; j++) {

}

System.out.print(' ');

// print out the required number of characters

for (int k = 1; k <= num_chars; k++) {

}

System.out.print(letter);

// to go to a new line print the new line character

System.out.print('\n');

// decrement the number of blanks

num_blanks--;

// increment the number of characters to print

num_chars += 2;

}

}

System.out.println("\nAll done");

}

While this approach would work, it is not very efficient… also we could forget to reset the number of blanks or characters.. so since I need to REUSE the same nested loop over and over.. maybe… must maybe I could take it out of MAIN and write a method that I could use to print as many triangles as I want!!!!!!!!!!!!!!!!

How to write a user defined method

To define and write a method you need to do the following: o Name the method o Determine the number and data type of formal parameters if any. o Determine the data type of the return value computed by the method if any. o Determine the algorithm to be implemented in the method body.

For now, our method will be contained inside the same “class” as our main method, simply following the body of main.

public class MyClass{

public static void main(String[] args) {

------- the body of main goes here

} // end of main

******* user defined methods go here

}// end of class MyClass the syntax of a user defined method is: modifier(s) returnType methodName( formal parameter list) { code implementing method body

}

static void printTriangle(int rows) { int num_blanks = 39, num_chars = 1; char letter = '#';

// print one row at a time

System.out.println(); for (int i = 1; i <= rows; i++) {

// for each row we need to skip enough spaces to center

// the characters in the row.. In the first row there

// is one character. Assuming 80 characters per row

// we need to skip 39 blank spaces. In each subsequent

// row, we will print 2 more characters, and skip one

// fewer space.

// print out the required number of blanks for(int j = 1; j <= num_blanks; j++) {

}

System.out.print(' ');

}

// print out the required number of characters for (int k = 1; k <= num_chars; k++) {

System.out.print(letter);

// to go to a new line print the new line character

System.out.print('\n');

// decrement the number of blanks num_blanks--;

// increment the number of characters to print num_chars += 2;

} // end of outter for

}// end of printTriangle

public class triangleMethod {

public static void main (String args[]) { int num_rows;

System.out.println("To print a Triangle, please enter the number");

System.out.println(" of rows to print as an integer between 1 & 26. "); num_rows = (int) ReadItem.getLong(); printTriangle (num_rows);

System.out.println("\nAll done");

}// end of main static void printTriangle(int rows) { int num_blanks = 39, num_chars = 1; char letter = '#';

// print one row at a time

System.out.println(); for (int i = 1; i <= rows; i++) {

// for each row we need to skip enough spaces to center

// the characters in the row.. In the first row there

// is one character. Assuming 80 characters per row

// we need to skip 39 blank spaces. In each subsequent

// row, we will print 2 more characters, and skip one

// fewer space.

}

// print out the required number of blanks for(int j = 1; j <= num_blanks; j++) {

System.out.print(' ');

// print out the required number of characters for (int k = 1; k <= num_chars; k++) {

}

System.out.print(letter);

// to go to a new line print the new line character

System.out.print('\n');

// decrement the number of blanks num_blanks--;

// increment the number of characters to print num_chars += 2;

} // end of outter for

}// end of printTriangle

} // end of class triangleMethod

I could even continue along this track, modifying main to allow me to print multiple triangles ….

public static void main (String args[]) {

int num_rows;

System.out.println("To print a Triangle, please enter the number");

System.out.println(" of rows to print as an integer between 1 & 26. ");

System.out.println("To stop printing triangles, enter 0");

num_rows = (int) ReadItem.getLong();

while (num_rows > 0){

printTriangle (num_rows);

System.out.println("To print a Triangle, please enter the number");

System.out.println(" of rows to print as an integer between 1 & 26. ");

System.out.println("To stop printing triangles, enter 0");

num_rows = (int) ReadItem.getLong();

} // end while

System.out.println("\nAll done");

} // end of main

/home/hayhurst/java- java triangleMethod

To print a Triangle, please enter the number

of rows to print as an integer between 1 & 26.

To stop printing triangles, enter 0

3

#

###

#####

To print a Triangle, please enter the number

of rows to print as an integer between 1 & 26.

To stop printing triangles, enter 0

4

#

###

#####

#######

To print a Triangle, please enter the number

of rows to print as an integer between 1 & 26.

To stop printing triangles, enter 0

0

All done

Download