Methods Material from Chapters 5 & 6. Terminology  Method, function, procedure, subroutine  all mean approximately the same thing »functions may return.

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Methods Java 5.1 A quick overview of methods
Building Java Programs
Return values.
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,
Slides prepared by Rose Williams, Binghamton University Chapter 1 Getting Started 1.1 Introduction to Java.
1 Fundamental Data types Overview l Primitive Data Types l Variable declaration l Arithmetical Operations l Expressions l Assignment statement l Increment.
Chapter 6: User-Defined Functions I
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
CS 201 Functions Debzani Deb.
1 Chapter 5 Methods. 2 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Chapter 6: User-Defined Functions I
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.
Introduction to Methods
1 Interactive Applications (CLI) Interactive Applications Command Line Interfaces Project 1: Calculating BMI Example: Factoring the Solution Reading for.
Week 2 - Friday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create.
Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To.
CSC Programming I Lecture 5 August 30, 2002.
Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators, Constants, and Switching int and double)
Week 2 - Wednesday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
Week 2 - Friday.  What did we talk about last time?  Using Scanner to get input  Basic math operations.
Agenda Review C++ Library Functions Review User Input Making your own functions Exam #1 Next Week Reading: Chapter 3.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Methods (a.k.a. Functions)
Math With Java The Math Class. First, A Quick Review of Math Operators in Java Primitive Data type in Java that represent numbers: Primitive Data type.
First Programs CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
CSC Programming I Lecture 6 September 4, 2002.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
Functions Overview Functions are sequence of statements with its own local variables supports modularity, reduces code duplication Data transfer between.
More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226.
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Exam tip! str.equals(), str.startsWith(), str.toUpperCase() kbd.next(), kbd.nextLine(), etc Exam tip! str.equals(), str.startsWith(), str.toUpperCase()
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
CSCI 1226 FALL 2015 MIDTERM #1 REVIEWS.  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice, keyboards,
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
1 Project 2: Using Variables and Expressions. 222 Project 2 Overview For this project you will work with three programs Circle Paint Ideal_Weight What.
Review of CSCI 1226 More of What You Should Already Know.
Methods II Material from Chapters 5 & 6. Note on the Slides  We have started to learn how to write non- program Java files  classes with functions/methods,
Review of CSCI 1226 What You Should Already Know.
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.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
CS 106 Introduction to Computer Science I 10 / 10 / 2007 Instructor: Michael Eckmann.
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2,
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
Chapter 2 Basic Computation
Chapter 2 More on Math More on Input
Methods: Creation and Use Chapters 5 and 6
Introduction to Computer Science / Procedural – 67130
Variables, Expressions, and IO
User-Defined Functions
Chapter 2 Basic Computation
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
IFS410 Advanced Analysis and Design
Presentation transcript:

Methods Material from Chapters 5 & 6

Terminology  Method, function, procedure, subroutine  all mean approximately the same thing »functions may return values; procedures don’t »methods belong to something; subroutines may not  usually more than one term applies (is correct)  Java uses methods  but I will sometimes call them functions  especially if they return a value »like the square root function/method does

Using Methods  We’ve been using methods from the start  print and println are methods (as is printf)  nextInt, nextDouble, next, and nextLine, too  equals, equalsIgnoreCase, startsWith, and all those other things we can ask a String to do  There are also “Math” methods »math functions Java knows about  A method is something the computer can do

Math Functions  Standard functions available using Math  power function: pow System.out.println(“5 squared is ” + Math.pow(5, 2));  maximum function: max int max = Math.max(n1, n2);  square root: sqrt double root = (-b + Math.sqrt(b*b – 4*a*c)) / (2 * a);  Same form for all functions Math.functionName(arguments…)

Arguments  “Arguments” are given to the method »we also say that the method takes arguments  Math.sqrt(10) – 10 is the (only) argument »asks Math for the square root of 10  Math.pow(5, 2) – 5 and 2 are both arguments »asks Math for 5 to the power 2 (i.e. 5 2 )  arguments must be in the right order! »Math.pow(2, 5) is 2 5, not 5 2

Return Values  Methods return values »(but some don’t)  we use the function to get the returned value  Math.sqrt(10) returns the square root of 10  Math.pow(2, 5) returns 2 to the 5 th power  Math.pow(5, 2) returns 5 to the 2 nd power  Math.sqrt(x) returns the square root of x  Name of method == what value is returned

Using Math Functions  Use the function in expressions  you can print it out System.out.println(“5 squared is ” + Math.pow(5, 2));  you can save the value in a variable maxGrade = Math.max(maxGrade, grade);  you can use it in a larger math expression root = (-b + Math.sqrt(b*b – 4*a*c)) / (2 * a); »and the argument can be an expression, too!

Using Return Values  Use the function in expressions  return value used in the expression System.out.println(“5 squared is ” + Math.pow(5, 2)); »Math.pow(5, 2) returns 5 2 = 25.0 »System.out.println prints “5 squared is 25.0” root = (-b + Math.sqrt(b*b – 4*a*c)) / (2 * a); »suppose a is 1, b is 6 and c is 9 »b*b – 4*a*c = 6*6 – 4*1*9 = 36 – 36 = 0 »Math.sqrt(0) returns 0.0 »root = ( ) / (2*1) = -6.0 / 2.0 = -3.0

Some Math Functions  Trigonometric functions  sin, cos, tan »each takes an angle (measured in radians)  toDegrees, toRadians »toDegrees takes an angle measured in radians, toRadians takes an angle measured in degrees  Exponential & logarithmic functions  exp, log, sqrt »each takes a number (a double value)

Exercise  Write calls to Math functions to find  the square root of 7  6 to the 3 rd power  10 times the log of x  the log of 10 times x  the number of radians equivalent to 45 degrees  the sine of 45 degrees

More Math Methods  Larger & smaller; rounding off  max, min (each takes two numbers)  ceil, floor, round (each takes one number)  Random number (in range [0,1))  random int dieRoll1 = 1 + (int)(Math.random() * 6); int dieRoll2 = 1 + (int)(Math.random() * 6); int dice = dieRoll1 + dieRoll2; Note: random takes no arguments! That’s fine.

Rounding Off  Math.round takes a double, returns a long  Math.round(3.0)  3L »long is like int, but bigger (up to ~10 quintillion)  can’t be saved in an int variable! int rounded = Math.round(3.6); »Error: possible loss of precision  need to tell Java it’ll be smaller… int rounded = (int)Math.round(3.6); »or just work with long variables!

Exercise  Write these math expressions in Java x 5 – 1 x 5 – 1  y = x – 1  a = πr 2  z =  density = mass / volume »rounded to nearest int »mass and volume are doubles

Other Methods We’ve Seen  For reading data (kbd is a Scanner)  kbd.nextInt() kbd.nextDouble() kbd.next() kbd.nextLine()  For checking strings (resp is a String)  resp.equals(“yes”) resp.equalsIgnoreCase(“yes”) resp.startsWith(“y”) resp.toLowerCase()

Parts of a Method Call  All method calls are alike:  Math.pow(5, 7)  kbd.nextInt();  resp.equals(“yes”)  Someone.doSomething(with, these) »Someone (Math, kbd, resp, …), dot, something (pow, nextInt, equals, …), open paren, arguments (separated by commas), close paren »there may not be any arguments, but the parentheses must still be there!

Argument Types  Arguments must be the right type!  Math.pow(“fred”, true) makes no sense! »the two arguments must be numbers »doubles are OK: Math.pow(3.7, 1.98)  resp.startsWith(7) makes no sense! »the argument must be a String: resp.startsWith(“7”)  And in the right order  and there must be the right number of them! »Math.pow(5) and Math.pow(1, 2, 3) make no sense!

Exercise  Assume the calls below are correct. What argument type(s) does each method take?  Math.getExponent(3400.2)  Math.ulp(2.6)  Math.scalb(4.5, 2)  str.split(“:”, “one:two:three:four”)  str.length()  str.regionMatches(true, 0, “this”, 7, 50)

Return Types  Methods can return any kind of value »(or even none)  Math.sqrt(10) returns a double value  Math.max(3, 5) returns an int value  kbd.nextInt() returns an int value  kbd.next() returns a String value  str.toUpperCase() returns a String value  str.indexOf(“n”) returns an int value

Exercise  Assuming the code below is correct, what kind of value does each method return? double x, y = 3.2; int n = 42; String name = “Mark”; boolean good; name = name.replaceFirst(“a”, “o”); x = Math.exp(y); n = Math.getExponent(x); good = (name.equalsIgnoreCase(“mork”));

Making a Method  We have been making methods all along  main is a method  it's the "main" method of a class »the method that runs when you run a program  main method has instructions in it »so will the other methods we make  our (first) methods will return a value »like Math.pow, str.toUppercase, kbd.nextInt,... »(main doesn’t return a value)

Why Do We Make Methods?  Code Re-use  Doing “same” thing in multiple places » we do a lot of printing!  Code Hiding (Encapsulation)  Secret  Implementation independence  Code Abstraction  Top-down design

How Do Methods Work  Instructions written down in one place...  Scanner.java, String.java, Math.java, … ... call comes from some other place  MyProg.java, ExamGrades.java, …  Computer remembers where it was... ... follows instructions for the method... ... returns to where it left off

Flow of Control  You ask System.out to print “Hello”  computer stops working on your program (for a moment) & takes “Hello” to the print method  the steps of the print method are followed to completion  Hello appears on the screen  your program starts up again, right where it left off Recall: Something you send to a method (like “Hello”) is called an argument

Flow of Control  You ask kbd to get the next int  computer stops working on your program (for a moment) & starts doing the nextInt method  the steps of the nextInt method are followed to completion, getting an int from the user  that int is brought back to your program  your program starts up again, right where it left off, with the int that kbd.nextInt sent back to you Recall: Something a method sends back to you (like this int) is called a return value

Classes for Methods  Scanners know how to do input  lots of input methods  System.out knows how to print stuff  several output methods  Strings know how to do things, too  plus they keep track of some information (the letters in the string)

Creating Our Own Methods  We will write our algorithms into methods  we will create a class to hold the methods  we put that class somewhere we can find it »(in the same project!)  we will ask that class to run that algorithm  Our class keeps related methods together  can also keep related constants for us

Example Class: Converter  A class for objects that know how to convert between metric and imperial/US measurements  use it like this: double degF = Converter.fahrenheitFromCelsius(29.0); System.out.println(“29C = ” + degF + “F”); double hgtInCM = Converter.cmFromFeetInches(5, 8); System.out.println(“5’ 8\” = ” + hgtInCM + “cm”);

Compare Method Calls  Converter method fahrenheitFromCelsius double degF = Converter.fahrenheitFromCelsius(29.0);  takes a double value... ... and returns a double value  it’s like Math.sqrt double squareRootOf10 = Math.sqrt(10); »yes, I know that 10 is an int »but the computer is expecting a double, so it changes the 10 into 10.0 automatically

Compare Method Calls  Converter method cmFromFeetInches double hgtInCM = Converter.cmFromFeetInches(5, 8);  takes two int values... ...and returns a double value  kind of like Math.pow double threeToTheSeventhPower = Math.pow(3, 7); »yeah, Math.pow is expecting doubles, too! »in fact, why shouldn’t cmFromFeetInches expect inches to be a double? »Converter.cmFromFeetInches(5, 7.5) makes sense!

Method Purpose  Method has a job to do  get an int from the user  print a string on the screen  translate a temperature in Celsius to Fahrenheit  Method does its job  how it does its job is not the caller’s business (recall: code hiding)  caller should not worry about it (nor have to)

In Your Project  Put files together in one project  NetBeans will keep them in the same folder  One of the files is for your “main class”  the class that has the main function in it »remember NetBeans asking you about that?  Other file is for the non-main class  the class that doesn’t have a main function in it »I will sometimes call this a “helper class”  in our example, it’s the Converter class

Note on the Slides  All of our classes have been programs so far  now we start to write non-program classes  In order to use them, we need a program…  program asks non-program to do things  …so we need two (or more) files  program class code will be in yellow  non-program class code will be in green

Declaring Methods  Need to declare the class (just like before) public class Converter {... // methods in here //... // methods in here //}  Need to declare the methods (like before) public static (...) {.... // commands in here //.... // commands in here //} Compare: public static void main(String[] args) {... }

Method Header  First line of method says:  public static (for now!)  return type of method »int, double, String, boolean,...  name of method »fahrenheitFromCelsius, cmFromFeetInches,...  its parameters (variables for its arguments) »(double degC), (int ft, double in),... »what kind of value is it & what shall we call it? »in parentheses, separated by commas

Arguments and Parameters  Arguments are values (10, 15.4, “Hello”)  Parameters are variables  need to be declared like variables »(double degC), (int ft, double in)  only differences are: »declarations are separated by commas, not ;s »every parameter needs its own type, even if they’re all the same type: (double x, double y, double z), (int a, int b)(double x, double y, double z), (int a, int b)

Arguments and Parameters  Parameters get their values from arguments Converter.fahrenheitFromCelsius(29.0) fahrenheitFromCelsius(double degC) »degC is set equal to 29.0 Converter.cmFromFeetInches(5, 8) cmFromFeetInches(int ft, double in) »ft is set to 5, in is set to 8.0 Converter.cmFromFeetInches(7, 1.5) cmFromFeetInches(int ft, double in) »ft is set to 7, in is set to 1.5 returns how many cm 5’ 8” is (172.72) returns how many cm 7’ 1.5” is (217.17) Every time you call a function, its parameters get new values.

Converter Class Beginning  Here’s what we have so far: public class Converter { public static double fahrenheitFromCelsius(double degC) { public static double fahrenheitFromCelsius(double degC) { } public static double cmFromFeetInches(int ft, double in) { public static double cmFromFeetInches(int ft, double in) { }}  this code won’t compile »error at end of method: missing return statement

The return Command  Tells method what value to send back  the value the method returns! return 3.5;// returns a double value // return 7; // returns an int value // return “Hello!”; // returns a String value //  or, more likely, return result;  where result has the value we calculated »e.g. the number of Fahrenheit degrees

Function “Stubs”  Our methods need return commands  need to return the right kind of thing  we want to return exactly the right value  but Java doesn’t care!  So we can just put a “dummy” return in  return something so that Java doesn’t complain  worry about making it right later  we call such a function a “stub” (it’s short)

Converter Class with Stubs  Here’s what we have so far: public class Converter { public static double fahrenheitFromCelsius(double degC) { public static double fahrenheitFromCelsius(double degC) { return 0.0; return 0.0; } public static double cmFromFeetInches(int ft, double in) { public static double cmFromFeetInches(int ft, double in) { double result = 0.0; double result = 0.0; return result; return result; }}  either way of writing the stub is fine!

Position of the return Command  The return command is at the end  when function returns a value, its job is done »it will not do anything after that  so no code comes after a return command »error message: unreachable statement »another error message: missing return command  next thing after a return command must be a } »nothing else makes sense!

The Method Body  The method body is where you tell the computer how to compute the value needed »how to convert feet and inches to cm »how to convert Celsius to Fahrenheit »...  Need to know how to do it... »feet times 12 plus inches, all multiplied by 2.54 ...and translate it into Java: result = (ft * 12 + in) * 2.54;

cmFromFeetInches Body public double cmFromFeetInches(int ft, double in) { double result = 0.0; result = (12 * ft + in) * 2.54; return result; } public static final int IN_PER_FT = 12; public static final double CM_PER_IN = 2.54; We should make CONSTANTS for the numbers we’re using here… Rewrite cmFromFeetInches to use these newly declared constants...

cmFromFeetInches Body double cm = Converter.cmFromFeetInches(5, 7.5); public double cmFromFeetInches(int ft, double in) { double result = 0.0; result = (IN_PER_FT * ft + in) * CM_PER_IN; return result; } 5 ft 7.5 in 0.0 result ? cm result cm After the value has been returned, the local variables cease to exist!

Local Variables  The parameters and any variables you create inside the method body are “local”  it only makes sense to use them in the method  cannot be used outside the method »in particular, not in main!  They are, in fact, temporary variables  they only exist while the method is running »not before; not after. »created anew every time the method is called

Exercise  Write the body of fahrenheitFromCelsius  take degrees in Celsius  multiply by 9.0/5.0  add 32.0  return the result  Create constants; rewrite body to use them  DEG_F_PER_DEG_C = 9.0 / 5.0  ZERO_C_IN_F = 32.0

fahrenheitFromCelsius Body public double fahrenheitFromCelsius(double degC) { double fahrenheitDegrees, fahrenheitTemp; fahrenheitDegrees = degC * 9.0 / 5.0; fahrenheitTemp = fahrenheitDegrees ; return fahrenheitTemp; }  This body has four lines  declarations & assignment statements  return command at the end, as usual

Method Body  Anything you can do in main …  …you can do in a method  (local) variable declarations (including objects)  assignment statements  selection controls (if, if-else, if-else-if)  repetition controls (while, for)  method calls  (other things we haven’t learned about yet)

Exercises  Write Converter methods  use the constants we defined before  celsiusFromFahrenheit subtract 32, then divide by 9.0 / – 32 = 36; 36 / (9.0 / 5.0) = / 9.0 =  F = 20  C  inchesFromCM divide by / 2.54 = cm = 39.37”

Input & Output  Value-returning methods usually do NONE  common mistake is to have it ask for the value to use – but we already gave it that value fahrenheitFromCelsius(29.0)  common mistake is to have it print the answer – but what if main doesn’t want it printed? tempInCelsius = fahrenheitFromCelsius(29.0);  just do the math; leave caller to do the I/O

Badly Behaved Function  WRONG! WRONG! WRONG! WRONG! public static double fahrenheitFromCelsius(double degC) { Scanner kbd = new Scanner(System.in); System.out.print(“Enter degrees Celsius: ”); degC = kbd.nextInt(); kbd.nextLine(); double result = degC * 9.0 / ; System.out.println(degC+ “C == ” + result + “F”); return result; }  DON’T DO THIS!!!

Bad Behaviour // this version of the Converter is buggy double tempF = Converter.fahrenheitFromCelsius(0.0); System.out.println(“0.0C is ” + tempF + “F”);  What went wrong?  fahrenheitFromCelsius did I/O »user typed in 50  function returned 50  C in  F instead of 0  C Enter degrees Celsius: C == 112.0F 0.0C is 112.0F

Recall  Method calls all alike:  Someone.doSomething(with, these)  Someone is usually an object  a Scanner, a String, System.out (a PrintWriter)  but can be a class (Math)  doSomething is the name of the method  with and these are arguments to the method

Recall  Method definition is like this: public static returnType name(pType1 p1, pType2 p2) { body... body... return result; return result;}  returnType is int, or double, or String, or... »so are pType1 and pType2  name is the name of the method »p1 and p2 are the names of the parameters  body is for the commands calculating the result

Questions