Suppose we want to print out the word MISSISSIPPI in big letters.

Slides:



Advertisements
Similar presentations
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 5 Functions.
Methods Liang, Chapter 4. What is a method? A method is a way of running an ‘encapsulated’ series of commands. System.out.println(“ Whazzup ”); JOptionPane.showMessageDialog(null,
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Introduction to Java Programming, 4E Y. Daniel Liang.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
1 Chapter 5 Methods. 2 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
1 Topic 04 Methods Programming II/A CMC2522 / CIM2561 Bavy Li.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
COMP More About Classes Yi Hong May 22, 2015.
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
The Java Programming Language
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
Chapter 5: Methods 1. Objectives To declare methods, invoke methods, and pass arguments to a method (§ ). To use method overloading and know ambiguous.
The scope of local variables. Murphy's Law The famous Murphy's Law says: Anything that can possibly go wrong, does. (Wikipedia page on Murphy's Law:
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Lecture 14 Functions.
1 Building Java Programs Chapter 3: Introduction to Parameters and Objects These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They.
CSC 212 Object-Oriented Programming and Java Part 2.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
Methods. Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Classes - Intermediate
Methods.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 6 Methods Dr. Musab Zghoul.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 6 Methods.
Information and Computer Sciences University of Hawaii, Manoa
Chapter 7 User-Defined Methods.
Reference: COS240 Syllabus
Suppose we want to print out the word MISSISSIPPI in big letters.
Chapter 6: Methods CS1: Java Programming Colorado State University
Object Oriented Systems Lecture 03 Method
Chapter 6 Methods 1.
Programmazione I a.a. 2017/2018.
Methods.
Chapter 5 – Part 2 Methods Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Class Structure 16-Nov-18.
An Introduction to Java – Part I, language basics
Group Status Project Status.
CHAPTER 6 GENERAL-PURPOSE METHODS
Class Structure 7-Dec-18.
Class Structure 2-Jan-19.
Chapter 6 Methods.
Chapter 5 Methods.
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Class Structure 25-Feb-19.
Week 4 Lecture-2 Chapter 6 (Methods).
Chapter 5 Methods Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Scope of variables class scopeofvars {
Corresponds with Chapter 5
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

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. * * ** ** * * * * * * * * * * * ********* *

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!

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

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.

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

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 }

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 }

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 }

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 }

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 }

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)

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++; }

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.

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.

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.

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

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);

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?

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.

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.

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.

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.

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.

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

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;

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);

Skip 5.3.1 (for now) Skip 5.6 (for now) Skip 5.9-5.12 Review Exercises Chapter 5 Skip 5.3.1 (for now) Skip 5.6 (for now) Skip 5.9-5.12 Review Exercises 5.1-5.2 5.6-5.11 5.15 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)

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;

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;