This Week s Agenda (Part A) CS121: Computer Programming I. Changing Between Loops. Things to do in-between Classes. Answer. Combining Statements

Similar documents
CS121: Computer Programming I

CS121: Computer Programming I

Brain Re-Wiring Time. CS121: Computer Programming I. How to Tackle a Problem? Agenda. Making Changes - which localises change?

Chapter 4 Defining Classes I

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

This Week s Agenda (Part A) CS121: Computer Programming I. The Games People Play. Data Types & Structures. The Array in Java.

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CS111: PROGRAMMING LANGUAGE II

STUDENT LESSON A12 Iterations

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

Java I/O and Control Structures

Loops. CSE 114, Computer Science 1 Stony Brook University

Java I/O and Control Structures Algorithms in everyday life

CS111: PROGRAMMING LANGUAGE II

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

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

CSC 1051 Data Structures and Algorithms I

Introduction to Software Development (ISD) Week 3

Chapter 3. Selections

CS 231 Data Structures and Algorithms, Fall 2016

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

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

Repetition CSC 121 Fall 2014 Howard Rosenthal

Introduction to Programming Using Java (98-388)

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

Midterms Save the Dates!

CSC 1051 Data Structures and Algorithms I

Pace University. Fundamental Concepts of CS121 1

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Recap: Assignment as an Operator CS 112 Introduction to Programming

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

Lecture 5: Methods CS2301

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.

COE 212 Engineering Programming. Welcome to Exam I Tuesday November 11, 2014

CSC 1051 Data Structures and Algorithms I

Chapter 4: Writing Classes

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

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

CS 112 Introduction to Programming

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Claremont McKenna College Computer Science

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

4. Java Project Design, Input Methods

Static Methods. Why use methods?

Bjarne Stroustrup. creator of C++

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

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

Ch. 6. User-Defined Methods

Last Class. While loops Infinite loops Loop counters Iterations

QUIZ Friends class Y;

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

CS1004: Intro to CS in Java, Spring 2005

CS113: Lecture 4. Topics: Functions. Function Activation Records

Object-oriented programming in...

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 6 Introduction to Defining Classes

Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by:

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

Top-Down Program Development

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Programming in Java Prof. Debasis Samanta Department of Computer Science Engineering Indian Institute of Technology, Kharagpur

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Anatomy of a Class Encapsulation Anatomy of a Method

CSE 114 Computer Science I

CS 106 Introduction to Computer Science I

(Refer Slide Time: 1:27)

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

Selection and Repetition Revisited

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Inheritance and Interfaces

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

COMP 250 Winter 2011 Reading: Java background January 5, 2011

1007 Imperative Programming Part II

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

COMP-202 Unit 4: Programming with Iterations

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore

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

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

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

First Java Program - Output to the Screen

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

Algorithms and Conditionals

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Midterms Save the Dates!

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

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

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

Java Bytecode (binary file)

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Get JAVA. I will just tell you what I did (on January 10, 2017). I went to:

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

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

CS121/IS223. Collections Revisited. Dr Olly Gotel

Transcription:

CS121: Computer Programming I A) Practice with Java Control Structures B) Methods Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors This Week s Agenda (Part A) Lots of practice with conditionals & loops Some loop extras A word on scope & local variables Finishing up with nested loops from week 3 s slides lots of class examples CS121/IS223 Week 4, Slide 1 CS121/IS223 Week 4, Slide 2 Things to do in-between Classes Changing Between Loops Code this? * *** ***** *** * Don t forget to do the readings and exercises from the text book these are essential to build on the class work and all outlined in Ex Sheet 1. You should have this all under control before week 5 starts! Write the following while loop as a for loop: int count = 1; while (count < 5){ System.out.println( Num = + count); count++; CS121/IS223 Week 4, Slide 3 CS121/IS223 Week 4, Slide 4 Answer for (int count = 1; count <5; count++) System.out.println( Num = + count); Combining Statements int x = 1; while (x++ < 10){ if (x == 5){ System.out.println( Number is 5 ); In real programs, expect to combine loops & conditionals CS121/IS223 Week 4, Slide 5 Beware of ++ try putting this before and after x and see what happens ++x??? x++??? CS121/IS223 Week 4, Slide 6 1

Exercise Write a Java program that accepts student marks from a user (from 0 to 100) until the user enters a bogus value (like 999 or 3): print out the highest mark entered print out the lowest mark entered (use if statements within a while loop) Call your file StudentMarks.java An Answer import java.util.scanner; Scanner scan = new Scanner(System.in); next = scan.nextint(); next = scan.nextint(); Uh oh the most common mistake! What is wrong with this? Hint look at the initial values of max & min Also try using a do-while loop This is called a sentinel value CS121/IS223 Week 4, Slide 7 CS121/IS223 Week 4, Slide 8 Nesting Write a nested for loop to print the following on the screen: cols = 5 ***** rows = 3 ***** ***** Use the outer loop for rows Use the inner loop for columns Extend this program to take input from user so the user can enter the number columns & number rows they want then make it print any symbol Working With Strings A string in Java is a sequence of characters Sometimes useful to identify separate elements within a string (called tokens): token This is a string delimiter token delimiter token delimiter token Extracting these elements is tokenising the string CS121/IS223 Week 4, Slide 9 CS121/IS223 Week 4, Slide 10 StringTokenizer Class Class from the Java Standard Class Library to work with string elements (part of java.util package) Use as is for now you can do some interesting loops by processing strings Example From [Lewis & Loftus 2003] -- Update to use Scanner for reading input Where the methods are kept Try this out Uses classes, objects & methods OO again! CS121/IS223 Week 4, Slide 11 CS121/IS223 Week 4, Slide 12 2

Want to Know What s Going On? Loop doesn t do what you expect need some diagnostic tools? Tracing variables watching variables change when the program is running helps with debugging Insert some temporary println() statements in your code to print the value of changing variables trace statements Remove the trace statements after debugging Example int count, sum = 0; System.out.println( Sum is + sum); for (count = 1; count < 10; count++){ sum = sum + count; System.out.println( Count is + count); System.out.println( Sum is + sum); System.out.println( Sum = + sum); CS121/IS223 Week 4, Slide 13 CS121/IS223 Week 4, Slide 14 Loops Use the break Statement Too The break statement can exit a loop from inside a loop body any sort of loop Example From [Savitch 2004] ignore the old ways of reading input (superseded by Scanner in Java 5.0) while (true){ x++; if (x > 10){ break; break exits the loop when x is greater than 10 Program execution then continues after the loop CS121/IS223 Week 4, Slide 15 CS121/IS223 Week 4, Slide 16 When To Use a break Statement When a condition changes inside a loop & you don t want to carry out the remaining loop statements break statements can make your code hard to read Avoid or use sparingly The continue Statement The continue statement jumps to the next iteration of the loop when x is greater than 10 while (true){ x++ if (x>10){ continue; Avoid or use sparingly CS121/IS223 Week 4, Slide 17 CS121/IS223 Week 4, Slide 18 3

Compound Statements A Bit Xtra Can declare variables inside compound statements Called local variables used for temporary/transient matters A local variable is only valid inside its local scope // counter does not exist out here { int counter = 10; // Can use counter in here // Can t use counter here counter is a local variable A compound statement defines local scope CS121/IS223 Week 4, Slide 19 Scope & Local Variables while (condition){ int x = 10; // can use x here // can t use x here x is a local variable it has local scope within the enclosing braces (i.e. ONLY exists and can be used inside here { **here** ) CS121/IS223 Week 4, Slide 20 Disjoint Scopes while (condition){ int x = 10; // can use x here while (condition){ int x = 10; // can use x here BUT it is a // different x from the x above CS121/IS223 Week 4, Slide 21 Lifetime & Visibility Variables have 2 characteristics lifetime & visibility: lifetime when & for how long it exists visibility what parts of the program can access the variable x only exists when the scope is active (i.e. the program is executing inside a compound statement outer braces) x is created anew & initialised every time the compound statement is executed (i.e. every time the loop body is executed) CS121/IS223 Week 4, Slide 22 What Happens? (1) for (int i=0;i<10;i++){ System.out.println(i); System.out.println(i); Make sure variable in scope (2) int i=10; for (int i=0; i<10;i++){ System.out.println(i); System.out.println(i); Don t re-declare the same variable (3) int i=20; for (i=0;i<10;i++){ System.out.println(i); System.out.println(i); i in scope outside loop Type in and try out figure out what is going on Key Points (Part A) Conditionals & loops are fundamental to controlling the control of execution through a program: you need to practice & practice with loops you will have LOTS of these in the exam! Variables can have restricted scope - local variables are only temporary, so memory is freed after their use CS121/IS223 Week 4, Slide 23 CS121/IS223 Week 4, Slide 24 4

This Week s Agenda (Part B) Methods ONE main method but you can have plenty of others! Writing Java Programs Only written very small programs to date using one class (the name of your program) OO, but not really OO How do your programs work? How do you write really BIG programs? How do you write OO ones? One big class, with lots of statements, loops & selections inside? repeats bits of code jumps all over the place It would just be a mess needs structure CS121/IS223 Week 4, Slide 25 CS121/IS223 Week 4, Slide 26 How Do You Eat an Elephant? How Do You Tie Shoe Laces? DON T! One bite at a time! Complex - so we refer to it as a whole and blackbox the details What did you do between waking up & getting to university today? CS121/IS223 Week 4, Slide 27 CS121/IS223 Week 4, Slide 28 Helping With Digestion Organising Code Managing complexity Which is easier to talk about or refer to: a sandwich, a packet of chips, a cookie, some fruit, a carton of juice? a box lunch? Package stuff up and give it a label to refer to! We group programming statements to make the task of programming more comprehensible Statements are generally grouped when, together, they perform some task A name is assigned to such blocks of code (functions, procedures, subroutines, modules, methods) so this name can be referred to in place of all the statements CS121/IS223 Week 4, Slide 29 Every programming language has its own way for doing these things CS121/IS223 Week 4, Slide 30 5

Chunky Variable a chunk of data with a name Method a chunk of code with a name The foundations of reuse CS121/IS223 Week 4, Slide 31 Packaging Code printsquare: ------------------------- ------------------------- ------------------------- ------------------------- Refer to printsquare() whenever we want to use the sequence of statements (this is abstraction) Write once, debug once, use many times, update in one place In Java, we call this a method & declare it inside a class CS121/IS223 Week 4, Slide 32 Methods in Java A method is a named sequence of programming statements Clarification Some programming languages have functions or procedures Python has functions for e.g. To use a method, you call it but you have to state where the method can be found (i.e. which class the code is inside) You do this by calling the method on an object of the class: General - objectname.methodname(); Specific - myobject.printsquare(); Static methods are called on a class no objects needed CS121/IS223 Week 4, Slide 33 Java has object methods a bit like a function that an object can perform terry.forwardmarch(); object of class turtle method Variable of a class type names an object (e.g. terry) this code tells Terry to move forward CS121/IS223 Week 4, Slide 34 More Clarification This turtle is called Tiffany To get her to move forward: tiffany.forwardmarch(); Code Structure Source file (ClassName.java) Class Method 1 Statement Statement Method 2 terry.forwardmarch(); Statement CS121/IS223 Week 4, Slide 35 CS121/IS223 Week 4, Slide 36 6

Classes & Methods Classes & Methods - Example public class ExampleClass{ public void methodone(){ Statements public void methodtwo(){ Statements Instance object created - one particular ExampleClass ExampleClass myobject = new ExampleClass(); myobj.methodone(); myobj.methodtwo(); A class can declare a number of methods (responsibilities, services, behaviours) Constructor - a method with same name as class to make an instance object of this class Methods are called on instance objects of the class (dot notation) CS121/IS223 Week 4, Slide 37 public class SquareClass{ Method name public void printsquare(){ for (int i = 0; i < 5; i++) System.out.println( +++++ ); Method code in braces Methods are just a nice way of packaging your code now just call the method rather than repeat the code Class name CS121/IS223 Week 4, Slide 38 What Do These Mean? Written a Method, How Do You Use It? public class SquareClass{ public void printsquare(){ for (int i = 0; i < 5; i++) System.out.println( +++++ ); public can call the method from anywhere in a program (if object is accessible) a visibility/access modifier void method returns no value back to the place of the method call, just does something handy CS121/IS223 Week 4, Slide 39 Methods are called on objects but when you start a program running, you have no objects Remember the main method: public static void main(string[] args){ Means method does NOT need to be called on an object main creates object(s) & calls their methods the objects then take over the show Only one main method in a program, even if lots of java files this is where your program starts CS121/IS223 Week 4, Slide 40 Hybrid OO - meaning I am making an instance of a class in the class itself better to have a separate DRIVER class that does this but easier for small things for now Using Our Example Classes, Objects & Methods Not the best way Future > class types & driver classes public class SquareClass{ public void printsquare(){ for (int i = 0; i < 5; i++) System.out.println( +++++ ); public static void main(string[] args){ SquareClass myobj = new SquareClass(); myobj.printsquare(); Constructor CS121/IS223 Week 4, Slide 41 Instance variable - gpa - each student object has own value for gpa (Student.java) public class Student { private int gpa=0; public int getgpa() { return this.gpa; public void setgpa(int newgpa) { this.gpa=newgpa; public static void main(string[] args) { Student s1 = new Student(); System.out.println(s1.getGpa()): Other methods here CS121/IS223 Week 4, Slide 42 7

Program Flow Like being interrupted by a phone call but you carry on doing what you were previously doing when it is over Built-in Methods Black-box programming A method call changes the flow of a program The program jumps & control passes to the method (it may be in an external class/file) Control returns to the point it left when the method has finished With conditionals (branches), loops (repeats) & methods (side-tracks) we can get quite interesting program flow CS121/IS223 Week 4, Slide 43 Methods provided by the programming language to carry out routine or complex things: System.out.println( bla ); We know nothing about how built-in methods like println are coded We don t need to know anything, other than: how to use the method (i.e. how to call it & whether to pass it any arguments - we are passing println a string here, bla ) the type of value the method returns println returns nothing - it is void) A sort of protocol CS121/IS223 Week 4, Slide 44 How Many Built-in Methods? There are an enormous number of built-in methods to take advantage of (see the API)! http://java.sun.com/javase/6/docs/api/ However, you are not expected to know about or use all of these you will find things as & when you need them User-Defined Methods When there is no built-in method to do what you want to do, you have to roll your own It is exactly like a built-in method, but YOU write the code Your method may do one specific thing, but it is often smarter to make it general purpose They can save you some work! CS121/IS223 Week 4, Slide 45 CS121/IS223 Week 4, Slide 46 Example We want to write a program to print out this sign ******************************************************* ******************************************************* Welcome ******************************************************* ******************************************************* ******************************************************* ******************************************************* Example from Dr Courtney A Class & Its Methods - Declaring public class SignClass{ public void printtwolines(){ System.out.println(" *******************************"); System.out.println(" *******************************"); public void printwelcome(){ System.out.println(" Welcome"); public void printfourlines(){ for(int i=1; i <=4; i++) System.out.println("********************************"); i is local / temporary variable with restricted scope Why use methods? CS121/IS223 Week 4, Slide 47 CS121/IS223 Week 4, Slide 48 8

Driver Class Making an Object; Calling its Methods public class SignDemo{ public static void main(string[] args){ Try it! Go back 2 slides make a SignClass class exactly as shown SignClass welcomesign = new SignClass(); //instantiating an object welcomesign.printtwolines(); //invocation of method in object s class definition welcomesign.printwelcome(); //invocation of method welcomesign.printfourlines(); //invocation of method Why do this? Go back 1 slide make a SignDemo class exactly as shown 2 java files in the same source folder - compile and run see what happens Then, look at the code changes to these 2 classes in the following slides, make the changes and keep re -running your code CS121/IS223 Week 4, Slide 49 CS121/IS223 Week 4, Slide 50 Making Methods More General (i) public void printlines(int number){ Parameter for(int i=1; i <=number; i++) System.out.println("*********************"); Create the above method in the SignClass public class SignDemo{ public static void main (String[] args){ SignClass welcomesign = new SignClass(); welcomesign.printlines(2); welcomesign.printwelcome(); welcomesign.printlines(4); Values for parameters to pass into methods should agree in type, quantity, and position CS121/IS223 Week 4, Slide 51 Aside This is called the method SIGNATURE or method declaration public void printlines(int number) The return type Visibility/access modifier Method name Parameter - variable name and its type CS121/IS223 Week 4, Slide 52 Making Methods More General (ii) public class SignDemo{ public static void main(string[] args){ SignClass forsalesign = new SignClass(); forsalesign.printlines(2); forsalesign.decideonmessage(); forsalesign.printmessage(); forsalesign.printlines(4); Need to declare some instance data for the SignClass, so each actual sign object we make can store its own unique message CS121/IS223 Week 4, Slide 53 Making Methods More General (iii) public class SignClass{ private String message= ; public void printlines(int number){ for (int i=1; i<=number; i++) System.out.println(" ******************"); public void printmessage(){ System.out.println(" " + message"); public void decideonmessage(){ System.out.println( What message do you want?"); message = scan.nextline(); Make your Scanner object the usual way CS121/IS223 Week 4, Slide 54 9

Making a General Purpose Method Try the next example too Returning to our Example public class SquareClass{ Hybrid OO public void printsquare(){ for (int i = 0; i < 5; i++) System.out.println( +++++ ); public static void main(string[] args){ SquareClass myobj = new SquareClass(); myobj.printsquare(); Constructor Change the method to print a square of ANY size CS121/IS223 Week 4, Slide 55 CS121/IS223 Week 4, Slide 56 Squares of Any Size? Revisiting a few concepts here Varied behaviour a better abstraction Parameter to method Rectangles of Any Size? An even better abstraction 2 parameters to method Parameter variable public void printsquare(int side){ for (int row = 0; row < side; row++){ for (int col = 0; col < side; col++){ System.out.print( + ); Scope of side? System.out.println( \n ); To call: myobj.printsquare(8); Change the method to print a rectangle of ANY size New line character Argument to method initialises side (the parameter variable) CS121/IS223 Week 4, Slide 57 public void printrect(int rows, int cols){ for (int row = 0; row < rows; row++){ for (int col = 0; col < cols; col++){ System.out.print( + ); System.out.println( \n ); 2 arguments to method types MUST match, so order is important, the value of 2 goes into rows and the value of 4 goes into cols To call: myobj.printrect(2, 4); Change the method to print a rectangle of ANY size using any character! CS121/IS223 Week 4, Slide 58 Rectangles Using Any Character? Better abstraction yet! Methods That Return Values void methods return no value 3 parameters to method public void printrect(int rows, int cols, char ch){ for (int row = 0; row < rows; row++){ for (int col = 0; col < cols; col++){ System.out.print(ch); System.out.println( \n ); 3 arguments to method types MUST match, so order is important, this time * goes into the variable ch To call: myobj.printrect(2, 4, * ); CS121/IS223 Week 4, Slide 59 Does a calculation & returns a value you must do something with this return value! Parameter is number to square, Type of the return value declared with its type declared public int square(int number){ number = number * number; return number; return statement returns a value & ends the method MUST be present if method declaration/signature returns a type, and here it must return an int value To call & use: int x = myobj.square(3); CS121/IS223 Week 4, Slide 60 10

The return Statement in Java Returns a value & ends a method jumps back to where the method was called & inserts its value What s the Difference? Arguments & parameters: two sides of the same coin -- it is just terminology (often used interchangeably) Methods only return 1 value, but this could be a collection of values (next week s topic)! public int square(int number){ return number * number; statement; This statement is NEVER executed because it is AFTER the return statement Note, constructors have no return type, not even void! CS121/IS223 Week 4, Slide 61 You specify a method signature using parameters You call a method using arguments (i.e. you give actual values for the parameters) When a method is called, arguments are passed into (substituted for) the parameters Be careful of scope - where do these variables exist? CS121/IS223 Week 4, Slide 62 More Terminology We Want Methods to be Good Tools! Encapsulation taking some code statements, turning them into a method, then using them as a whole: simpler to refer to & remember as a whole can be used many times, in many places (reuse) other people can use your code & you can use other people s (a clear contract of use) Generalisation writing methods that can do more than one particular thing: a method that can find the factorial of any number is more useful than a method that only finds 5! CS121/IS223 Week 4, Slide 63 Good to make methods as general -purpose & reusable as possible CS121/IS223 Week 4, Slide 64 Writing Java Programs Using Methods No longer a long sequential list of statements Instead, loosely coupled methods that call each other Create small cohesive methods that do a single thing: if it does many things, split into multiple methods if it is long, split into multiple methods Parameterise your methods to make them general -purpose Key Points (Part B) Methods in Java: parameters specify the type & number of variables used by a method (can have any number) sometimes called formal parameters arguments are the actual values of these variables & they are passed to the method when it is called sometimes called actual parameters scope determines the lifetime of a variable (often delimited by the braces of compound statements & sometimes nested) local / temporary variables are variables declared in a method, & have restricted scope created when scope entered, destroyed when scope exited (names can be reused if scopes disjoint) if your method specifies a non-void return type, it needs a return statement CS121/IS223 Week 4, Slide 65 CS121/IS223 Week 4, Slide 66 11

Before Next Time Reading: if 3 rd -6 th edition read the relevant sections in Chapter 4 on methods PRACTICE: Variables, types, conditionals, loops. Etc. (Not methods!) exercise sheet 1 should be completed! Start working on Part A of exercise sheet 2 Start developing your project! NOTE: This is your FIRST exposure to these concepts and they take time and practice to learn. But you HAVE to try things or you will get lost! We will keep on revisiting things and building on basics Coming Up Next TEST ON CONDITIONALS, LOOPS, ETC (not methods) We will keep on looking at methods We will also look at a new data type when we next meet the array, it is used for storing collections of data. We will look at arrays containing data of primitive types (like int, double, char ) A few loose ends that some of you may find helpful for project work.. I ll show you some sample projects too CS121/IS223 Week 4, Slide 67 CS121/IS223 Week 4, Slide 68 12