cop3502 programming fundamentals for cis majors 1

Post on 20-Feb-2016

45 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi. Chapter 4 Loops for w hile do-while. Chapter 5 Methods Input arguments Output O verloading Code reusability Scope of variables. Methods. - PowerPoint PPT Presentation

TRANSCRIPT

COP3502 Programming Fundamentals for CIS Majors 1

Instructor: Parisa Rashidi

Chapter 4 Loops

forwhiledo-while

Last Week

Chapter 5 Methods

Input argumentsOutputOverloading

Code reusability Scope of variables

Objectives

Methods

Suppose we want to write a program to find the sum of integers from 1 to 10 from 20 to 30 from 35 to 45

Motivation

Obvious solution

Naïve Solution

int sum = 0;for (int i = 1; i <= 10; i++) sum += i;System.out.println("Sum from 1 to 10 is " + sum);

sum = 0;for (int i = 20; i <= 30; i++) sum += i;System.out.println("Sum from 20 to 30 is " + sum);

sum = 0;for (int i = 35; i <= 45; i++) sum += i;System.out.println("Sum from 35 to 45 is " + sum);

What about some refactoring?

Refactor

int sum = 0;for (int i = 1 ; i <= 10; i++) sum += i;System.out.println("Sum from 1 to 10 is " + sum);

sum = 0;for (int i = 20; i <= 30; i++) sum += i;System.out.println("Sum from 20 to 30 is " + sum);

sum = 0;for (int i = 35; i <= 45; i++) sum += i;System.out.println("Sum from 35 to 45 is " + sum);

x

x

x

y

y

y

x y

x y

x y

A better approach is to use a method

Solution

public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;}

modifier outputname

input

Methodbody

First, a method should be definedThen we can use the method

i.e. calling or invoking a method

Invoking a Method

public static void main(String[] args) { int total1 = sum(1, 10); int total2= sum(20, 30); int total3 = sum(35, 45); int total4 = sum(35,1000);}

When calling a method within the same class, we directly call the method

Invoking a Method

public class TestClass{ public static void main(String[] args) { int total1 = sum(1, 10);}//----------------------------------------------public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;}

}

calling directly

When calling a method from another class, use class name if a static method

Invoking a Method

public class TestClass{ public static void main(String[] args) { int total1 = AnotherClass .sum(1, 10); }

}Class name

public class AnotherClass{ public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;}

}

When calling a method from another class, use class name if a static method

Invoking a Method

public class TestClass{ public static void main(String[] args) { AnotherClass a = new AnotherClass(); int total1 = a.sum(1, 10); }

} Instance name

public class AnotherClass{ public int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;}

}

Method is A collection of statements grouped together

to perform an operation To use a method

We invoke the method E.g. int result = sum(1,10);

So…

Method signature Combination of the method name and the

parameter list

Method Signature

public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;}

signature

Method header

Parameters

Parameters

public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;}

Formal parameter

public static void main(String[] args) { int total1 = sum(1, 10);} Actual parameter

Formal parameters: Variables defined in the method header

Actual parameters:When a method is invoked, you pass a

value to the parameter. This value is referred to as actual parameter or argument.

Parameters

If the method does not return a value, the “return type” is the keyword void. It means “nothing” will be returned

A method may return a value: Use return keyword to return the value…

E.g. return sum; “return” keyword is required if return type is

anything other than void

Output

A return statement is not required for a void method. return still can be used for terminating

the method This is not often done

Tip

Use “return” only once in a method! Easier to debug and trace

Programming Style

public int max(int x, int y) {  if (x > y) return x; else return y; }

public int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;} One exit point:

This is better

Two exit points

This program demonstrates calling a method max to return the largest value among a set of values.

Program

TestMax Run

Passing arguments

Program

public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

Program Trace

public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

i is now 5

Program Trace

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

j is now 2

Program Trace

public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

invoke method max(i,j)

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

Program Trace

public static void main(String[] args){ int i = 5; int j = 2; int k = max(i, j); }

pass the value of i to xpass the value of j to y

Program Trace

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

Declare variable result

Program Trace

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

(x > y) is true because (5 > 2)

Program Trace

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

result is now 5

Program Trace

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

return result which is 5

Program Trace

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

return max(i, j) and assign the return value to k

Program Trace

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

finished

Methods reduce redundant coding and enable code reuse.

Methods modularize code and improve the quality of the program.

Modularizing Code

PrimeNumberMethod

Run

Chapter 5 Methods

Input arguments Output

Previously

Methods Overload …

Memory management

Today

Write a method that converts a decimal integer to a hexadecimal.

Program

Decimal2HexConversion Run

Converting a decimal number x (e.g. 74) into a hexadecimal number (e.g. 4A) 1. Divide x by 162. Save remainder and quotient3. Repeat step 1 and 2 until quotient is 04. Form the hexadecimal number from remainders

(the most recent remainder will be the leftmost digit)

Program Explained

Memory & Methods

A data structure Last in, first out (LIFO) Two basic operation

Pop Push

Stack

xYZ

Push Pop

How memory is arranged1. Registers

Inside the processor, very limited, you have no direct access

2. RAM Stack memory

Inside RAM, very fast, lifetime of objects should be known, all primitive variables placed here

Heap memory Inside RAM, reference values placed here

3. Constant values Will be directly replaced in code

Memory

Revisiting Program

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

Each time a method is called, the system stores parameters and variables in stack memory.

How memory is managed?

Memory

Space required for

main method:

k:i:5j:2

Space required for

main method:

k:i:5j:2

Space required for

main method:

k:i:5j:2

Space required for

main method:

k: 5i:5j:2

Stackis empty

Space required for

maxmethod:

x:5y:2

Space required for

maxmethod:

Result: 5x:5y:2

What about reference types? E.g. Random r = new Random();

Pass by Reference

Space required for main method:

r(reference)

Stack Memory Heap Memory

Actual Object

What about reference types? E.g. Random r = new Random();

Pass by Reference

Space required for main method:

r(reference)

Stack Memory Heap Memory

Actual Object

Space required for

testmethod:

x

If primitive types are passed Value is passed Changes inside method will not affect the

variable outside the method If a reference type is passed

Reference is passed (address of memory location containing actual object)

Changes inside the method will affect the variable

Passing Arguments

Method Overload

Different versions of the same method accepting different arguments

Method Overload

TestMethodOverloading Run

Method overload is only based on input arguments

Method overload can not be based on different output values

Method overload cannot be based on different modifiers

Tip

Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match.

This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error.

Method Overload

Ambiguous invocation

public class AmbiguousOverloading { public static void main(String[] args) { System.out.println(max(1, 2)); }  public static double max(int num1, double num2) { double result = 0; if (num1 > num2) result = num1; else result = num2; return result; } public static double max(double num1, int num2) { double result = 0; if (num1 > num2) result = num1; else result = num2; return result; }}

Variable Scope

Scope: Part of the program where the variable

can be referenced.A local variable:

A variable defined inside a method. The scope of a local variable starts from

its declaration and continues to the end of the block that contains the variable.

Variable Scope

A variable declared in the initial action part of a for loop has its scope in the entire loop.

A variable declared inside a for loop body has its scope limited in the loop body from its declaration and to the end of the block.

Variable Scope

public static void method1() { . . for (int i = 1; i < 10; i++) { . . int j; . . . } }

The scope of j

The scope of i

You can declare a local variable with the same name multiple times in different non-nesting blocks in a method

You cannot declare a local variable twice in nested blocks.

Variable Scope

A variable declared in a method

Variable Scope

public static void method1() { int x = 1; int y = 1;

for (int i = 1; i < 10; i++) {

x += i; }

for (int i = 1; i < 10; i++) {

y += i; } }

It is fine to declare i in two non-nesting blocks public static void method2() {

int i = 1; int sum = 0;

for (int i = 1; i < 10; i++) {

sum += i; } }

It is wrong to declare i in two nesting blocks

Method Abstraction

You can think of the method body as a black box that contains the detailed implementation for the method.

Abstraction

Method Header

Method body Black Box

Optional arguments for Input

Optional return value

Write a method once and reuse it anywhere.

Hide the implementation from the user. Change it without affecting the user

Reduce complexity.

Method Benefits

Example Math class provides many methods Trigonometric Methods Exponent Methods Rounding Methods min, max, abs, and random Methods

Method Benefits

HW4 due todayHW5 postedMonday: homework review session

Agenda

Chapter 5 Code reusability & program design

Objectives

When writing a large program, you can use the “divide and conquer” strategy, also known as stepwise refinement, to decompose it into sub-problems.

The sub-problems can be further decomposed into smaller, more manageable problems.

Stepwise Refinement

Main Task

Task 1

Task 1-1

Task 1-2

Task 2

Task 3

An example to demonstrate the stepwise refinement approach:

Stepwise Refinement

PrintCalendar Run

Stepwise Refinement

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Stepwise Refinement

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Stepwise Refinement

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Stepwise Refinement

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Stepwise Refinement

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Stepwise Refinement

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Top-down approach is to implement one method in the structure chart at a time from the “top to the bottom”.

Implement the main method first and then use a stub for each one of the methods.

Stubs can be used for the methods waiting to be implemented.

A stub is a simple but incomplete version of a method.

The use of stubs enables you to test invoking the method from a caller.

Top Down Design

A Skeleton for printCalendar

Bottom-up approach is to implement one method in the structure chart at a time from the “bottom to the top”.

For each method implemented, write a test program to test it.

Bottom Up Design

Both top-down and bottom-up methods are fine.

Both approaches implement the methods incrementally and help to isolate programming errors and makes debugging easy.

Sometimes, they can be used together.

Comparison

An example to demonstrate the stepwise refinement approach:

Program Revisited

PrintCalendar Run

As introduced before, each character has a unique Unicode between 0 and FFFF in hexadecimal (65535 in decimal). To generate a random character is to generate a random integer between 0 and 65535. The Unicode for lowercase letters are consecutive integers starting from the Unicode for 'a', then for 'b', 'c', ..., and 'z'. A random character between any two characters ch1 and ch2 with ch1 < ch2 can be generated as follows:

Random r = new Random();char x = ch1 + r.nextInt(ch2 – ch1 + 1)

Program

Random character generator

Program

TestRandomCharacter

Run

RandomCharacter

Math Class

Class constants: PI E

Class methods: Trigonometric Methods Exponent Methods Rounding Methods min, max, abs, and random Methods

Math Class

Trigonometric methods sin(double a) cos(double a) tan(double a) acos(double a) asin(double a) atan(double a)

Math Class

Examples:

Math.sin(0) returns 0.0 Math.sin(Math.PI / 6) returns

0.5 Math.sin(Math.PI / 2) returns

1.0Math.cos(0) returns 1.0Math.cos(Math.PI / 6)

returns 0.866 Math.cos(Math.PI / 2)

returns 0

Exponent methods exp(double a)

Returns e raised to the power of a. log(double a)

Returns the natural logarithm of a. log10(double a)

Returns the 10-based logarithm of a. pow(double a, double b)

Returns a raised to the power of b. sqrt(double a)

Returns the square root of a.

Math Class

Rounding methods double ceil(double x)

x rounded up to its nearest integer. This integer is returned as a double value.

double floor(double x)x is rounded down to its nearest integer. This integer is returned as a double value.

double rint(double x)x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double.

int round(float x)Return (int)Math.floor(x+0.5).

long round(double x)Return (long)Math.floor(x+0.5).

Math Class

Rounding examplesMath.ceil(2.1) returns 3.0 Math.ceil(2.0) returns 2.0Math.ceil(-2.0) returns –2.0Math.ceil(-2.1) returns -2.0Math.floor(2.1) returns 2.0Math.floor(2.0) returns 2.0Math.floor(-2.0) returns –2.0Math.floor(-2.1) returns -3.0Math.rint(2.1) returns 2.0Math.rint(2.0) returns 2.0Math.rint(-2.0) returns –2.0Math.rint(-2.1) returns -2.0Math.rint(2.5) returns 2.0Math.rint(-2.5) returns -2.0Math.round(2.6f) returns 3 Math.round(2.0) returns 2 Math.round(-2.0f) returns -2

Math.round(-2.6) returns -3

Math Class

Min, max, etc max(a, b) and min(a, b)

Returns the maximum or minimum of two parameters.

abs(a)Returns the absolute value of the parameter.

random()Returns a random double valuein the range [0.0, 1.0).

Math Class

random method Generates a random double value greater than

or equal to 0.0 and less than 1.0 (0 <= Math.random() < 1.0).

Math Class

(int)(Math.random() * 10) Returns a random integer

between 0 and 9.

50 + (int)(Math.random() * 50) Returns a random integer between 50 and 99.

a + Math.random() * b Returns a random number between

a and a + b, excluding a + b.

top related