Methods CSC 121 Fall 2016 Howard Rosenthal

Similar documents
Methods CSC 121 Spring 2017 Howard Rosenthal

Methods CSC 121 Fall 2014 Howard Rosenthal

CT 229 Java Syntax Continued

C++ Programming Lecture 11 Functions Part I


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

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

1001ICT Introduction To Programming Lecture Notes

What did we talk about last time? Examples switch statements

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

Repetition CSC 121 Fall 2014 Howard Rosenthal

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

MYSQL NUMERIC FUNCTIONS

4. Java Project Design, Input Methods

C++ Overview. Chapter 1. Chapter 2

Product Price Formula extension for Magento2. User Guide

Goals for This Lecture:

CP122 Computer Science I. Chapter 3: Methods/Functions

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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

Lecture 5: Methods CS2301

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

CEN 414 Java Programming

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

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Chapter 2. Outline. Simple C++ Programs

Full file at

Programming Exercise 7: Static Methods

Methods (Deitel chapter 6)

St. Edmund Preparatory High School Brooklyn, NY

Methods (Deitel chapter 6)

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

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

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

CS111: PROGRAMMING LANGUAGE II

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

Methods: A Deeper Look

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

Primitive Data Types: Intro

Custom Variables (Virtual Variables)

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

CS111: PROGRAMMING LANGUAGE II

Fundamentals of Programming Data Types & Methods

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

C Functions. 5.2 Program Modules in C

Lab5. Wooseok Kim

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

Computer Science is...

Computer Science & Engineering 150A Problem Solving Using Computers

LAB 13: ARRAYS (ONE DIMINSION)

Engineering Problem Solving with C++, Etter/Ingber

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

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

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

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

double float char In a method: final typename variablename = expression ;

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

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

XQ: An XML Query Language Language Reference Manual

Introduction to Computer Science and Object-Oriented Programming

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

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

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

Programming with Java

APCS Semester #1 Final Exam Practice Problems

Introduction to Python, Cplex and Gurobi

Introduction to Engineering gii

Mr. Monroe s Guide to Mastering Java Syntax

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

Lab5. Wooseok Kim

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

CIS133J. Working with Numbers in Java

CS110: PROGRAMMING LANGUAGE I

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

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

Math 144 Activity #4 Connecting the unit circle to the graphs of the trig functions

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

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

Introduction to Programming

Python Programming: An Introduction to Computer Science

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

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

Downloaded from Chapter 2. Functions

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

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

CS 302: Introduction to Programming

Introduction to Programming Using Java (98-388)

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14

Programming in MATLAB

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Functions. Systems Programming Concepts

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

Text User Interfaces. Keyboard IO plus

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Transcription:

Methods CSC 121 Fall 2016 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. 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 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 - 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 between 0 and 1. Selected based on tine 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 if you are only returning 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 value then you will get an error 15

Some Simple Methods 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 definitions 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 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 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. 24

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

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( ). 26