Decisions CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 5, Horstmann*

Slides:



Advertisements
Similar presentations
DECISIONS Chapter 5. The if Statement  Action based on a conditions  If the condition is true, the body of the statement is executed if (amount
Advertisements

Math 130 Decisions II Wed, Sept 12, 2007 Notes: ref. C. Horstmann, Java Concepts.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.
Chapter 6 Horstmann Programs that make decisions: the IF command.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 5  Decisions 1 Chapter 5 Decisions. Chapter 5  Decisions 2 Chapter Goals  To be able to implement decisions using if statements  To understand.
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
Computer Science A 3: 10/2. Logical Expressions Expressions that has a value which is either true or false. Logical expressions are essential in a program.
Introduction to Java Programming, 4E Y. Daniel Liang.
If Statement if (amount
Chapter 5 – Decisions Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Logical Operators and Conditional statements
Chapter 4 Making Decisions
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Control Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
Chapter 6 Decisions. Chapter Goals To be able to implement decisions using if statements To understand how to group statements into blocks To learn how.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Introduction to Object-Oriented Programming
Decision Structures and Boolean Logic
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. if (amount
Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester,
Loops and Iteration for Statements, while Statements and do-while 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.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 5: Decisions 1 Chapter 5 Decisions.
Fall 2006Slides adapted from Java Concepts companion slides1 Decisions Advanced Programming ICOM 4015 Lecture 5 Reading: Java Concepts Chapter 6.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Copyright 2003 Scott/Jones Publishing Making Decisions.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
Boolean Expressions and if-else Statements Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006.
If Statement if (amount
Topics Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement The for loop Nested Loops.
Week 7 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Chapter 6 Decisions. Chapter Goals To be able to implement decisions using if statements To understand how to group statements into blocks To learn how.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Week 7 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Decisions Bush decision making.
Control statements Mostafa Abdallah
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Selections Java.
Chapter 4: Making Decisions.
EGR 2261 Unit 4 Control Structures I: Selection
Topics The if Statement The if-else Statement Comparing Strings
Chapter 4: Making Decisions.
Chapter 5/6 Decisions.
Topics The if Statement The if-else Statement Comparing Strings
Chapter 4: Control Structures I (Selection)
Control Structure Chapter 3.
Chapter 5 – Decisions Big Java by Cay Horstmann
Boolean Expressions to Make Comparisons
Classes CS 21a: Introduction to Computing I
Loops and Iteration CS 21a: Introduction to Computing I
Control Structure.
Presentation transcript:

Decisions CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 5, Horstmann* text) *Some slides taken from Horstmann’s notes

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 2 Conditional Execution Sometimes we want a statement executed only when a condition is met Java structures for conditions The if-statement boolean variables, operators, expressions, and methods The ? Operator The switch-statement

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 3 The if-statement Syntax if (condition) statement Notes parentheses are required around the condition statement means any valid statement in Java (including if-statements and blocks)

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 4 Example 1 public class BankAccount { private double balance;... public void withdraw( double amount ) { if ( amount <= balance ) balance = balance - amount; System.out.println( “End of Transaction” ); // print statement executed unconditionally }... }

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 5 Example 2 public class BankAccount { private double balance;... public void withdraw( double amount ) { if ( amount <= balance ) balance = balance - amount; if ( amount > balance ) balance = balance – OVERDRAFT_PENALTY; }... }

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 6 The optional else clause If-statement syntax revisited if (condition) statement else statement Use whenever an alternative statement should be executed when the condition is not met

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 7 Example 2, revised; Using the else public class BankAccount { private double balance;... public void withdraw( double amount ) { if ( amount <= balance ) balance = balance - amount; else balance = balance – OVERDRAFT_PENALTY; }... }

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 8 Example 3 public class BankAccount { private double balance;... public void withdraw( double amount ) { if ( amount <= balance ) balance = balance - amount; else System.out.println( “Insufficient Balance” ); System.out.println( “End of Transaction” ); }... } No penalty is applied but an error message is printed when the condition is not met

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 9 Example 4 Suppose two statements need to be conditionally executed Incorrect attempt if ( amount <= balance ) balance = balance - amount; System.out.println(“amount deducted”); Print statement will be executed unconditionally

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 10 Block of Statements A block allows us to group several statements into one place the statements in sequence and surround them with { } Correct code if ( amount <= balance ) { balance = balance - amount; System.out.println(“amount deducted”); }

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 11 Brace layout, White spaces and Indentation In Java, spaces, tabs, and extra lines don’t affect the meaning of the program A program could be written in diff ways; e.g., all in one line such that each word/symbol is in one line such that words/symbols are separated by 5 spaces each BUT … Spaces (indentation) help to clarify intent

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 12 Brace layout if (amount <= balance) { double newBalance = balance – amount; balance = newBalance; } OR if (amount <= balance) { double newBalance = balance – amount; balance = newBalance; }

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 13 Indentation and tabs public class BankAccount { private int balance;... public void withdraw( int amount ) { if ( amount <= balance )` balance = balance - amount; else balance = balance – OVERDRAFT_PENALTY; }... } Two to three spaces per indentation

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 14 Indentation and tabs public class BankAccount { private int balance;... public void withdraw( int amount ) { if ( amount <= balance ) balance = balance - amount; else balance = balance – OVERDRAFT_PENALTY; }... } Eight spaces per indentation You can use the space bar or the tab key to indent your code

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 15 Relational Operators Compares two (usually numeric) operands >, >=, <, <=, == (equal), != (not equal) Example: >= binary operation returns a boolean result true if left operand is greater than or equal to right operand false otherwise

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 16 Comparing floating-point numbers Consider this code: double r = Math.sqrt(2); double d = r * r - 2; if (d == 0) System.out.println( "sqrt(2)squared minus 2 is 0" ); else System.out.println( "sqrt(2)squared minus 2 is not 0 but " + d ); It prints: sqrt(2)squared minus 2 is not 0 but E-16

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 17 Comparing floating-point numbers To avoid roundoff errors, don't use == to compare floating-point numbers To compare floating-point numbers, test whether they are close enough: |x - y| ≤ ε final double EPSILON = 1E-14; if (Math.abs(x - y) <= EPSILON) // x is approximately equal to y ε is a small number such as 10-14

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 18 Comparing strings Don't use == for strings! if (input == "Y") // WRONG!!! Use equals method: if (input.equals("Y")) == tests identity, equals() tests for equal contents Case insensitive test ("Y" or "y") if (input.equalsIgnoreCase("Y"))

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 19 Comparing strings (cont.) s.compareTo(t) < 0 means: s comes before t in the dictionary "car" comes before "cargo" All uppercase letters come before lowercase: "Hello" comes before "car"

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 20 Lexicographic comparison

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 21 Comparing objects Since object variables contain references, == tests for identity, not for identical object content BankAccount b = new BankAccount( 1000 ); BankAccount c = new BankAccount( 1000 ); Object references are not the same b != c But contents are equal b.getBalance() == c.getBalance()

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 22 null reference refers means no object String middleInitial = null; // Not set if (... ) middleInitial = middleName.substring(0, 1); Can be used in tests: if (middleInitial == null) System.out.println(firstName + " " + lastName); else System.out.println(firstName + " " + middleInitial + ". " + lastName); Use ==, not equals(), to test for null Note that null is not the same as the empty string "" Testing for null

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 23 Sequences of comparisons if (condition1) statement1; else if (condition2) statement2;... else statementn; -The statement that corresponds to the first matching condition is executed -Also called an if-else chain

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 24 Example 5 if ( score >= 92 ) System.out.println( “A” ); else if ( score >= 80 ) System.out.println( “B” ); else if ( score >= 70 ) System.out.println( “C” ); else if ( score >= 60 ) System.out.println( “D” ); else System.out.println( “F” );

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 25 About the if-else chain Order matters if (score >= 60) System.out.println( “D” ); else if (score >= 70) System.out.println( “C” ); … // most students will get D’s See richter’s scale example in the textbook for another if-else chain The if-else chain is an example of a nested branch

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 26 Nested branches Branch inside another branch if (condition0) if (condition1) statement1a; else statement1b; else statement2; else portion could also contain a nested branch; e.g., if (condition2) statement2a; else statement2b;

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 27 Example 6 Movie ticket price example Premium movie (first week of release): P120 Regular movie (second week of release or later): P100 Senior citizen discount: 20%

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 28 Example 6 public double TicketPrice( int customerAge, int daysShowing ) { double cost; if (customerAge >= 60) if ( daysShowing < 8 ) cost = * 0.80; else cost = * 0.80; else if ( daysShowing < 8 ) cost = 100.0; else cost = 120.0; return cost; }

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 29 The boolean Data Type Only two possible values true and false Literals true, false lowercase (reserved words in Java) Operations relational operators logical operators

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 30 Logical Operators Boolean operands && (and), || (or), ! (unary not) Example ((x>=0) && (x<=9)) Truth table depicts semantics of the operation similar to a multiplication/addition table

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 31 ! (NOT) Unary operation Returns a boolean result true when the operand is false false when the operand is true Example alternative to != (a != 5) same as (!(a == 5))

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 32 && (AND) Returns a boolean result true whenever both operands are true false otherwise Example: testing whether a number is between 0 and 9 if ((num >= 0) && (num <= 9))... // inclusive Truth Table? ABA && Bfalse falsetrue truefalsetrue false true

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 33 || (OR) Returns a boolean result true when at least one operand is true false otherwise Example if ((num % 2 == 0) || (num % 3 == 0)) … condition will evaluate to true if the number is a even or if it is a multiple of 3 Truth Table? ABA || Bfalse falsetrue truefalsetrue false true

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 34 Short-Circuit Evaluation Sometimes, we know the result of a boolean expression without checking all the conditions AND ( && ): If first condition is false, then result is false regardless of second condition ( x < y ) && ( a < b ) OR (||): If first condition is true, then result is true regardless of second condition ( x < y ) || ( a < b ) Short-circuit evaluation can prevent errors ( x 20 ) ( x != 0 ) && ( y/x > 20 )

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 35 Boolean Variables Boolean variables are convenient for long conditions Example boolean withinRange; … withinRange = ( num >= 0 ) && ( num <= 9 ); if ( withinRange )...

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 36 Methods with boolean return values Methods can return boolean-type values Allows you to encapsulate complex conditions, or conditions that depend on the state of an object

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 37 Example 7 public class BankAccount {... public static final double MINBAL = 10000;... public boolean isBelowMinBalance() { if ( balance < MINBAL ) return true; else return false; }... } It is common and recommended practice to give boolean-type methods names starting with isXXX Is there a shorter way to write this?

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 38 Example 7, revised public class BankAccount {... public static final double MINBAL = 10000;... public boolean isBelowMinBalance() { return (balance < MINBAL); }... }

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 39 Calling a boolean-type method public class BankSystem { public static void main( String args[] ) { BankAccount b = new BankAccount();... boolean below = b.isBelowMinBalance(); if ( below ) System.out.println( “account is below balance” ); else System.out.println( “account is OK” );... }

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 40 Calling a boolean-type method within the same class public class BankAccount {... public void withdraw( double amount ) { if ( amount <= balance ) { balance = balance - amount; if ( isBelowMinBalance() ) balance = balance – 50; // subtract penalty } else System.out.println( “Insufficient Balance” ); }... }

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 41 Advanced Topics Dangling Else The ? operator The switch statement

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 42 Dangling Else if ( num > 10 ) if ( num > 100 ) System.out.println( “Large” ); else System.out.println( “Small” ); What gets printed out when num = 150? when num = 80? when num = 5? Which if does the else clause match?

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 43 Dangling Else, continued Rule in Java: an else clause matches the nearest enclosing if Use { } to match the outer if if ( num > 10 ) { if ( num > 100 ) System.out.println( “Large” ); } else System.out.println( “Small” );

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 44 The ? operator Syntax: condition ? then-value : else-value Use this as a one-line replacement for if Instead of String s; if ( x % 2 == 0 ) s = “even”; else s = “odd”; We can say String s = (x%2 == 0) ? “even” : “odd”; Commonly used in C programs Use sparingly, since it can lead to cryptic code

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 45 The if-else chain revisited If the conditions in an if-else chain are exact comparisons (using ==) on integral (or char) values, consider using a switch statement Example: print “One” if the value is 1, print “Two” if the value if 2, …

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 46 Example 8 if (num == 1) { System.out.println(“One”); } else if (num == 2) { System.out.println(“Two”); } else if (num == 3) { System.out.println(“Three”); } else { System.out.println(“Other number”); }

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 47 Example 8, revised; using a switch switch(num) { case 1: System.out.println(“One”); break; case 2: System.out.println(“Two”); break; case 3: System.out.println(“Three”); break; default: System.out.println(“Other number”); }

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 48 The switch statement Use a switch statement whenever the conditions in an if-else chain are designed to check for constant values representing a finite number of cases Switch-case statement switch( exp ) exp must be a “countable” primitive type (i.e., byte, int, char, etc., but not float or double) CANNOT be a String case literal serves as “entry-point” label for case when exp==literal break; statement that causes control to exit the block if there’s no break, control “falls-through” until we see a break

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Decisions Slide 49 Using (or not using) break switch( letter ) { case ‘a’: case ‘e’: case ‘i’: case ‘o’: case ‘u’: System.out.println(“Vowel”); break; default: System.out.println(“Consonant”); }