Download presentation
Presentation is loading. Please wait.
Published byMark Kennedy Modified over 6 years ago
1
Suppose we want to print out the word MISSISSIPPI in big letters.
Methods! Suppose we want to print out the word MISSISSIPPI in big letters. * * ** ** * * * * * * * * * * * ********* *
2
We only really need to describe how to create 4 letters -- M, I, S, P
We could write a method for each letter! A method in Java is a named chunk of statements that performs a single well-defined task. The method’s name is a Java identifier Same rules as for variable names Choose a name that reflects the task performed by the method Method names typically sound like action verbs or phrases printM Methods are placed in the class definition of the program, right after the main section. Variables and objects declared in a method can only be used within that method!
3
So now we need 4 methods: printM printI printS printP public static void printM() { System.out.println(“* *”); System.out.println(“** **”); System.out.println(“* * * *”); System.out.println(“* * * *”); System.out.println(“* * *”); System.out.println(); } //printM
4
We call or invoke a method simply by stating its name.
printM(); tells the computer to run the method. This causes the following actions to take place: The computer remembers the line where the call took place Control is passed to the method (which means that the entire method is executed). When the method is completed, control is passed back to where the call occurred. Program execution continues there.
5
We would also define the other methods.
The body of main will look like: public static void main(String[] args) { printM(); printI(); printS(); printP(); } //main
6
A Java program printing the big letter word “Simple”
public class Simple { public static void main (String [] args) printS(); printI(); printM(); printP(); printL(); printE(); } //main public static void printS() { }\\printS public static void printI() {}\\printI public static void printM() {}\\printM public static void printP() {}\\printP public static void printL() {}\\printL public static void printE() {}\\printE }
7
public class Simple { public static void main (String [] args) printSimple(); } //main public static void printSimple() printS(); printI(); printM(); printP(); printL(); printE(); }\\printSimple public static void printS() { }\\printS public static void printI() {}\\printI public static void printM() {}\\printM public static void printP() {}\\printP public static void printL() {}\\printL public static void printE() {}\\printE }
8
public class Simple { public static void main (String [] args) printSimple(); } //main public static void printSimple() printS(); printI(); printM(); printP(); printL(); printE(); }\\printSimple public static void printS() { }\\printS public static void printI() {}\\printI public static void printM() {}\\printM public static void printP() {}\\printP public static void printL() {}\\printL public static void printE() {}\\printE }
9
public class Simple { public static void main (String [] args) printSimple(); printE(); } //main public static void printSimple() printS(); printI(); printM(); printP(); printL(); }\\printSimple public static void printS() { }\\printS public static void printI() {}\\printI public static void printM() {}\\printM public static void printP() {}\\printP public static void printL() {}\\printL public static void printE() {}\\printE }
10
public class Simple { public static void main (String [] args) int i; printSimple(); for (i = 1; i <= 5; i++) printE(); } //main public static void printSimple() printS(); printI(); printM(); printP(); printL(); }\\printSimple public static void printS() { }\\printS public static void printI() {}\\printI public static void printM() {}\\printM public static void printP() {}\\printP public static void printL() {}\\printL public static void printE() {}\\printE }
11
Method Examples Example 1. print 5-star method
public static void print5Stars( ) { int i = 1; while(i <= 5) System.out.print(“*”); i++; } Example 2. print 10-star method public static void print10Stars( ) while(i <= 10)
12
Method Parameter Example. print N-star method, where N can be ANY integer greater than 1 public static void printStars(int N) { int i = 1; while(i <= N) System.out.print(“*”); i++; }
13
Calling with Parameters
public static void main(String[] args) { printStars(5); printStars(10); } Tell the method how many stars you want when you call it.
14
public static void printStars(int N)
{ int i = 1; while(i <= N) System.out.print(“*”); i++; } printStars(5); // the above method call specifies that N=5. printStars(10); // the above method call specifies that N=10. printStars(); // the above method call DOES NOT work. Exercise: Write a void method that will print “Simple” with N letters ‘E’ attached to it, where N>0. For example: N=1, print Simplee.
15
printMax public static void printMax(double x, double y) { if(x > y) System.out.println(x + “ is bigger”); else System.out.println(y + “ is bigger”); } Write the statement that will call the method printMax to print out the maximum number between 76 and 100.
16
Most of the time, we want to give methods certain values to work with
Most of the time, we want to give methods certain values to work with. The values that methods accept are called parameters. In order to use a method with parameters, we must know the name of the method and the features of the parameters. These items describe the interface of the method. the number, order, and data type of parameters in the parameter list must match the number and order of the values used when calling the method. the parameters in the method header are called formal parameters the parameters in the call are called actual parameters or arguments we do not use the same variable names for formal and actual parameters!!!!!!! The method name and the parameter list together make up the method signature example, page 130
17
public static void printEcho(String mess, int N )
{ int i = 1; while(i <= N) System.out.println(mess); i++; } In main method: String message = "Hello"; printEcho(message, 3); Parameters must match. None of these works: printEcho(); printEcho(5, “Java”); printEcho(“Java”); printEcho(4.0, “Java”); printEcho(3, “abc”, 1);
18
Information Hiding Calling or using a method only requires the caller to know the information in the “signature” or first line of a method definition. The caller or user of a method does not need to know what goes on inside the body of the method. A method can be viewed as a black box (Can’t see inside it) What does this suggest about who can use variables declared inside the body of a method?
19
A return statement is required for a nonvoid method.
A method may return a value. The returnValueType is the data type of the value the method returns. If the method does not return a value, the returnValueType is the keyword void. For example, the returnValueType in the main method is void. A return statement is required for a nonvoid method. The following method is logically correct, but it has a compilation error, because the Java compiler thinks it possible that this method does not return any value. public static int findSign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; } To fix this problem, declare a local variable to hold the answer, then return that variable.
20
Write the method named findMax, which accepts two integers and returns the larger value of the two integers. public static int findMax(int a, int b) { int bigger; if(a >= b) bigger = a; else bigger = b; return bigger; } Write the method named findAvg, which accepts three integers and returns the average of those three integers.
21
The Scope of a Variable Think of the entire program as a block. Think of methods as sub-blocks. Each (sub)block can contain a parameter list a declaration section a body (of code) Basically, you can “see” variables/constants in your block, or in any containing or surrounding block. The scope of an identifier refers to the block in which it was declared or defined. Identifiers are available only within their block; they are never available outside their block. Identifiers declared within a method are called local variables.
22
A local variable: a variable defined inside a method.
Scope: the part of the program where the variable can be referenced. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used. It is legal to declare a local variable with the same name multiple times in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks.
23
Example A variable declared in the initial action part of a for loop header has its scope in the entire loop. But a variable declared inside a for loop body has its scope limited in the loop body from its declaration and to the end of the block that contains the variable.
24
It is fine to declare the variable i in two non-nesting blocks.
// Fine with no errors public static void correctMethod() { int x = 1; int y = 1; // i is declared for (int i = 1; i < 10; i++) x += i; } //for i // i is declared again y += i; } //correctMethod
25
It is wrong to declare a variable in two nesting blocks.
public static void badIdea() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) int x = 0; x += i; } //for i System.out.println(x); } //badIdea int i = 1;
26
When an identifier is encountered, its scope determines its value.
We do not use the same variable names for formal and actual parameters. We can use the same variable names as the formal parameters of different methods. public static int max(int a, int b, int c) . . . public static int min(int a, int b, int c) public static float avg(int a, int b, int c) high = max(num1, num2, num3); low = min(num1, num2, num3);
27
Skip 5.3.1 (for now) Skip 5.6 (for now) Skip 5.9-5.12 Review Exercises
Chapter 5 Skip (for now) Skip 5.6 (for now) Skip Review Exercises In Prog4.java import java.util.*; import java.text.*; public class Prog4 { public static Scanner keyboard = new Scanner (System.in); public static DecimalFormat moneyStyle = new DecimalFormat("$0.00"); public static void main(String[] args)
28
The factorial of a positive integer n is defined as
n! = n * (n - 1) * (n - 2) * * 2 * 1 for n > 1. Write the method. public static int factorial(int n) { int ans=1; for (int i = n; i > 1; i--) ans = ans * i; return ans; } Suppose that n>=0. int ans = 1; if (n > 1) for (int i=n; i>1; i--) ans*=i;
29
Write a method called Arithmetic that accepts 3 parameters (2 integers and one character, which will be either ‘+’, ‘-’, ‘*’, or ‘/’). It returns the result of applying the operator to the two integers. public static double operateTwoNum(int n1, int n2, char operator) { double ans = 1; switch (operator) case '+': ans = n1 + n2; break; case '-': ans = n1 - n2; case '*': ans = n1 * n2; case '/': ans = (double) n1 / n2; } return ans;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.