Download Java Control Structures - Computer Programming I | CS 121 and more Study notes Computer Science in PDF only on Docsity!
CS121/IS223 Week 4, Slide 1
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 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++ ???
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
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);
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
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
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
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 System.out.println(" void printTwoLines() *******************************");{ }^ System.out.println("^ *******************************"); public System.out.println(" void printWelcome(){ Welcome"); } public for(int void printFourLines(){i=1; i <=4; i++) }^ System.out.println("********************************"); } Why use methods? i is local / temporary variable with restricted scope
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
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