Things to do in-between Classes Changing Between...

12
1 CS121/IS223 Week 4, Slide 1 CS121: Computer Programming I A) Practice with Java Control Structures B) Methods Dr Olly Gotel [email protected] http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223 Week 4, Slide 2 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 3 Things to do in-between Classes 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! CS121/IS223 Week 4, Slide 4 Changing Between Loops 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 5 Answer for (int count = 1; count <5; count++) System.out.println(“Num = ” + count); CS121/IS223 Week 4, Slide 6 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 Beware of ++ … try putting this before and after x and see what happens ++x ??? x++ ???

Transcript of Things to do in-between Classes Changing Between...

1

CS121/IS223 Week 4, Slide 1

CS121: Computer Programming I

A)  Practice with Java Control Structures B)   Methods

Dr Olly Gotel [email protected] http://csis.pace.edu/~ogotel

Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors

CS121/IS223 Week 4, Slide 2

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 3

Things to do in-between Classes

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!

CS121/IS223 Week 4, Slide 4

Changing Between Loops

•  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 5

Answer

for (int count = 1; count <5; count++)

System.out.println(“Num = ” + count);

CS121/IS223 Week 4, Slide 6

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

Beware of ++ … try putting this before and after x and see what happens ++x ??? x++ ???

2

CS121/IS223 Week 4, Slide 7

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

This is called a sentinel value

CS121/IS223 Week 4, Slide 8

An Answer 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

import java.util.Scanner;

next = scan.nextInt();

Scanner scan = new Scanner(System.in); next = scan.nextInt();

CS121/IS223 Week 4, Slide 9

Nesting

•  Write a nested for loop to print the following on the screen:

***** ***** *****

•  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

Use the outer loop for rows Use the inner loop for columns

cols = 5

rows = 3

CS121/IS223 Week 4, Slide 10

Working With Strings

•  A string in Java is a sequence of characters

•  Sometimes useful to identify separate elements within a string (called tokens):

“This is a string”

•  Extracting these elements is tokenising the string

token token token token

delimiter delimiter delimiter

CS121/IS223 Week 4, Slide 11

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

Try this out…

CS121/IS223 Week 4, Slide 12

Example From [Lewis & Loftus 2003] -- Update to use Scanner for reading input

Uses classes, objects & methods – OO again!

Where the methods are kept

3

CS121/IS223 Week 4, Slide 13

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

CS121/IS223 Week 4, Slide 14

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 15

Loops Use the break Statement Too

•  The break statement can exit a loop from inside a loop body – any sort of loop

while (true){

x++;

if (x > 10){

break;

}

}

•  Program execution then continues after the loop

break exits the loop when x is greater than 10

CS121/IS223 Week 4, Slide 16

Example From [Savitch 2004] – ignore the old ways of reading input (superseded by Scanner in Java 5.0)

CS121/IS223 Week 4, Slide 17

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

CS121/IS223 Week 4, Slide 18

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

4

CS121/IS223 Week 4, Slide 19

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

A compound statement defines local scope

counter is a local variable CS121/IS223 Week 4, Slide 20

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 21

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 22

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 23

What Happens?

for (int i=0;i<10;i++){ System.out.println(i); } System.out.println(i);

int i=10; for (int i=0; i<10;i++){ System.out.println(i); } System.out.println(i);

int i=20; for (i=0;i<10;i++){ System.out.println(i); } System.out.println(i);

(1)

(2)

(3)

Don’t re-declare the same variable

Make sure variable in scope

i in scope outside loop

Type in and try out … figure out what is going on

CS121/IS223 Week 4, Slide 24

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

5

CS121/IS223 Week 4, Slide 25

This Week’s Agenda (Part B)

•  Methods

•  ONE main method … but you can have plenty of others!

CS121/IS223 Week 4, Slide 26

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

How do your programs work?

CS121/IS223 Week 4, Slide 27

How Do You Eat an Elephant?

What did you do between waking up & getting to university today?

DON’T!

One bite at a time!

CS121/IS223 Week 4, Slide 28

How Do You Tie Shoe Laces?

Complex - so we refer to it as a whole and blackbox the details

CS121/IS223 Week 4, Slide 29

Helping With Digestion

•  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!

CS121/IS223 Week 4, Slide 30

Organising Code

•  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

•  Every programming language has its own way for doing these things

Managing complexity

6

CS121/IS223 Week 4, Slide 31

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 32

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 33

Methods in Java

•  A method is a named sequence of programming statements

•  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 34

Clarification

•  Some programming languages have functions or procedures – Python has functions for e.g.

•  Java has object methods – a bit like a function that an object can perform

terry.forwardMarch();

method object of class turtle

Variable of a class type names an object (e.g. terry) – this code tells Terry to move forward

CS121/IS223 Week 4, Slide 35

More Clarification

•  This turtle is called Tiffany

•  To get her to move forward:

tiffany.forwardMarch();

terry.forwardMarch();

CS121/IS223 Week 4, Slide 36

Code Structure

Source file (ClassName.java)

Class

Method 1

Statement Statement

Method 2

Statement

7

CS121/IS223 Week 4, Slide 37

Classes & Methods

public class ExampleClass{

public void methodOne(){

Statements… }

public void methodTwo(){

Statements… }

}

ExampleClass myObject = new ExampleClass(); myObj.methodOne(); myObj.methodTwo();

A class can declare a number of methods (responsibilities, services, behaviours)

Methods are called on instance objects of the class (dot notation)

Instance object created - one particular ExampleClass

Constructor - a method with same name as class to make an instance object of this class

CS121/IS223 Week 4, Slide 38

Classes & Methods - Example

public class SquareClass{

public void printSquare(){ for (int i = 0; i < 5; i++)

System.out.println(“+++++”);

} }

Methods are just a nice way of packaging your code – now just call the method rather than repeat the code

Class name

Method name

Method code in braces

CS121/IS223 Week 4, Slide 39

What Do These Mean?

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 40

Written a Method, How Do You Use It?

•  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){ }

•  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

Means method does NOT need to be called on an object

CS121/IS223 Week 4, Slide 41

Using Our Example

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

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

CS121/IS223 Week 4, Slide 42

Classes, Objects & Methods

(Student.java)

public class Student {

}

public static void main(String[] args) { Student s1 = new Student(); System.out.println(s1.getGpa()): }

public int getgpa() { return this.gpa; }

Other methods here…

Not the best way … Future –> class types & driver classes

public void setGpa(int newGpa) { this.gpa=newGpa; }

private int gpa=0;

Instance variable - gpa - each student object has own value for gpa

8

CS121/IS223 Week 4, Slide 43

Program Flow

•  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…

Like being interrupted by a phone call – but you carry on doing what you were previously doing when it is over

CS121/IS223 Week 4, Slide 44

Built-in Methods

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

Black-box programming

A sort of protocol

CS121/IS223 Week 4, Slide 45

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

They can save you some work!

CS121/IS223 Week 4, Slide 46

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

CS121/IS223 Week 4, Slide 47

Example

•  We want to write a program to print out this sign

******************************************************* ******************************************************* Welcome ******************************************************* ******************************************************* ******************************************************* *******************************************************

Example from Dr Courtney

CS121/IS223 Week 4, Slide 48

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("********************************"); }

}

Why use methods?

i is local / temporary variable with restricted scope

9

CS121/IS223 Week 4, Slide 49

Driver Class – Making an Object; Calling its Methods

public class SignDemo{

public static void main(String[] args){ 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?

CS121/IS223 Week 4, Slide 50

Try it!

•  Go back 2 slides… make a SignClass class exactly as shown

•  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 51

Making Methods More General (i)

public void printLines(int number){ for(int i=1; i <=number; i++) System.out.println("*********************"); }

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

Create the above method in the SignClass

Parameter

CS121/IS223 Week 4, Slide 52

Aside

•  This is called the method SIGNATURE or method declaration

public void printLines(int number)

Visibility/access modifier

The return type

Method name Parameter - variable name and its type

CS121/IS223 Week 4, Slide 53

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 54

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

10

CS121/IS223 Week 4, Slide 55

Making a General Purpose Method

•  Try the next example too…

CS121/IS223 Week 4, Slide 56

Returning to our Example

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(); } } Change the method to print a square of ANY size

Constructor

Hybrid OO

CS121/IS223 Week 4, Slide 57

Squares of Any Size?

public void printSquare(int side){ for (int row = 0; row < side; row++){

for (int col = 0; col < side; col++){

System.out.print(“+”); }

System.out.println(“\n”);

} }

Parameter to method

To call: myObj.printSquare(8);

Argument to method initialises side (the parameter variable)

Parameter variable

New line character

Varied behaviour – a better abstraction

Scope of side?

Revisiting a few concepts here…

Change the method to print a rectangle of ANY size CS121/IS223 Week 4, Slide 58

Rectangles of Any Size?

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 parameters to method

To call: myObj.printRect(2, 4);

An even better abstraction

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

Change the method to print a rectangle of ANY size using any character!

CS121/IS223 Week 4, Slide 59

Rectangles Using Any Character?

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 parameters to method

To call: myObj.printRect(2, 4, ‘*’);

Better abstraction yet!

3 arguments to method – types MUST match, so order is important, this time ‘*’ goes into the variable ch

CS121/IS223 Week 4, Slide 60

Methods That Return Values

•  Does a calculation & returns a value – you must do something with this return value!

public int square(int number){

number = number * number;

return number;

}

Type of the return value declared Parameter is number to square, with its type declared

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

void methods return no value

11

CS121/IS223 Week 4, Slide 61

The return Statement in Java

•  Returns a value & ends a method – jumps back to where the method was called & inserts its value

•  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 62

What’s the Difference?

•  Arguments & parameters: two sides of the same coin -- it is just terminology (often used interchangeably)

•  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 63

More Terminology

•  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 64

We Want Methods to be Good Tools!

Good to make methods as general-purpose & reusable as possible

CS121/IS223 Week 4, Slide 65

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

CS121/IS223 Week 4, Slide 66

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

12

CS121/IS223 Week 4, Slide 67

Before Next Time…

•  Reading: –  if 3rd-6th 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

CS121/IS223 Week 4, Slide 68

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…