Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Methods (a.k.a. Functions)

Slides:



Advertisements
Similar presentations
Craps. /* * file : Craps.java * file : Craps.java * author: george j. grevera, ph.d. * author: george j. grevera, ph.d. * desc. : program to simulate.
Advertisements

BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
Introduction to Computers and Programming Lecture 11: Introduction to Methods Professor: Evan Korth New York University.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
July 13 th.  If/ Else if / Else  Variable Scope  Nested if/else's  Switch statements  Conditional Operator.
Computer Science 1620 Loops.
Introduction to working with Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming.
©2004 Brooks/Cole Chapter 6 Methods. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Using Methods We've already seen examples of using methods.
Introduction to Computers and Programming Introduction to Methods in Java.
Structured programming
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computer Programming Decisions If/Else Booleans.
School of Computing Science CMT1000 © Ed Currie Middlesex University Lecture 10: 1 TEST!!
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Relational Operators Control structures Decisions using “if” statements  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
 To be able to write larger programs ◦ By breaking them down into smaller parts and passing data between the parts.  To understand the concepts of Methods.
CS305j Introduction to Computing While Loops 1 Topic 15 Indefinite Loops - While Loops "If you cannot grok [understand] the overall structure of a program.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
Lecture 7. Review Homework 1 (sample solution) Project 1 will be assigned next week –Draw a picture (whatever you want) in the world by using turtles.
Introduction to Methods
Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
COMP More About Classes Yi Hong May 22, 2015.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Arrays (Part 1) Computer Science Erwin High School Fall 2014.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Variables, Arithmetic, etc.)
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
Session Three Review & Conditional Control Flow. Java File Hierarchy Projects Packages Classes Methods.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
COM S 207 Method Instructor: Ying Cai Department of Computer Science Iowa State University
CSC1030 HANDS-ON INTRODUCTION TO JAVA Introductory Lab.
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
Java methods Methods break down large problems into smaller ones Your program may call the same method many times saves writing and maintaining same code.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
2.1 Functions. Functions in Mathematics f x y z f (x, y, z) Domain Range.
Application development with Java Lecture 6 Rina Zviel-Girshin.
1 Class Chapter Objectives Use a while loop to repeat a series of statements Get data from user through an input dialog box Add error checking.
Department of Computer Engineering Methods Computer Programming for International Engineers.
CSCI S-1 Section 8. Coming Soon Problem Set Four (72 + 5/15 points) – Tuesday, July 21, 17:00 EST.
AP Computer Science A – Healdsburg High School 1 Unit 9 - Parameter Passing in Java.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Chapter 2 Clarifications
CSC111 Quick Revision.
Chapter 7 User-Defined Methods.
AKA the birth, life, and death of variables.
SELECTION STATEMENTS (1)
Control Statement Examples
Chapter 5 - Functions Outline 5.1 Introduction
Starting Out with Java: From Control Structures through Objects
Defining methods and more arrays
Faculty of Computer Science & Information System
METHODS, CLASSES, AND OBJECTS A FIRST LOOK
Methods and Data Passing
Methods/Functions.
Repetition CSC 1051 – Data Structures and Algorithms I Course website:
Presentation transcript:

Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Methods (a.k.a. Functions)

Methods (a.k.a. Functions) We’ve seen and used methods already.... These are all examples of method calls r = Math.sqrt( 9.0 ); q = Math.pow( r, 3.0 ); answer = Math.sqrt(Math.pow(x, 2.0) + Math.pow(y, 2.0)); z = Math.abs( y – x ); p = Math.exp( n );

Methods Method calls change a program’s flow of control: The flow of control jumps to the method Method code is executed An output is returned and flow of control returns to the calling method r = Math.sqrt(9.0); execute the square root code (algorithm) 2 capture the returned value 3 1 call the sqrt() method input to method 3.0 output of method 2 1 3

Writing our own Methods We can build our own methods in Java by identifying the three required elements : Input values (and data types)... Name of method... Output data type... public static double cube(double x) a Java method can have no more than 1 output (to have zero outputs, use void instead)

Writing our own Methods public class CubeProgram { public static void main(String args[]) { double v = 12.5; double vCubed = cube(v); // CALL THE METHOD System.out.println(v + " cubed is: " + vCubed); } public static double cube(double x) { double y = x * x * x; // METHOD CODE return y; } Add a quadruple() method and call it from main()

Writing our own Methods public class CubeProgram { public static void main(String args[]) { double v = 12.5; double vCubed = cube(v); // CALL THE METHOD System.out.println(v + " cubed is: " + vCubed); } public static double cube(double x) { double y = x * x * x; // METHOD CODE return y; } Add a quadruple() method and call it from main() Write a program that asks the user to enter four numbers in main() ; write a method called calcAverage() that calculates and returns the average of the four numbers Write a program to simulate the rolling of two dice, displaying the results; use a method called rollDice()

Why Create Methods? Methods are reusable program units Write once, use repeatedly Algorithm details are hidden, increasing readability Methods are compact modules that serve a specific purpose for which they were designed It’s easier to read, write, and maintain individual modules

Decision-Making Methods Aside from calculations, methods are often used to make decisions Return value is of type boolean (i.e. true or false ) public static boolean isPassingGrade( int grade ) { if ( grade >= 60 ) { return true; } else { return false; }

Decision-Making Methods public static void main( String[] args ) {... if ( isPassingGrade( grade ) ) { System.out.println( "You passed!" );... }... } public static boolean isPassingGrade( int grade ) { if ( grade >= 60 ) { return true; } else { return false; }

Input Parameters When we call a method, we pass in values int max = findMax( num1, num2 ); double c = cube( 9.0 ); double r = power( x, 4 ); int fact = factorial( n ); int total = rollDice();...or sometimes we don’t pass in any values at all

Input Parameters public class FindMaxProgram { public static void main( String[] args ) { int num1 = 19, num2 = 24; int max = findMax( num1, num2 ); // CALL METHOD System.out.println( max + " is the maximum." ); } public static int findMax( int x, int y ) { // METHOD CODE GOES HERE... } Write the findMax() method code ( HINT : use an if-else statement)

Input Parameters public static void main( String[] args ) {... int max = findMax( num1, num2 ); // CALL METHOD... } public static int findMax( int x, int y ) { // METHOD CODE GOES HERE... } Pass values to the method

Input Parameters storage in memory Variables x and y are usable only within the findMax() method public static void main( String[] args ) {... int max = findMax( num1, num2 ); // CALL METHOD... } public static int findMax( int x, int y ) { // METHOD CODE GOES HERE... }

Variable Scope We know that a variable must be declared before it can be used public static void main( String[] args ) { int x = 5; System.out.println( x ); System.out.println( y ); } Variable y is not declared! Declaring variable x creates storage for it in memory 5 x

Variable Scope Variables are usable (in scope) only within the section of code in which they are declared public static void main( String[] args ) { int x = 5; int r; r = cube( x ); } 5 x r public static int cube( int w ) {... 5 w x and r only usable within main() method w only usable within cube() method

public static int cube( int w ) {... public static void main( String[] args ) { int x = 5; int r; r = cube( x ); } Variable Scope Variables are usable (in scope) only within the section of code in which they are declared 5 xr main() 5 w cube() w only usable within cube() method x and r only usable within main() method

public static int cube( int w ) { int z = w * w * w; public static void main( String[] args ) { int x = 5; int r; r = cube( x ); } Variable Scope Variables are usable (in scope) only within the section of code in which they are declared 5 xr 5 w main() cube() w and z only usable within cube() method x and r only usable within main() method 125 z

public static int cube( int w ) { int z = w * w * w; return z; } public static void main( String[] args ) { int x = 5; int r; r = cube( x ); } Variable Scope Variables are usable (in scope) only within the section of code in which they are declared 5 xr 5 w main() cube() w and z only usable within cube() method x and r only usable within main() method 125 z

public static int cube( int w ) { int z = w * w * w; return z; } public static void main( String[] args ) { int x = 5; int r; r = cube( x ); } Variable Scope Variables are usable (in scope) only within the section of code in which they are declared 5 x 125 r 5 w main() cube() w and z only usable within cube() method x and r only usable within main() method 125 z