COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS.

Slides:



Advertisements
Similar presentations
Flow of Control Chapter 3.
Advertisements

SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
True or false A variable of type char can hold the value 301. ( F )
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
Logical Operators and Conditional statements
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
C++ for Engineers and Scientists Third Edition
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
TODAY’S LECTURE Review Chapter 2 Go over exercises.
UNIT II Decision Making And Branching Decision Making And Looping
Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus.
Principles of Programming - NI July Chapter 5: Structured Programming In this chapter you will learn about: Sequential structure Selection structure.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 5: Structured Programming.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
CSCI 1100/1202 January 28, The switch Statement The switch statement provides another means to decide which statement to execute next The switch.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
Controlling Execution Dong Shao, Nanjing Unviersity.
1 Week 6 Branching. 2 What is “Flow of Control”? l Flow of Control is the execution order of instructions in a program l All programs can be written with.
 The if statement and the switch statement are types of conditional/decision controls that allow your program.  Java also provides three different looping.
Review – Final Test Chapters 8,10,11. Locate error in following statement try i = Integer.pareseInt(str); catch(NumberFormatException e) System.out.println(“Input.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Application development with Java Lecture 6 Rina Zviel-Girshin.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 8 Java Fundamentals Control Structures Fri.
CS-1010 Dr. Mark L. Hornick 1 Selection and Iteration and conditional expressions.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
LECTURE # 7 : STRUCTURED PROGRAMMING Selection Statements Tr.Hadeel.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
C++ LANGUAGE MULTIPLE CHOICE QUESTION
Java Programming Fifth Edition
Java Programming: Guided Learning with Early Objects
Ch 7: JavaScript Control Statements I.
JavaScript: Control Statements.
Arrays, For loop While loop Do while loop
Outline Altering flow of control Boolean expressions
3 Control Statements:.
By Hector M Lugo-Cordero September 3, 2008
CS2011 Introduction to Programming I Selections (I)
Chap 7. Advanced Control Statements in Java
Looping and Repetition
Presentation transcript:

COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

What are flow control instructions? A program’s normal execution is sequential, i.e. instructions are executed line by line Flow control instructions simply allow to change this Main difference between C/C++’s and Java’s flow control – C/C++ utilizes numbers to represent TRUE/FALSE, anything different than 0 is a TRUE, and the value 0 is FALSE – Java has a boolean data type which may assume the values true or false. Assigning a number to a boolean variable is an error

Conditions Equal: ==a == b Not Equal: !=a != b Greater: >a > b Less: <a < b Greater or Equal: >=a >= b Less or Equal: <=a <= b Not: !!(a == 0) !(b > 2)

Conditional Assignment Allows assigning a value if a condition is met, another otherwise Syntax: – = ? : ; E.g. consider a clock that is stored in 24 hrs format, but has the option of working with AM/PM format int displayHour = hour > 12 ? hour – 12 : hour;

Multiple Conditions Multiple conditions must be met (AND) x == y && x > 0 At least one condition must be met (OR) x == y || x > y Complex conditions may be not as well !(x == y || x > y)

Conditionals if(condition){…code…} if(condition1){…} else if(condition2){} else{} – The else if are optional and may include as many as you need – else is optional unlike C/C++ where is required after using the else if Omiting the {} will only execute the next instruction after the if

Switches Switches are an alternative for having multiple conditions (equality) The condition of a switch is a number or enum Java 1.7 aka Java 7 allows usage of String variables within a switch as well Switches do not accept boolean expressions Each case in a switch is terminated by a break, if no break is added then subsequent cases may be executed as well

Switch Example Example if(x == 0) …. else if(x == 1) … … else May be written as: switch(x){ case 0: break; case 1: break; …. default: } Important: DO NOT FORGET THE BREAK

Enums Specify a collection of values where only one may be assigned Example the boolean data type may be an enum as well public enum myBoolean { FALSE, TRUE; }; Enums work like this in C/C++, but Java further extends to having methods for the enums as well – So an enum is also an Object

Loops Follow the same convention as in C/C++ – for(init_control; condition ;increment){} – while(condition){} – do{}while(condition); There is also a foreach which may be used to read sequentially a collection (this will make more sense later) – for(String name : allNames){…} – Equivalent to having a for(int i = 0; i < allNames.length; ++i){ String name = allNames[i]; … }

Comparing Strings An error would be to compare strings with == or != Test for equality.equals – if(lastName.equals(otherLastName)) Test for equality ignoring case.equalsIgnoreCase – if(user.equalsIgnoreCase(storedUser)) Both methods (functions) return a boolean

Comparing Objects As with Strings (which are object in Java as well) == and != have different sense – == tests to see if the location where two variables are stored are the same – != tests to see if the location where two variables are stored are not the same So how do we test for their values? – The method compareTo and compare – compareTo is applied to an object – compare is static, hence it receives two parameters We shall cover more on this Compares return a > 0 number if the first operand is greater, a < 0 number if it is less, and 0 if they are equal

Conditions for Comparing Objects A class should implement Comparable, what implements means will be discussed later in course Otherwise it may implement Comparator to compare two objects of another class, will cover this as well later

So what is an object then? From Java’s point of view is another data type To avoid too many abstractions, an object is an area in memory just like a data type, but it holds a collection of values Is this a struct as in C? struct Complex{ double real; double imag; }; In a sense yes, but no since Java objects are classes and as we shall see, there are more things that can be done with classes

compareTo Example public class Complex implements Comparable { …//all necessary code comes before or later this method public int compareTo(Complex other){ double thisMagnitude = this.Magnitude(); double otherMagnitude = other.Magnitude(); double thisAngle = this.Angle(); double otherAngle = other.Angle(); //test for greater if(thisMagnitude > otherMagnitude){ return 1; } //test for less if(thisMagnitude < otherMagnitude){ return -1; } //test for equal return thisAngle – otherAngle; }

compare Example public class ComplexComparator implements Comparator{ public static int compare(Complex first, Complex second){ //may used the already defined method //or redefine the method here return first.compareTo(second); }

Dealing with booleans Consider this variable definition – boolean isPresent = true; A common non-required way of testing with such values is For true – if(isPresent == true) or if(isPresent != false) – Correct: if(isPresent) For false – if(isPresent == false) or if(isPresent != true) – Correct: if(!isPresent) In a function that checks if a list is empty one could return: – return list.size() == 0 – return list.isEmpty() – No need for return true or return false, such may be used under different situations

Exceptions Exceptions are special cases that normally should not occur on a program (hence its name exception), and must be handled before continuing execution Example: – double average = sum / count; – What could be a problem with this line? – How do we fix it? If? while? Something better?

Exception Handling Each potential problem code is enclosed with a try keyword An error or exceptional case may be catch with the catch keyword Exceptions are also in C++ and are enclosed by a try{} catch(Exception e){} blocks Java also contains another keyword named finally where the code inside is executed always no matter if there is a exception or not, or even if there is a return inside

Exceptions by Example try{ double average = sum / count; return average; } catch(Exception e){ System.err.println(e.getMessage()); return Double.NaN; } finally{ System.out.println(“Average Function Exited”); }