Introduction to Methods Introduction • Modules – Small pieces of a problem • e.g., divide and conquer – Facilitate design, implementation, operation and maintenance of.

Download Report

Transcript Introduction to Methods Introduction • Modules – Small pieces of a problem • e.g., divide and conquer – Facilitate design, implementation, operation and maintenance of.

Introduction to Methods
2
Introduction
• Modules
– Small pieces of a problem
• e.g., divide and conquer
– Facilitate design, implementation, operation and
maintenance of large programs
 2003 Prentice Hall, Inc. All rights reserved.
3
Program Modules in Java
• Modules in Java
– Methods (procedural programming)
– Classes (object oriented programming)
• Java API provides several modules
• Programmers can also create modules
– e.g., programmer-defined methods
• Methods
– Invoked by a method call
– Returns a result to calling method (caller)
– Similar to a boss (caller) asking a worker (called method) to
complete a task.
• The boss method delegates certain jobs to specific methods.
 2003 Prentice Hall, Inc. All rights reserved.
Modified by Evan Korth
Examples of methods
• A method that determines the maximum of two
numbers.
• A method that sorts a list of names
• A method that opens a file from the file system.
• A method that reads from the open file.
• A method that opens a new socket to the internet.
• A method that reads from that socket.
• A method that parses an integer value from a
String.
• A method that gets a String from the user.
Important concept #1
• Divide and Conquer: Break large programs into
a series of smaller modules
– Helps manage complexity
– Makes it easier to build large programs
– Makes it easier to debug programs
Important concept #2
• Abstraction: Most of the time, you need to know
what a method does, but not how it actually does
it.
– Also helps manage complexity
– You use other people’s code without knowing how it does
it’s job.
Using Static methods in the Java API
8
Math-Class Methods
• Class java.lang.Math
– Provides common mathematical calculations
– Calculate the square root of 900.0:
• Math.sqrt( 900.0 )
– Method sqrt belongs to class Math
• Dot (.) allows access to method sqrt
– The argument 900.0 is located inside parentheses
 2003 Prentice Hall, Inc. All rights reserved.
random numbers
• Often we want our programs to generate random
numbers.
– games of chance
– testing without user interaction
• java.lang.Math provides a method which can be
used to generate random numbers
 2003 Prentice Hall, Inc. All rights reserved.
10
Random-Number Generation
• Java random-number generators
– Math.random()
• Returns a double value with a positive sign, greater than
or equal to 0.0 and less than 1.0.
– What if we want to generate random integers?
 2003 Prentice Hall, Inc. All rights reserved.
11
Random-Number Generation
– ( int ) ( Math.random() * 6 )
• Produces integers from 0 - 5
 2003 Prentice Hall, Inc. All rights reserved.
12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Outline
// Fig. 6.8: RollDie.java
// Roll a six-sided die 6000 times.
import javax.swing.*;
RollDie.java
public class RollDie {
public static void main( String args[] )
{
Produce integers
int frequency1 = 0, frequency2 = 0, frequency3 = 0,
frequency4 = 0, frequency5 = 0, frequency6 = 0, face;
Line 14
in range 1-6Produce integers in
range 1-6
// summarize results
for ( int roll = 1; roll <= 6000; roll++ ) {
face = 1 + ( int ) ( Math.random() * 6 );
// determine roll value and increment appropriate counter
switch ( face ) {
case 1:
++frequency1;
break;
Lines 17-43
Increment appropriate
frequency counter,
depending on
randomly generated
number
Increment appropriate frequency counter,
depending on randomly generated number
case 2:
++frequency2;
break;
case 3:
++frequency3;
break;
 2003 Prentice Hall, Inc.
All rights reserved.
13
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
case 4:
++frequency4;
break;
case 5:
++frequency5;
break;
case 6:
++frequency6;
break;
} // end switch
} // end for
JTextArea outputArea = new JTextArea();
outputArea.setText( "Face\tFrequency" + "\n1\t" + frequency1 +
"\n2\t" + frequency2 + "\n3\t" + frequency3 +
"\n4\t" + frequency4 + "\n5\t" + frequency5 +
"\n6\t" + frequency6 );
Outline
RollDie.java
This is different from
the example I showed
in the compiler. I left
it this way to show
you that
showMessageDialog()
can take other objects
besides String for the
message. Remember
the API.
You do not need to
know JTextArea for
this class!
JOptionPane.showMessageDialog( null, outputArea,
"Rolling a Die 6000 Times", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate application
} // end main
} // end class RollDie
 2003 Prentice Hall, Inc.
All rights reserved.
14
User Defined Methods Declarations
• Methods
– Allow programmers to modularize programs
• Makes program development more manageable
• Software reusability
• Avoid repeating code
– Local variables
• Declared in method declaration
– Parameters
• Communicates information between methods via method calls
• Programmers can write customized methods
 2003 Prentice Hall, Inc. All rights reserved.
1 // Fig. 6.3: SquareIntegers.java
2 // Creating and using a programmer-defined method.
3 public class SquareIntegers {
4
5
6
7
8
9
10
11
12
public static void main (String args[])
{
int result;
// store result of call to method square
// loop 10 times
for ( int counter = 1; counter <= 10; counter++ ) {
result = square( counter ); // method call
// print the result of one call to the method
System.out.println ("The square of " + counter + " is " +
result );
13
} // end for
14
} // end method main()
15
// square method declaration
16
17
18
public static int square( int y )
{
return y * y; // return square of y
19
} // end method square
20 } // end class SquareIntegers
Method square returns
int that result stores
Line 9: method call to
square
line 16: header for
method square. States
that we have a method
that accepts one
integer as a parameter
and returns one integer
line 18: returns the
value y * y
y is the parameter of
method square
Method square
returns the square of y
 2003 Prentice Hall, Inc.
All rights reserved.
Modified by Evan Korth
16
User defined Method Declarations
• General format of method declaration:
modifiers return-value-type method-name( parameter1, …, parameterN )
{
declarations and statements
}
• Method can also return values:
return expression;
 2003 Prentice Hall, Inc. All rights reserved.
Naming your methods
• As with variables naming methods is important
• You should give your methods names which
clearly describe what the function is doing
– helps debugging
– helps others read your code
• Same rules as naming variables
– E.g. public static double calculateTax( int sale )
• When you write about a method in an explanation
use the parenthesis to indicate you are referencing
a method (as opposed to a regular variable):
– E.g. //call squareInteger() to calculate the square
 2003 Prentice Hall, Inc. All rights reserved.
Good programming with methods
• A method should do one and only one useful
action
– If you see names for your method that suggest multiple
actions then it’s time to break it up into separate functions;
for example,
calculateTaxAndPrintReturnAndSaveFile();
-ugh
• If you do something more than once in a program,
you should write a method for that action.
 2003 Prentice Hall, Inc. All rights reserved.
More Good Programming
• If you have written a method to do something in
one project, and you need to do the same action in
another project, you should reuse the method.
– In Java this is usually accomplished by using classes which
we will cover later this semester.
 2003 Prentice Hall, Inc. All rights reserved.
Return Value Types
• You can only return one value from a method.
• Returning void
– void: means nothing
– A method that returns void therefore returns nothing.
– Hence, there is no need for the optional return statement. But
using one can force early exit from the method.
– Example:
public static void printIntro (int n);
 2003 Prentice Hall, Inc. All rights reserved.
Parameter Data Types
• Unlike return values, you can pass as many
parameters as you like.
• To pass more than one parameter, you need to
separate the parameters with commas.
public static int max (int x, int y)
{
/*body*/
}
 2003 Prentice Hall, Inc. All rights reserved.
Warning
• Unlike declaring variables, you must specifically
state the type for multiple variables
– For example
takeTwoInts( int x, y )
is incorrect
– Instead you must write
takeTwoInts(int x, int y)
 2003 Prentice Hall, Inc. All rights reserved.
No parameters
• You can also have a method that accepts no
parameters. In such case, you would just have an
empty parameter list.
E.g.
public static int rollDie ()
public static void printIntro ()
 2003 Prentice Hall, Inc. All rights reserved.
24
Argument Promotion
• Coercion of arguments
– Forcing arguments to appropriate type to pass to method
• e.g., System.out.println( Math.sqrt( 4 ) );
– Evaluates Math.sqrt( 4 )
– Then evaluates System.out.println()
• Promotion rules
– Specify how to convert types without data loss
 2003 Prentice Hall, Inc. All rights reserved.
25
Type
double
float
long
int
char
short
byte
boolean
Valid promotions
None
double
float or double
long, float or double
int, long, float or double
int, long, float or double
short, int, long, float or double
None (boolean values are not considered to be
numbers in Java)
Fig. 6.5 Allowed promotions for primitive types.
 2003 Prentice Hall, Inc. All rights reserved.
Exercise 1
• Implement the following methods
– Method convertToCelsius returns the Celsius
equivalent of a Fahrenheit temperature (( 5.0 / 9.0 * ( fTemp
- 32 ) )
– Method convertToFahrenheit returns the Fehrenheit
equivalent of a Celsius temperature ( 9.0 / 5.0 * cTemp + 32
)
– Use these methods to write a program that prints charts
showing the Fahrenheit equivalent of all Celsius
temperatures from 0 to 100 degrees, and the Celsius
equivalents of all Fahrenheit temperatures from 32 to 212
degrees. Print the output in a neat tabular format.
 2003Prentice
Prentice Hall,Hall,
Inc. All
rightsAll
reserved.
 2000
Inc.
rights
Exercise 2
• Write a method that will print a line of stars. The
method should take one parameter which will
determine the number of stars to print. Write a
main() method which calls the star printing
method 5 times using random numbers from 3 13.
 2003 Prentice Hall, Inc. All rights reserved.
review
• When is the return statement required?
• What do the following method headers tell us?
public
public
public
public
public
static
static
static
static
static
int max (int a, int b)
void nPrintln (String s, int n)
void main (String args[])
int max (int a, n)
String pickLine ()
 2003 Prentice Hall, Inc. All rights reserved.
review
• Given the following method headers:
public static int max (int x, int y)
public static double min (double x,
double y)
Which of the following method calls are legal?
max (1,2);
min (1,2);
max (1.0, 2.0);
min (1.0, 2.0);
 2003 Prentice Hall, Inc. All rights reserved.
30
Method Overloading
• Method overloading
– Several methods of the same name
– Different parameter set for each method
• Number of parameters
• Parameter types
– The Java compiler determines which method to use based on
the parameters.
– Can also be used in conjunction with argument coercion.
• The combination can lead to ambiguous invocation which is an
error
 2003 Prentice Hall, Inc. All rights reserved.
Outline
Understanding Scope
 2000 Prentice Hall, Inc. All rights
Scope
• Determines where the variable can be referenced
in a program.
• By understanding scope, you can make your
programs:
– more modular
– easier to debug
 2003 Prentice Hall, Inc. All rights reserved.
33
Scope of Declarations
• Scope
– Portion of the program that can reference an entity by its
name
– Basic scope rules
• Scope of a parameter declaration
– The entire method
• Scope of a local-variable declaration
– From where it is declared until the end of the block it is
declared in
• Scope of a local-variable declaration that appears in the
initialization section of a for statement’s header
– The entire code block of the for loop
 2003 Prentice Hall, Inc. All rights reserved.
Modified by Evan Korth
pass by value
• In Java when a parameter is passed to a method
and the variable is modified by that method, the
value does not change upon return to the calling
method (there are exceptions to this including
passing arrays and passing object references)
• This is not true in all programming languages.
 2003 Prentice Hall, Inc. All rights reserved.
Good Programming Habits
• Pick a method name that strongly, completely and
clearly describes what the function does or returns
– E.g. verb-plus-object or description of returned value
(getters, setters, predicates are object orientated naming
conventions)
• Make sure your actual parameters (i.e. the actual
data you pass to a method) matches the data type
the method expects.
• Make sure you use all the parameters in your
method; if not, lose the ones you don’t use.
• Document any assumptions about your
parameters!
 2003 Prentice Hall, Inc. All rights reserved.