Methods CSC 121 Spring 2017 Howard Rosenthal

Similar documents
Methods CSC 121 Fall 2016 Howard Rosenthal

Methods CSC 121 Fall 2014 Howard Rosenthal

CT 229 Java Syntax Continued

C++ Programming Lecture 11 Functions Part I


The Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class

What did we talk about last time? Examples switch statements

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a,

The Number object. to set specific number types (like integer, short, In JavaScript all numbers are 64bit floating point

1001ICT Introduction To Programming Lecture Notes

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

4. Java Project Design, Input Methods

Product Price Formula extension for Magento2. User Guide

Lecture 5: Methods CS2301

Repetition CSC 121 Fall 2014 Howard Rosenthal

Goals for This Lecture:

CEN 414 Java Programming

MYSQL NUMERIC FUNCTIONS

C++ Overview. Chapter 1. Chapter 2

CP122 Computer Science I. Chapter 3: Methods/Functions

Custom Variables (Virtual Variables)

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Programming Exercise 7: Static Methods

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

CSC Algorithms and Data Structures I. Midterm Examination February 25, Name:

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

Fundamentals of Programming Data Types & Methods

AP CS Unit 3: Control Structures Notes

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Methods: A Deeper Look

Chapter 2. Outline. Simple C++ Programs

Introduction to Computer Science and Object-Oriented Programming

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

St. Edmund Preparatory High School Brooklyn, NY

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

APCS Semester #1 Final Exam Practice Problems

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

C Functions. 5.2 Program Modules in C

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

Full file at

Computer Science & Engineering 150A Problem Solving Using Computers

CS111: PROGRAMMING LANGUAGE II

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

Java Classes: Math, Integer A C S L E C T U R E 8

Introduction to Computer Science Unit 2. Notes

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

Introduction to Computer Science Unit 2. Notes

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Python Programming: An Introduction to Computer Science

Primitive Data Types: Intro

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

CS110: PROGRAMMING LANGUAGE I

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Lab5. Wooseok Kim

Downloaded from Chapter 2. Functions

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

CS111: PROGRAMMING LANGUAGE II

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Computer Science is...

Introduction to Programming

Introduction to Java Applications

LAB 13: ARRAYS (ONE DIMINSION)

Introduction to Python, Cplex and Gurobi

Object-Oriented Programming

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

Engineering Problem Solving with C++, Etter/Ingber

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Introduction to PartSim and Matlab

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

XQ: An XML Query Language Language Reference Manual

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

Lab5. Wooseok Kim

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Chapter 5 Methods / Functions

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

CIS133J. Working with Numbers in Java

Section 2.2 Your First Program in Java: Printing a Line of Text

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

Mr. Monroe s Guide to Mastering Java Syntax

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Programming with Java

Introduction to Engineering gii

Transcription:

Methods CSC 121 Spring 2017 Howard Rosenthal

Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods and methods that return a value Understand method overloading Write several programs using methods 2

Fundamental Defini.ons A method is a named sequence of instructions that are grouped together to perform a task pretty much the same as any other program segment. The main method is required for every application. Every application starts with a main method Other methods are accessed via calls from the main method or other methods. Examples of methods that you know System.out.println() println() is the static method which means you don t have to declare an object keyboard.nextint() keyboard is the name of the object instantiated from the class Scanner nextint() is a method Note that the format is object.method(parameter list) when accessing a method in another class or object For this chapter methods that we write will all be in one class, although we will invoke methods from other classes Typically, you need to import the class and create an object from that class before you can use the methods of the class. In a few cases, no import is required, as the class is included within the java.lang package that you get automatically Other basics Some methods require one or more inputs called parameters, others none Some methods generate outputs Many common methods are prepackaged and easily accessible in Java 3

Why Do We Use Methods We write methods to Allow for simplified and modular development Isolating the complexity of an idea, simplifies the coding challenges and nesting in the entire programming Reduce redundant code Create a modular testing environment Improve readability 4

A Sample Method Let s look at a simple example of a method called Math.sqrt(x) - Math is a reference to the class that contains the method it is a static class and is imported automatically as a part of the java.lang package - sqrt is the name of the static method - x is the single parameter input into the method 5

Using Preexis.ng Methods Java includes many methods inside the java.lang package You only need to know the name of the class and method, its return type, and the parameters of the method to use it Other methods require importing the class that the method resides in in order to use it i.e import java.util.scanner; You still need to understand the input to and output from the method One of the nicest things about creating objects is the methods you get access to When calling a method the parameters are casted upward without loss of information You can t cast downward when passing parameters So you can pass an int value if expecting a double value, but not vice-versa When these classes use static methods you don t need to create a separate object Normally you can't call a method of a class without first creating an instance of that class using new i.e. Scanner keyboard = new Scanner(System.in); By declaring a method using the static keyword, you can call it without first creating an object because it becomes a class method (i.e. a method that belongs to a class rather than an object). That is why we can use the Math class methods without creating new objects. 6

The Math Class Methods Method Description abs(x) Returns absolute value of x. acos(x) Returns arc cosine of x in radians. asin(x) Returns arc sine of x in radians. atan(x) Returns arc tan of x in radians. atan2(y, x) Counterclockwise angle between x axis and point (x,y). ceil(x) Returns the smallest integer greater than or equal to x as a double. (round up). cos(x) Returns cosine of x, where x is in radians. exp(x) Returns e x floor(x) Returns the largest integer less than or equal to x as a double. (round down) log(x) Returns the natural logarithm (base E) of x. max(a, b) Returns the larger of a and b. min(a, b) Returns the lesser of a and b. pow(x, y) Returns x y random() Returns a pseudorandom number greater than or equal to 0.0 and less than 1.0. Selected based on time of day round(x) Rounds x up or down to the nearest integer as a long. It rounds.5 up. sin(x) Returns the sin of x, where x is in radians. 7

Some of these Methods are Overloaded Java allows 2 or more methods of the same class to share the same name this is called overloading Any overloaded method name must have a different number of parameters or different parameter types to distinguish between the methods Examples public static double min(double x, double y) public static int min(int x, int y) In both of these cases you make a call using the method min, but the results are different Is their another Math method that is overloaded?? 8

Some Examples Using Math Methods We will execute the MathLibraryExample.java program 9

Wri.ng a Method A Java method consists of a header method block really another program Methods may accept arguments A method may return a value A method may be used as part of an expression Every method that returns a value has a return statement in the method block A return statement returns the value in that statement return sum; return true; return; // if there is no return value A return statement terminates the method A method may have more than one return statement If no value is being returned, you don t need the return statement you return at the end of the method Variables declared inside a method are called local variables. They are only valid while the method is being executed and only work inside the method This includes the variables declared in the method This is another example of the scope of variables 10

The Method Header (1) The form of a Java method header is : modifiers return_type name(parameter_list) For now we just use public static as the modifiers this allows us to access the methods in the class directly return_type is the type of data that will be returned If no value will be returned this will use the word void instead of a data type Obviously the main method has no return type (that s why it s return value is void) The return value in the return statement cannot be of a higher type than the return type (no casting downwards) The return value can be a reference variable Only one value may be returned name is the name of the method By convention each name begins with a small letter with subsequent words in the name beginning with a capital letter drawcoordinates 11

The Method Header (2) The form of a Java method header is : modifiers return_type name(parameter_list) parameter list is an ordered list of typed variables The parameter list is a set of individually typed parameter in a specific order When the method is called values are passed to the parameter list of arguments The type can be a primitive variable or an object reference variable Examples of parameter lists: (boolean b1) (int x, double y) () (boolean x2, char c2) 12

Simple Structure for Building Methods in a Class public class MyClass { public static type method1( ) { statement; statement; } --------- public static type methodn( ) { } statement; statement; } public static void main (String[] args) { statement; } statement; We usually put the main method last Note that all the methods are inside the class 13

Calling Methods A method can be invoked from The main method Another method If the method invoked doesn t return a value you just put the method name into a statement System.out.println( An example without a return value ); When there is no return value the method should be doing something If the method returns a value you must have a variable set up to receive the value (assignment statement) or have the method somewhere else where the value can be used y = Math.sqrt(x); System.out.println( The square root of y is + Math.sqrt(x)); 14

Formal and Actual Parameters The formal parameters are the parameters found in the method header statement. They are reinitialized each time the method is called (invoked) The scope of these parameters is the method in which they are invoked Actual parameters are the parameters used when calling the method All actual parameters must evaluate to a value of the proper type before the method is called If there is an uninitialized actual parameter then you will get an error 15

Some Simple Methods N/2 16

More Examples MethodExample001 MethodExample005 MethodExample007 Above examples found in: http://facultyfp.salisbury.edu/despickler/personal/resources/javaprogramming/handouts/ MethodExamples001.pdf 17

void Methods A void method is a method that doesn t return a value The return statement is simply: return; You can use a void method to print out a graph or a figure based on the input, without returning anything. The main program has a void return value: public static void main (String[] args) Don t create an overloaded method with the name main 18

More on Overloading Java allows 2 or more methods of the same class to share the same name Any overloaded method name must have a different number of parameters or at least one parameter of a different type (in the same parameter position) to distinguish between the methods Simple example with different number of parameters: public static int max(int x, int y) public static int max(int x, int y, int z) Simple example with at least one parameter of a different type : public static int max(int x, int y) public static int max(int x, double y) Warning: It is not legal to overload a method by having two identical methods (same name and number of variables of the same type in the same order) with different return types: public static int mymethod(int x) and public static double mymethod(int x) cannot appear in the same class 19

Global Variables and Scope You can create global variables for a class They are created within the scope of the class You need to place them inside the scope of the class but not inside any method otherwise they are only valid for that method They should be declared as static within the class, and we will just declare them as public static Here is a fragment: import java.util.scanner; //Using the scanner public class PriceAdjustment { public static Scanner keyboard = new Scanner(System.in); public static int bumpme(int price, int increase, boolean updown) { 20

Summary of the Rules on Scope The scope of a parameter declaration is the body of the method in which the declaration appears it only exists as long as the method is executing The scope of a local-variable declaration is from the point at which the declaration appears to the end of the block The scope of a local-variable declaration that appears in the initialization section of a for statement s header is the body of the for statement and the other expressions in the header A method or field s scope is the entire body of the class. This enables a class s instance methods to use the fields and other methods of the class (note: fields are discussed next semester) Remember any block may contain variable declarations 21

Summary on Calling and Using Methods There are three ways to call a method Using a method s name by itself to call another method in the same class when the method is static Using a variable that contains a reference to an object, foll0wed by a dot. This is done for non-static methods int x = keyboard.nextint(); Next semester you will learn to create your own classes with non-static methods Using the class name and a dot to call a static method of a class double z = Math.sqrt(variable); 22

Programming Exercises Class (1) Exercise 2 Centigrade to Fahrenheit Write a method int ctof(int x) that converts a Centigrade temperature to a Fahrenheit temperature. The conversion formula is: F= (9.0/5.0)*C + 32 The returned value should be rounded to the nearest degree. Test your method by displaying a table of Centigrade temperatures from -40 to 100, in increments of 5 degrees, with the Fahrenheit equivalents. 23

Programming Exercises Class (2) Exercise 15 Geometric Mean A home purchased for 300,000 dollars increases in value by 10% after one year and by another 20% after a second year. Thus, a year after purchasing the house, its value is 1.10*300,000 dollars and after two years 1.20*1.10*300,000 dollars. A third year decrease of 6% drops the value to 94% of the previous value. 0.94*1.20*1.10*300000 = 372240 dollars. Notice that the multiplier is 1-0.06 = 0.94. The average annual increase over the three-year period is the geometric mean of 1.10, 1.20 and 0.94. In general, the geometric mean of n numbers is the nth root of their product. Thus, the geometric mean of 1.10, 1.20, and.94 is (1.10*1.20*.94) 1/3 = 1.074568 and the product 1.074568*1.074568*1.074568*300000 equals 372240, as does the original product,.94*1.20*1.10*300000. In other words, the home s value after three annual changes of 10%, 20%, and 6% is the same as if, each year, the home s value increased by 7.4568%. Write a program that calculates the average increase or decrease on an investment held from one to six years. Your program should first prompt for the length of time of the investment (an integer between 1 and 6, inclusive) and then the percent increase or decrease for each year. A negative number indicates a decrease. The program should display the average annual increase or decrease. For example, if a home, over a six-year period, has changed in value by 10%, 20%, 6%, 8%, 12%, and 3%, then to compute the average annual increase (or decrease), you would calculate the geometric mean of 1.1, 1.2, 1.06, 0.92, 0.88, and 1.03. Hints: Overload a method, geometricmean( ). Make five versions that have two, three, four, five, and six parameters of type double. Use Math.pow(x,y). 24

Sample SoluMons for Class Exercise 2 Geometric Mean 1 5-1.05 2 5 5 1.05 3 5 10 15 1.0992419018963262 4-5 10-15 20-1.016082836863058 5 2 4 6 8 10-1.0596224801684886 6 1-1 9 19 32-8 - 1.078653518313325 25

Programming Exercises Class (3) Exercise 6 Price Adjustment Write a method int bumpme(int price, int increase, boolean updown) that accepts a price in dollars and returns a new price rounded to the nearest dollar, after increasing or decreasing the price by increase percent. If updown is true then you should increase the price; otherwise decrease the price. Write an appropriate main method to test the method. 26

Programming Exercises Lab (1) Exercise 3 Random Numbers Write a method int randomint(int x, int y) that returns a random integer between x and y, inclusive. x and y can be positive or negative. Remember: Math.random() returns a value greater than or equal to o and less yjan 1 of type double. 27

Programming Exercises Lab (2) Exercise 5 Consumer Price Index The Consumer Price Index (CPI) represents the change in the prices paid by urban consumers for a representative basket of goods and services. It is a percentage value rounded to the nearest tenth, for instance 9.2 or -0.7. Write a method double getcpi() that asks a user to enter a number between -20 and 20 with one number after the decimal point. If the user supplies an unacceptable number the method should display an appropriate message ( number is too high, number is too low, number has wrong precision. and prompt the user for another value. When the user succeeds the method should return the number. Test your number by continually prompting a user for a value and displaying the value. When you are confident that the method is correct write a second method double inflation(double cpi, double expenses) that accepts the CPI and last year's annual expenses. Method inflation( ) returns what you might expect to pay for the same goods in the coming year. Write a main method that calls both getcpi() and inflation( ). 28