Methods CSC 121 Fall 2014 Howard Rosenthal

Similar documents
Methods CSC 121 Fall 2016 Howard Rosenthal

Methods CSC 121 Spring 2017 Howard Rosenthal

C++ Programming Lecture 11 Functions Part I

CT 229 Java Syntax Continued

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

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

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

Product Price Formula extension for Magento2. User Guide

MYSQL NUMERIC FUNCTIONS

1001ICT Introduction To Programming Lecture Notes

C++ Overview. Chapter 1. Chapter 2

Custom Variables (Virtual Variables)

Introduction to Python, Cplex and Gurobi

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

Chapter 2. Outline. Simple C++ Programs


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

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

Introduction to Programming

Introduction to Engineering gii

Goals for This Lecture:

CS111: PROGRAMMING LANGUAGE II

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

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

CP122 Computer Science I. Chapter 3: Methods/Functions

Trigonometric Functions of Any Angle

Engineering Problem Solving with C++, Etter/Ingber

Repetition CSC 121 Fall 2014 Howard Rosenthal

Python Programming: An Introduction to Computer Science

Introduction to MATLAB

Programming in MATLAB

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

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

Arithmetic. 2.2.l Basic Arithmetic Operations. 2.2 Arithmetic 37

Chapter 1 Introduction to MATLAB

Introduction. What is function? Multiple functions form a larger program Modular programming

CS110: PROGRAMMING LANGUAGE I

Introduction to Computer Science and Object-Oriented Programming

Introduction to MATLAB

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

C Functions. 5.2 Program Modules in C

Introduction to PartSim and Matlab

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

Computer Science & Engineering 150A Problem Solving Using Computers

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Introduction to Programming

CIS133J. Working with Numbers in Java

Methods: A Deeper Look

Introduction to Matlab

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

Sketchify Tutorial Properties and Variables. sketchify.sf.net Željko Obrenović

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

Consider this m file that creates a file that you can load data into called rain.txt

Quick MATLAB Syntax Guide

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Variable and Data Type 2

Primitive Data Types: Intro

Using Free Functions

4. Modules and Functions

Fundamentals of Programming & Procedural Programming

A. Introduction to Function 1. Modular Programming input processing output functions library functions 2. Function 1. Benefit of Using Functions

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

Lecture 5: Methods CS2301

LAB 13: ARRAYS (ONE DIMINSION)

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

Maths Functions User Manual

ECET 264 C Programming Language with Applications

Introduction to MATLAB 7 for Engineers

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

Chapter 4: Basic C Operators

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

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

Downloaded from Chapter 2. Functions

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

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions.

Process Optimization

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

Chapter 3 Mathematical Functions, Strings, and Objects

Extending Ninox with NX

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

MobileCoach ISRII Handout

JAVA Programming Concepts

Intrinsic Functions Outline

TECH TIP VISION Calibration and Data Acquisition Software

(Type your answer in radians. Round to the nearest hundredth as needed.)

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

Chapter 6 - Notes User-Defined Functions I

AP CS Unit 3: Control Structures Notes

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

Computer Science II (20082) Week 1: Review and Inheritance

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

ME 142 Engineering Computation I. Unit 1.2 Excel Functions

CS111: PROGRAMMING LANGUAGE II

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

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

Data Types and Basic Calculation

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

Transcription:

Methods CSC 121 Fall 2014 Howard Rosenthal

Lesson Goals Understand what a method is in Java Understand Java s Math Class Learn the syntax of method construction Learn both void methods and methods that return a value Understand method overloading 2

Fundamental Definitions 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 that are repeated are often accessed via calls rather than by repeating the method over and over again System.out.println() is a method keyboard.nextint() is a method Some methods require one or more inputs Some methods generate outputs Many common methods are prepackaged and easily accessible in Java 3

A Sample Method Let s look at a simple example of a method called Math.sqrt(x) - Math is a reference to the object that contains the method - sqrt is the name of the method - x is the single parameter input into the method 4

Using Preexisting Methods Java includes many methods inside the language You only need to know the name of the method, its return type, and the parameters of the method to use it Other methods require importing the method or object that the method resides in in order to use it When calling a method the parameters are casted upward without loss of information You can t cast downward when passing parameters 5

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. (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. (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.. round(x) Rounds x up or down to the nearest integer. It rounds.5 up. sin(x) Returns the Sin of x, where x is in radians. 6

Some of these Methods are Overloaded Java allows 2 or more methods of the same class to share the same name Any overloaded method name must have different numbers or types of parameters 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 Which of the Math methods are overloaded?? 7

Some Examples Using Math Methods We will execute the MathLibraryExample program 8

Writing 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 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 is called the scope of the variable 9

The Method Header The form of a Java header is : modifiers return_type name(parameter_list) For now we just use public static as the modifiers 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 The return value in the return statement cannot be of a higher type than the return type (no casting downwards) name is the name of the method Each name begins with a small letter with subsequent words in the name beginning with a capital letter drawcoordinates parameter list is an ordered list of typed variables When the method is called values are passed to the parameter list of arguments 10

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

Calling Methods A method can be invoked from The main Program Another method If the method invoked doesn t return a value you just put the method name into a statement printy(param1, param2, ); If the method returns a value you must have a variable set up to receive the value 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)); 12

Some Simple Methods 13

More Examples CallingMethodsInSameClass.java MethodExample001 - shows overloading the println method MethodExample005 MethodExample007 Above examples found in: http://facultyfp.salisbury.edu/despickler/personal/resources/javaprogramming/handouts/ MethodExamples001.pdf 14

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 is typically void: public static void main (String[] args) 15

More on Overloading Java allows 2 or more methods of the same class to share the same name Any overloaded method name must have different numbers or types of parameters to distinguish between the methods Simple example: int max(int x, int y) and int max(int x, int y, int z) 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: int mymethod(int x) and double mymethod(int x) cannot appear in the same class 16

Programming Exercises Class Exercise 2 Celsius to Fahrenheit Write a method int ctof(int x) that converts a Celsius 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 Celsius temperatures from -40 to 100, in increments of 5 degrees, with the Fahrenheit equivalents. 17

Programming Exercises Class 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. 18

Programming Exercises - Lab 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( ). 19