methods csc 121 spring 2015 howard rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...a...

19
Methods CSC 121 Spring 2015 Howard Rosenthal

Upload: others

Post on 26-Mar-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

Methods

CSC 121

Spring 2015

Howard Rosenthal

Page 2: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

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

Page 3: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

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

Page 4: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

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 method

- x is the single parameter input into the method

4

Page 5: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

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 class 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

Page 6: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

The Math Class Methods

6

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 ex

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 xy

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.

Page 7: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

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

Page 8: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

Some Examples Using Math Methods

We will execute the MathLibraryExample program

8

Page 9: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

Writing a Method A Java method consists of a

header method block – really another program

Methods may accept arguments 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

Page 10: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

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 adata type

The return value in the return statement cannot be of a higher typethan 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

Page 11: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

Simple Structure for Building Methods in a Classpublic class MyClass

{

public static type method1(…)

{

statement;

statement;

}

---------

public static type methodn(…)

{

statement;

statement;

}

public static void main (String[] args)

{

statement;

statement;

}

}

11

Page 12: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

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;

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

Page 13: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

Some Simple Methods

13

Page 14: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

More Examples MethodExample001 - shows overloading the println method

MethodExample005

MethodExample007

Above examples found in:

http://facultyfp.salisbury.edu/despickler/personal/Resources/JavaProgramming/Handouts/

MethodExamples001.pdf

14

Page 15: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

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

Page 16: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

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

Page 17: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

Programming Exercises – Class

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.

17

Page 18: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

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

Page 19: Methods CSC 121 Spring 2015 Howard Rosenthalcsc121spring2015csudh.weebly.com/uploads/2/2/7/6/...A Java method consists of a header method block –really another program Methods may

Programming Exercises - LabExercise 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