CS115 Principles of Computer Science

Similar documents
Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

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

Chapter 6 Methods. Dr. Hikmat Jaber

Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Chapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 5 Methods / Functions

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

Chapter 6: Methods. Objectives 9/21/18. Opening Problem. Problem. Problem. Solution. CS1: Java Programming Colorado State University

Benefits of Methods. Chapter 5 Methods

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.

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

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Methods. CSE 114, Computer Science 1 Stony Brook University

JAVA Programming Concepts

Lecture 5: Methods CS2301

CS110: PROGRAMMING LANGUAGE I

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

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

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

Lecture #6-7 Methods

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

CS-201 Introduction to Programming with Java

CS1150 Principles of Computer Science Methods

CS-201 Introduction to Programming with Java

CS1150 Principles of Computer Science Methods

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Top-down programming design

Chapter 4. Mathematical Functions, Characters, and Strings

12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Chapter 4 Mathematical Functions, Characters, and Strings

Methods. Eng. Mohammed Abdualal

AP CS Unit 3: Control Structures Notes

CS171:Introduction to Computer Science II

COMP 111 PROGRAMMING I MODULARITY USING FUNCTIONS

Advanced Computer Programming

CS115 Principles of Computer Science

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

A Foundation for Programming

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

CS1150 Principles of Computer Science Methods

Lecture 1 Java SE Programming

M e t h o d s a n d P a r a m e t e r s

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Methods with Parameters and Return Values

CONDITIONAL EXECUTION

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

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

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Functions. x y z. f (x, y, z) Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing)

Variable Scope. The variable scope is the range of the program where the variable can be referenced.

Introduction to Programming (Java) 4/12

Place your name tag here

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

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

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

Chapter 3 Selection Statements

Java Tutorial. Saarland University. Ashkan Taslimi. Tutorial 3 September 6, 2011

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

The return Statement


More on methods and variables. Fundamentals of Computer Science Keith Vertanen

Module 4: Characters, Strings, and Mathematical Functions

CS110D: PROGRAMMING LANGUAGE I

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Methods CSC 121 Spring 2017 Howard Rosenthal

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

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

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

1.00 Lecture 5. Floating Point Anomalies

Procedural Abstraction and Functions That Return a Value. Savitch, Chapter 4

Module 7: Arrays (Single Dimensional)

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

Eng. Mohammed S. Abdualal

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Arithmetic Compound Assignment Operators

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

x++ vs. ++x x=y++ x=++y x=0; a=++x; b=x++; What are the values of a, b, and x?

CT 229 Java Syntax Continued

Methods CSC 121 Fall 2016 Howard Rosenthal

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Introduction to programming using Python

Course Outline. Introduction to java

Introduction to Software Development (ISD) Week 3

Using Java Classes Fall 2018 Margaret Reid-Miller

Methods: A Deeper Look

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

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Transcription:

CS115 Principles of Computer Science Chapter 5 Methods Prof. Joe X. Zhou Department of Computer Science CS115 Methods.1 Re: Objectives in Loops Sequence and selection aside, we need repetition (loops) To use while, do-while, and for loop statements to control the repetition of statements To understand the flow of control in loop statements To use Boolean expressions to control loop statements To write nested loops To know the similarities and differences of three types of loops To implement program control with break and continue CS115 Methods.2

Objectives in Methods To declare methods, invoke methods, and pass arguments to a method To use method overloading and know ambiguous overloading To determine the scope of local variables To learn the concept of method abstraction To know how to use the methods in the Math class To design and implement methods using stepwise refinement CS115 Methods.3 What is a Method? A method is a collection of statements that are grouped together to perform an operation (for reuse). System.out.println( Hello World! ); String input = JOptionPane.showInputDialog( Enter the number: ); Example: create a method to find which of two integers is bigger. Define a method Invoke a method modifier return value type method name formal parameters method header public static int max(int num1, int num2) { int z = max(x, y); method body int result; if (num1 > num2) result = num1; result = num2; return result; return value parameter list actual parameters (arguments) CS115 Methods.4

Two Method Types Query: A method may return a value. The returnvaluetype is the data type of the value the method returns Example: public static int max(int num1, int num2) int maxvalue = max(number1, number2); String input = JOptionPane.showInputDialog( Enter the number: ); Command: A method does not return a value, the returnvaluetype is the keyword void. Example: public static void main(string[] args) System.out.println( Hello World! ); (1) Every parameter in a method must be declared to be of some specific data type (2) Every Java method must have a specific type that it returns CS115 Methods.5 void Methods Listing 5.2 Print the grade for a given score public class Instructor { public static void main(string[] args) { printgrade(78.5); CS115 Methods.6 public static void printgrade(double score) { if (score >= 90.0) { System.out.println('A'); if (score >= 80.0) { System.out.println('B'); if (score >= 70.0) { System.out.println('C'); if (score >= 60.0) { System.out.println('D'); { System.out.println('F');

nonvoid Methods Listing 5.1 Testing the max method public class TestMax { /** Main method */ public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println("The maximum between " + i + " and " + j + " is " + k); /** Return the max between two numbers */ public static int max(int num1, int num2) { int result; CS115 Methods.7 if (num1 > num2) result = num1; result = num2; return result; // how to simplify it using the conditional operator? TestMax Calling Methods, cont. i is now 5; tracing pass the value of i pass the value of j public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; result = num2; return result; Caution: the actual arguments must match the parameters in order, number, and compatible types, as defined in the method signature. * Can the arguments of a method have the same name as its parameters? CS115 Methods.8

CAUTION A return statement is required for a nonvoid method. The following method is logically correct, but it has a compilation error, because the Java compiler thinks it possible that this method does not return any value. public static int sign(int n) { if (n > 0) return 1; if (n == 0) return 0; if (n < 0) return 1; To fix this problem, delete if (n < 0) in the code. The compiler can see a return statement to be reached regardless of the if comparison. CS115 Methods.9 Call Stacks pass the value of i pass the value of j public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; result = num2; return result; Space required for the max method result: 5 num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 Space required for the main method k: j: 2 i: 5 Space required for the main method k: 5 j: 2 i: 5 Stack is empty CS115 Methods.10 The main method is invoked. The max method is invoked. The max method is finished and the return value is sent to k. The main method is finished.

Passing Parameters public static void nprintln(string message, int n) { for (int i = 0; i < n; i++) System.out.println(message); Suppose you invoke the method using nprintln( Welcome to Java, 5); What is the output? Suppose you invoke the method using nprintln( Computer Science, 15); What is the output? CS115 Methods.11 CS115 Methods.12 Pass by Value in Java Listing 5.2 Testing Pass by value; swap two integer values public class TestPassByValue { /** Main method */ public static void main(string[] args) { // Declare and initialize variables int num1 = 1; int num2 = 2; System.out.println("Before method invoking, num1 is " + num1 + " and num2 is " + num2); swap(num1, num2); // invoke the swap method System.out.println("After method invoking, num1 is " + num1 + " and num2 is " + num2); /** Swap two variables */ What output you expect? public static void swap(int n1, int n2) { System.out.println("\tInside the swap method"); System.out.println("\t\tBefore swapping n1 is " + n1 + " n2 is " + n2); // Swap n1 with n2 int temp = n1; n1 = n2; n2 = temp; System.out.println("\t\tAfter swapping n1 is " + n1 + " n2 is " + n2);

Stack of the Pass by Value The values of num1 and num2 are passed to n1 and n2. Executing swap does not affect num1 and num2. Space required for the swap method temp: n2: 2 n1: 1 Space required for the main method num2: 2 num1: 1 Space required for the main method num2: 2 num1: 1 Space required for the main method num2: 2 num1: 1 Stack is empty The main method is invoked The swap method is invoked The swap method is finished The main method is finished What we can do in Java? CS115 Methods.13 Overloading Methods method overloading: two methods have the same name but different parameter lists within one class (make program more readable) public static int max(int num1, int num2) { if (num1 > num2) return num1; return num2; public static double max(double num1, double num2) { if (num1 > num2) return num1; return num2; Public static double max(double num1, double num2, double num3) { return max(max(num1, num2), num3); How the compiler determines which one to use? * caution: we cannot overload methods based on return type or modifiers. CS115 Methods.14

Ambiguous Invocation ambiguous invocation : there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match; a compilation error. public class AmbiguousOverloading { public static void main(string[] args) { System.out.println(max(1, 2)); public static double max(int num1, double num2) { if (num1 > num2) return num1; return num2; CS115 Methods.15 public static double max(double num1, int num2) { if (num1 > num2) return num1; return num2; Scope of Local Variables The scope of a variable: the part of the program where the variable can be referenced/accessed 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. A local variable must be declared before it can be used. public static void method1() { int k;.. for (int i = 1; i < 10; i++) {.. int j;... What is the scope of k? What is the scope of i? What is the scope of j? CS115 Methods.16

Scope of Local Variables, cont. You can declare a local variable with the same name multiple times in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks. It is fine to declare i in two non-nesting blocks 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 wrong to declare i in two nesting blocks public static void method2() { int i = 1; int sum = 0; for (int i = 1; i < 10; i++) sum += i; CS115 Methods.17 The Math Class Class constants: PI E (the base of natural logarithms) Class methods (static): Exponent Methods Rounding Methods min, max, abs, and random Methods and more All Math methods are static methods (vs. instant methods) CS115 Methods.18

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. Examples: Math.exp(1) returns 2.71 Math.log(2.71) returns 1.0 Math.pow(2, 3) returns 8.0 Math.pow(3, 2) returns 9.0 Math.pow(3.5, 2.5) returns 22.91765 Math.sqrt(4) returns 2.0 Math.sqrt(10.5) returns 3.24 CS115 Methods.19 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. CS115 Methods.20

min, max, and abs max(a, b)and min(a, b) Overloaded methods; return the maximum or minimum of two parameters (int, long, float, or double). abs(a) Returns the absolute value of the parameter. random() Returns a random double value in the range [0.0, 1.0); excluding 1.0 How to generate random numbers, say 0 ~ 9; 0 ~ 10; 50 ~ 100; a ~ a + b? Tips: (int) (Math.random() * 10) (int) (Math.random() * 11) 50 + (int) (Math.random() * 50) a + Math.random() * b You can view the complete documentation for the Math class online from http://java.sun.com/j2se/1.5.2/docs/api/index.htm. CS115 Methods.21 Method Abstraction You can think of the method body as a black box that contains the detailed implementation for the method. Optional arguments for Input Optional return value Method Signature Method body Black Box Benefits of methods Write a method once and reuse it anywhere. Information hiding. Hide the implementation from the user. Reduce complexity. CS115 Methods.22

Reuse Methods from Other Classes NOTE: One of the benefits of methods is for reuse. The max method can be invoked from any class besides TestMax. If you create a new class Test, you can invoke the max method using ClassName.methodName (e.g., TestMax.max). If you create a new class Grader, you can invoke the printgrade method using Instructor.printGrade. Note that those methods must be defined using public static modifiers (called static methods) CS115 Methods.23 Re: void Methods Listing 5.2 Print the grade for a given score public class Instructor { public static void main(string[] args) { printgrade(78.5); * Method abstraction is crucial to programming and problem solving. public static void printgrade(double score) { if (score >= 90.0) { System.out.println('A'); if (score >= 80.0) { System.out.println('B'); if (score >= 70.0) { System.out.println('C'); if (score >= 60.0) { System.out.println('D'); { System.out.println('F'); CS115 Methods.24 printgrade() implementation can be changed by the instructor; but a grader can reuse it as long as the method signature is the same.

Case Study: Generating Random Characters public class RandomCharacter { /** Generate a random character between ch1 and ch2 */ public static char getrandomcharacter(char ch1, char ch2) { return (char)(ch1 + Math.random() * (ch2 - ch1 + 1)); /** Generate a random lowercase letter */ public static char getrandomlowercaseletter() { return getrandomcharacter('a', 'z'); /** Generate a random uppercase letter */ public static char getrandomuppercaseletter() { return getrandomcharacter('a', 'Z'); /** Generate a random digit character */ public static char getrandomdigitcharacter() { return getrandomcharacter('0', '9'); /** Generate a random character */ public static char getrandomcharacter() { return getrandomcharacter('\u0000', '\uffff'); CS115 Methods.25 Case Study: Method Reuse public class TestRandomCharacter { /** Main method */ public static void main(string args[]) { final int NUMBER_OF_CHARS = 175; final int CHARS_PER_LINE = 25; // Print random low case characters between a' and z', 25 chars per line for (int i = 0; i < NUMBER_OF_CHARS; i++) { char ch = RandomCharacter.getRandomLowerCaseLetter(); if ((i + 1) % CHARS_PER_LINE == 0) System.out.println(ch); System.out.print(ch); How to compile and run an application with multiple classes? CS115 Methods.26

Stepwise Refinement (Reading) The concept of method abstraction can be applied to the process of developing programs. When writing a large program, you can use the divide and conquer strategy, also known as stepwise refinement, to decompose it into subproblems. The sub-problems can be further decomposed into smaller, more manageable problems. CS115 Methods.27 PrintCalender Case Study Let us use the PrintCalendar example to demonstrate the stepwise refinement approach. CS115 Methods.28

Design Diagram printcalendar (main) readinput printmonth printmonthtitle getmonthname printmonthbody getstartday Top-Down or Bottom-Up gettotalnumofdays getnumofdaysinmonth isleapyear CS115 Methods.29 Package There are three reasons for using packages: To avoid naming conflicts. When you develop reusable classes to be shared by other programmers, naming conflicts often occur. To prevent this, put your classes into packages so that they can be referenced through package names. To distribute software conveniently. Packages group related classes so that they can be easily distributed. To protect classes. Packages provide protection so that the protected members of the classes are accessible to the classes in the same package, but not to the external classes. Putting classes into a package: package packagename; Using classes in a package: import javax.swing.*; import javax.swing.joptionpane; CS115 Methods.30

Exercise: Computing the sum of a geometric series suppose we wish to compute the sum of a geometric series: 1/2 + (1/2) 2 + (1/2) 3 + + (1/2) n. At your desk, write a function geometricsum that takes the value n (type int) as its input parameter and returns the sum of the geometric series (as a double). We shall embed the function geometricsum into an interesting application whose specification is given as follows. Specification: write a short application class, GeometricSeries, that outputs a table with consecutive values of n in its first column and the sum of the geometric series (1/2) + (1/2) 2 + + (1/2) n in its second column. Continue this table until the sum of the geometric series equals to or greater than 1. Clearly we do not know how many rows this table shall have in advance (theoretically, indefinite if we had unlimited precision). n Geometric Sum 1 0.5 2 0.75 3 0.875. CS115 Methods.31 Reading/Homework Review chapter 5 of the textbook: 5.1 5.12 Preview chapter 6 of the textbook Do review questions: 5.1, 5.2, 5.5, 5.7, 5.11, 5.13, 5.15 CS115 Methods.32