chapter 6 general-purpose methods

40
©2004 Brooks/Cole Modified by S. J. fritz 1/05 CHAPTER 6 GENERAL-PURPOSE METHODS Click the mouse to move to the next page. Use the ESC key to exit this chapter. This chapter in the book includes: 6.1 Method and Parameter Declarations 6.2 Returning a Single Value 6.3 Variable Scope 6.4 Common Programming Errors 6.5 Chapter Summary 6.6 Chapter Supplement: Generating Random Numbers

Upload: phyllis-martinez

Post on 02-Jan-2016

30 views

Category:

Documents


4 download

DESCRIPTION

CHAPTER 6 GENERAL-PURPOSE METHODS. This chapter in the book includes: 6.1Method and Parameter Declarations 6.2Returning a Single Value 6.3Variable Scope 6.4Common Programming Errors 6.5Chapter Summary 6.6Chapter Supplement: Generating Random Numbers. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

CHAPTER 6GENERAL-PURPOSE METHODS

Click the mouse to move to the next page.Use the ESC key to exit this chapter.

This chapter in the book includes:6.1 Method and Parameter Declarations6.2 Returning a Single Value6.3 Variable Scope6.4 Common Programming Errors6.5 Chapter Summary6.6 Chapter Supplement:

Generating Random Numbers

Page 2: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Method and Parameter Declarations

• Every Java method must be contained within a class just as the main( ) method is.

• There are different types of methods– Static – which receives its data as arguments and

manipulates a shared variable – it belongs to the class rather than to objects of the class – it is a class method

– Non-static – has access to both instance (without static) and static fields – most methods are non-static or instance methods

• The key word public mean that the method can be used outside its own class; private indicates that the method is used only within the class

Page 3: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Java Methods

• Instance methods- are associated with individual objects

• Class methods- ( static) methods are associated with a class (like main)

• Helper methods- are subprograms within a class that help other methods in the class; they are declared privately within a class

• Constructor methods- are used with the new operator to prepare an object for use.

Page 4: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

General Purpose Methods

We will be concerned with the method itself and how it interacts with other methods, such as

main( )• Passing data to a general purpose method• Having the method correctly receive, store and

process the data• A method is called by using its name and passing

data (or arguments) in parenthesis

Page 5: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Figure 6.1: Calling and Passing Data to a Method

Page 6: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Figure 6.2: Calling and Passing Two Values to findMaximum()

Page 7: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

import javax.swing.*;

public class ShowTheCall

{ public static void main(String[] args)

{

String s1;

double firstnum, secnum;

s1 = JOptionPane.showInputDialog("Enter number:");

firstnum = Double.parseDouble(s1);

s1 = JOptionPane.showInputDialog("Great! Please enter a second number: ");

secnum = Double.parseDouble(s1);

findMaximum(firstnum, secnum); // the method is called here

System.exit(0);

} // end of method

} // end of class

Page 8: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Figure 6.3: findMaximum() Receives Actual Values

Page 9: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Figure 6.4: General Format of a Method

Method signature

Header – specifies access privileges (where method can be called), data type of returned value, gives method a name and specifies number, order and type of its arguments

Page 10: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Figure 6.5: The Structure of a General Purpose Method’s Header

For example:

public static void main (String [] args)

Page 11: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Figure 6.6: The Structure of a Method Body

Page 12: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Structure of Method Body for findMaximum

// following is the findMaximum() method

public static void findMaximum(double x, double y) // no semicolon here!

{ // start of method body

double maxnum; // variable declaration

if (x >= y) // find the maximum number

maxnum = x;

else

maxnum = y;

JOptionPane.showMessageDialog(null,

"The maximum of " + x + " and " + y + " is " + maxnum,

"Maximum Value", JOptionPane.INFORMATION_MESSAGE);

} // end of method body and end of method

Page 13: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

import javax.swing.*;

public class CompleteTheCall

{

public static void main(String[] args)

{

String s1;

double firstnum, secnum; s1 = JOptionPane.showInputDialog("Enter a number:"); firstnum = Double.parseDouble(s1); s1 = JOptionPane.showInputDialog("Great! Please enter a second number:");

secnum = Double.parseDouble(s1); findMaximum(firstnum, secnum); // the method is called here System.exit(0); } // end of main() method // following is the findMaximum() method public static void findMaximum(double x, double y) { // start of method body double maxnum; // variable declaration if (x >= y) // find the maximum number maxnum = x; else maxnum = y;

JOptionPane.showMessageDialog(null, "The maximum of " + x + " and " + y + " is " + maxnum, "Maximum Value", JOptionPane.INFORMATION_MESSAGE); } // end of method body and end of method} // end of class

Page 14: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Figure 6.7: A Sample Display Produced by Program 6.2

Page 15: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Point of Information: Isolation Testing

Page 16: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Calling a Method

•The findMaximum( ) method is the called method, because it is called by its reference in main( )

•The method that does the calling (in this case main( ) ) is the calling method

•The items within parenthesis are the arguments or parameters:

•Formal-the list of values and their data types(or form), that the method expects to receive ( in parenthesis in the method header)

•Actual - the actual data values supplied when the call is made ( in the calling method)

Page 17: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Method Stubs and Testing

• Usually write the main method and add other methods as they are developed

• Problem – can’t be run without the methods• Solution – design “empty methods” or stubs,

which just contain the header ( and perhaps some comment or print statement to aid in debugging)

• Stub is used as a placeholder until the method is written

• Calling program is called a “driver” and is used to test each method

Page 18: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Empty Parameter Lists and Overloading

• Rarely, but sometimes, no parameters are needed – just include empty parenthesis

public static int display ( ) //returns an integer

• To call this method use x = display( );

• Using the same method name for more than one method is called overlaoding. The compiler must be able to determine which method to use based on the data types of the parameters. ( eg. square(5); for ints and square (2.5); for doubles)

• Method signatures must be unique.

Page 19: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Figure 6.8: A Method Directly Returnsat Most One Value

Page 20: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Returning a Single Value

• Pass by value or call by value – copies of the data values contained in the arguments when the method is called are passed to the method.

• Method may change the values in its copy as well as any local variables declared in the method

• A method returns at most one single value.

Page 21: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Void and Value Returning Methods

• Void methods are those which manipulate the data within the method. They often contain input or output statements. ( Name with an action word like displayMenu).

• Value returning methods ( like mathematical functions) – just compute and return a single value. They DO NOT include input or output statements. They must be part of an expression or assigned to a variable in the calling program. (Usually name with a noun such as square or cube)

Page 22: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Another Maximum method

// this one returns the maximum valuepublic double Maximum(double x, double y) { // start of method body double maxnum; // variable declaration if (x >= y) // find the maximum number maxnum = x; else maxnum = y; return maxnum; // return statement}

Page 23: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Calling a Value Returning Method

• Void methods can stand alone- so they are called just by using the method name:

findMaximum( 5, 8);• Value returning methods must return their value to a

variable or be used within an expression (anywhere that data type can be used)larger = Maximum(5,8); or

if (Maximum(5,8) <10) … or

….2* Maximum(5,8)… or

System.out.println( Maximum(5,8) + “ is the larger number “);

Page 24: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Passing a Reference Variable

• Java passes both primitive and reference variables in the same way: ( by value) a copy is passed to the method and stored in one of the formal parameters.

• Advantages:– Methods can use any variable name without interfering

with other methods that might use the same name– Changing the value in the method will not affect the

value of that variable in other methods (called a side effect)

• Passing a reference variable does have some other implications that passing a primitive does not

Page 25: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Figure 6.9: Passing a Reference Value

Page 26: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Passing a Reference Variable

• Since a reference value gives direct access to the object, any change made within the method is made to the original object’s value.

• The ability to alter a referenced object within a method is useful where a method must return more than one value.– Primitive types must first be converted to wrapper

types( see p.105-106). Then the reference to this object is passed to the called method.

– This will not work with String objects, because they are immutable.

Page 27: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Exercises 6.2: Item 9.a.

For Practice:

Write a method named distance that accepts the coordinates of two points (x1,y1) and (x2, y2) and calculates and returns the distance between them according to this formula:

Page 28: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Exercises 6.2: Item 11

Page 29: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Figure 6.10: A Method Can Be Considereda Closed Box

Page 30: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Variable Scope

• What goes on inside the method are “hidden” from other methods.

• Variables declared inside a method are available only to that method and are called local variables.

• The section of the program where an identifier is “known” or is visible is its scope – usually the block in which it is declared ( block scope).

• A Class variable is any variable declared within a class, but outside a method.

Page 31: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Variable “Lifetime” and Duration

• Identifiers within the class scope come into being when the class is loaded into memory and remain until the program finishes executing.

• Static variables have the same duration as their defining class.

• Variables with block scope exist only which the block in which they are defined is in scope, then they are released. If the block comes back into scope later, new storage areas are reserved.

Page 32: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Figure 6.11:

The Three Storage Areas Created by

Program 6.6

Page 33: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Scope Resolution

• Whe a local ( block) variable has the same name as a variable with class scope, all references within the scope of the local variable refer to that local variable.

• The local variable takes precedence.• The class variable can be accessed by

prefacing it with its class name as shown in the next example.

Page 34: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

public class ScopeCover

{

private static double number = 42.8; // this variable has class scope

public static void main(String[] args)

{

double number = 26.4; // this variable has local scope

System.out.println("The value of number is " + number);

}

} // end of class

What is the output of this code?

The value of number is 26.4

Page 35: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

public class ScopeResolution

{

private static double number = 42.8; // this is a static (class scope) variable

public static void main(String[] args)

{

double number = 26.4; // this is a local variable

System.out.println("The value of number is " + ScopeResolution.number);

}

} // end of class

What is the output of this code?

The value of number is 42.5

Page 36: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Inner and Outer Blocks

• Variables declared in an inner block cannot be acced in any enclosing outside block.

• This includes variables declared within the parenthesis of a for statement ( the value of i cannot be accessed once the loop terminates).

• The same variable name can be declared and used again after the inner block is out of scope.

Page 37: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Common Programming Errors

• Attempting to pass incorrect data types• Declaring the same variable locally within

both the calling and called methods and assuming that changing one value affects the other.

• Ending a method header with a semicolon• Forgetting to include the data type of the

method’s parameters within the header.

Page 38: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

Random Numbers

• Random numbers – a series of numbers whose order cannot be predicted, where each has the same likelyhood of occurring.

• Pseudorandom numbers – sufficiently random.

• General purpos method in the Math class

• random( ) – produces double precision numbers from 0.0 up to, but not including 1.0

Page 39: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

More Random Numbers

• To produce integers use scaling:

(int)(Math.random( ) * n) // for 0 to n-1• To produce a random integer between 1 and n use

1+ (int)(Math.random( ) * n) // for 1 to n

Example:

1+ (int)(Math.random( ) * 6) // for 1 to 6 (dice game)

or in general use

a+ (int)(Math.random( ) * b+1-a) // for a to b

Page 40: CHAPTER 6 GENERAL-PURPOSE METHODS

©2004 Brooks/ColeModified by S. J. fritz 1/05

public class RandomNumbers

{ // prints 10 random numbers

public static void main(String[] args)

{

final int NUMBERS = 10;

double randValue;

int I, randInt;

for (i = 1; i <= 10; i++)

{

randValue = Math.random( );

randInt = (int)( Math.random( ) * 100) //integers between 0 and 99

System.out.println(randValue, randInt);

} // end for loop

} // end main

} // end of class