Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Methods

Similar documents
Midterm Examination (MTA)

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

Introduction to Computer Science Unit 2. Notes

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Testing and Debugging

Introduction to Computer Science Unit 2. Notes

Lab Exercise 1. Objectives: Part 1. Introduction

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Arrays

CS141 Programming Assignment #5

Programming with Java

Java Reference Card. 1. Classes. 2. Methods. 3. Conditionals. 4. Operators

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

CS141 Programming Assignment #6

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Object Oriented Programming. Java-Lecture 6 - Arrays

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

AP CS Unit 3: Control Structures Notes

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. File Input and Output

Date: Dr. Essam Halim

Chapter 5 Lab Methods

1. A company has vans to transport goods from factory to various shops. These vans fall into two categories: 50 items 150 items


Programming Exercise 7: Static Methods

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

Program Control Flow

Program Control Flow

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

ITERATION WEEK 4: EXMAPLES IN CLASS

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

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

Building Java Programs

Tutorial 03. Exercise 1: CSC111 Computer Programming I

Example: Monte Carlo Simulation 1

Fundamentals of Programming Data Types & Methods

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Arrays OBJECTIVES. In this chapter you will learn:

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

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

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

CMPS 11 Introduction to Programming Midterm 1 Review Problems

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

Reading Input from Text File

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

CS141 Programming Assignment #8

H212 Introduction to Software Systems Honors

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS

Example Program. public class ComputeArea {

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

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

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

Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 45 Obtained Marks:

Welcome to the Primitives and Expressions Lab!

CS111: PROGRAMMING LANGUAGE II

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Arrays. Eng. Mohammed Abdualal

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Exceptions Handeling

Methods. Eng. Mohammed Abdualal

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

++x vs. x++ We will use these notations very often.

Ahmadu Bello University Department of Mathematics First Semester Examinations June 2014 COSC211: Introduction to Object Oriented Programming I

Chapter 12 Exception Handling

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

2.2 - Making Decisions

Introduction to Java Applications

Java Console Input/Output The Basics. CGS 3416 Spring 2018

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Important Java terminology

Web-CAT submission URL: CAT.woa/wa/assignments/eclipse

4. Java Project Design, Input Methods

AP COMPUTER SCIENCE A

2.8. Decision Making: Equality and Relational Operators

Introduction to Computer Science Unit 2. Exercises

Practice Midterm 1. Problem Points Score TOTAL 50

Chapter 5 Lab Methods

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

CSC 1051 Data Structures and Algorithms I

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

Practice Midterm 1 Answer Key

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Pace University. Fundamental Concepts of CS121 1

Chapter 6 Methods. Dr. Hikmat Jaber

Common Mistakes with Functions. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Programming: Java. Chapter Objectives. Chapter Objectives (continued) Program Design Including Data Structures. Chapter 7: User-Defined Methods

COMP-202: Foundations of Programming. Lecture 4: Methods Jackie Cheung, Winter 2016

Introduction to Computer Programming

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

CMSC 202. Exceptions

Warm up Exercise. What are the types and values of the following expressions: * (3 + 1) 3 / / 2.0 (int)1.0 / 2

CS170 (005): Introduction to Computer Science Exam 2

Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points.

Chapter 2 ELEMENTARY PROGRAMMING

AP CS A Exam Review Answer Section

Topics. The Development Process

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

CAT.woa/wa/assignments/eclipse

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

CSC 1051 Data Structures and Algorithms I

CS Computers & Programming I Review_01 Dr. H. Assadipour

Transcription:

WIT COMP1000 Methods

Methods Programs can be logically broken down into a set of tasks Example from horoscope assignment:» Get input (month, day) from user» Determine astrological sign based on inputs and output horoscope Individual tasks can be separated out from the main program into methods A method is simply a mini-program that completes a specific task WIT COMP1000 2

Predefined Methods Java includes many predefined methods for common programming tasks Example of using the predefined square root method, Math.sqrt(): double root, input_value; System.out.print("Enter a number: "); returned input_value = input.nextdouble(); method call value root = Math.sqrt(input_value); argument System.out.println("The square root is " + root); WIT COMP1000 3

WIT COMP1000 4 Generic Form RETURN_TYPE FUNCTION(PARAMETER_1, PARAMETER_2,, PARAMETER_N) A method can have any number of parameters» Each parameter has a specified type (int, double, String, etc) A method has either zero or one return value(s)» The return value is commonly the result of the method» If it has a return value, the value also has a specified type» The return value can be assigned to variable of the same type (as in the previous example)» Alternatively, the method call can be placed directly in another Java expression and the return value will be used in place of the method call

A Few Java Methods return type method name parameter list Square root: double Math.sqrt(double a) Power: double Math.pow(double base, double exp) Absolute value: double Math.abs(double a) Natural log: double Math.log(double a) Log base 10: double Math.log10(double a) WIT COMP1000 5

More Examples double number, cube, log2; System.out.print("Enter a number: "); number = input.nextdouble(); System.out.println(number + "'s square root is " + Math.sqrt(number)); cube = Math.pow(number, 3.0); System.out.println(number + "^3.0=" + cube); log2 = Math.log(number) / Math.log(2.0); System.out.println("log2(" + number + ")=" + log2); WIT COMP1000 6

Terminology Notes We use parameters to refer to the list of variables a method requires (in parentheses)» They are place holders for values that will be used when the function is called We use arguments (a.k.a. actual parameters) to refer to the specific values and/or variables that are passed in when you invoke the method Also note that other languages refer to methods as functions or procedures WIT COMP1000 7

Exercise Write a program that prints out the value of 2 x for x=1,2,3,,32 Use the Math.pow() method and a while loop WIT COMP1000 8

Answer double x = 1; double pow2; System.out.printf() is just another method! It has a String parameter followed by one argument for each % place holder while (x <= 32) { pow2 = Math.pow(2, x); System.out.printf("2^%.0f=%.0f%n", x, pow2); x++; WIT COMP1000 9

Programmer-Defined Methods Java allows you to define your own methods to meet the needs of your specific program To define your own method, you need to write the method signature and the method body The signature includes the method name, parameter list, and return type The body is the set of Java statements that will be executed when the method is invoked WIT COMP1000 10

No Parameters, No Return Value public class ClassExamples { public static void main(string[] args) { void means no return value sayhello(); method call to execute the method public static void sayhello() { System.out.println("hello!"); empty () means no parameters For now, always put public static in front WIT COMP1000 11 statements to execute when the method is called

Methods When a program executes a method, it temporarily stops where it is in main(), goes to the lines of code in the method, and executes those lines like normal Then, when you get to the end of the method (or a return statement) it goes back to main() and resumes executing after the method call WIT COMP1000 12

No Parameters, One Return Value import java.util.scanner; public class ClassExamples { public static void main(string[] args) { int i; i = getinteger(); System.out.println("Got: " + i); public static int getinteger() { Scanner input = new Scanner(System.in); System.out.print("Enter an integer: "); int input_value = input.nextint(); return input_value; int means the method returns an integer Have to return an integer value WIT COMP1000 13

Return Values Methods have zero or one return value(s) If a method has a return value, it is of a specific type (int, double, String, )» Type is defined as part of the method signature Use the return statement to return a value of the specified type» Can be a constant, variable, expression, method, or anything that is evaluated to the required type WIT COMP1000 14

Another Example import java.util.scanner; public class ClassExamples { public static void main(string[] args) { String s; s = getstring(); System.out.println("Got: " + s); public static String getstring() { Scanner input = new Scanner(System.in); System.out.print("Enter a string: "); String input_value = input.next(); return input_value; WIT COMP1000 15

return a Method Call import java.util.scanner; public class ClassExamples { public static void main(string[] args) { String s; s = getstring(); System.out.println("Got: " + s); public static String getstring() { Scanner input = new Scanner(System.in); System.out.print("Enter a string: "); return input.next(); WIT COMP1000 16

Exercise Write a method named getdouble() that reads a (double) value from the user and returns it to main(), then print the value in main() WIT COMP1000 17

Answer import java.util.scanner; public class ClassExamples { public static void main(string[] args) { double val; val = getdouble(); System.out.println("Got: " + val); public static double getdouble() { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); double input_value = input.nextdouble(); return input_value; WIT COMP1000 18

Methods with Parameters Methods can take any number of parameters Each parameter has a predefined data type (int, double, String, ), defined as part of the method signature When called, the value of the argument is passed to the method» In other words, the values of the arguments are plugged in to the method, just like in a normal expression WIT COMP1000 19

import java.util.scanner; public class ClassExamples { Example with Two Parameters public static void main(string[] the current args) value { of Scanner input = new Scanner(System.in); input1 is passed double input1, input2, result; to the method as a System.out.print("Enter two numbers: "); input1 = input.nextdouble(); input2 = input.nextdouble(); double means the result = docalculation(input1, first parameter is input2); a System.out.printf("The double answer valueis %.3f%n", result); double means the method returns a double value public static double docalculation(double a, double b) { return (a*a + b*b); WIT COMP1000 20 the current value of input2 is passed to the method as b double means the second parameter is a double value

Parameters Each time a method is called, you can pass it different arguments» The arguments are plugged in separately each time, so you can call a method many times with different arguments to get a different return value public class ClassExamples { public static void main(string[] args) { double result1, result2; result1 = docalculation(3, 4); System.out.printf("result1 is %.3f%n", result1); result2 = docalculation(2, 8); System.out.printf("result2 is %.3f%n", result2); public static double docalculation(double a, double b) { return (a*a + b*b); WIT COMP1000 21

Important Note Arguments are passed in by value to the method If you have a variable in main() that is used as an argument to a method then the value of that variable is used as the parameter in the method Any changes made to the value in the method do not affect the original variable in main() WIT COMP1000 22

public class ClassExamples { Pass by Value Example public static void main(string[] args) { double x = 10, y = 20; double result; System.out.println("before docalculation(), x=" + x); result = docalculation(x, y); System.out.println("after docalculation(), x=" + x); System.out.println("doCalcuation() result=" + result); public static double docalculation(double a, double b) { System.out.println("at start of docalculation(), a=" + a); a = a - 5; System.out.println("at end of docalculation(), a=" + a); return (a*a + b*b); WIT COMP1000 23

Multiple return Statements Methods (including the main() method) can have multiple return statements in them When a return statement is executed, the method stops and the stated value is returned to the caller immediately» No more of the method is executed (unless it is called again, in which case it starts over)» Note that in main(), return causes the entire program to end (main() is a method, too!) WIT COMP1000 24

Multiple return Statements Example import java.util.scanner; Methods that return a boolean are often used in boolean expressions public class ClassExamples { public static void main(string[] args) { Scanner input = new Scanner(System.in); int input_value; System.out.print("Enter an integer: "); input_value = input.nextint(); if(iseven(input_value)) { System.out.println(input_value + " is even!"); else { System.out.println(input_value + " is odd!"); Methods can have multiple return statements public static boolean iseven(int number) { if (number % 2 == 0) { return true; else { return false; WIT COMP1000 25

Exercise Write a program that calculates the area of a rectangle given the two side lengths which are provided by the user. You must write a method that is passed the two side lengths and returns the area. WIT COMP1000 26

Answer import java.util.scanner; public class ClassExamples { public static void main(string[] args) { Scanner input = new Scanner(System.in); double l, w; double a; System.out.print("Enter rectangle length: "); l = input.nextdouble(); System.out.print("Enter rectangle width: "); w = input.nextdouble(); a = rectanglearea(l, w); System.out.printf("The area is %.3f%n", a); public static double rectanglearea(double length, double width) { return (length*width); WIT COMP1000 27

Take Home Points Methods are mini-programs that are generally used to contain all of the code to complete some particular task Methods have either zero or one return value(s)» If it has one, the value is of a specified type Methods have zero or more parameters» Each parameter (if any) has a specified type» When called, the current values of the arguments are plugged in and passed as values to the method Methods can have multiple return statements WIT COMP1000 28