Decisions Bush decision making.

Slides:



Advertisements
Similar presentations
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. It is common to use two nested loops when filling or searching: for.
Advertisements

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
Math 130 Decisions II Wed, Sept 12, 2007 Notes: ref. C. Horstmann, Java Concepts.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Chapter 5 – Decisions Big Java by Cay Horstmann
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.
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.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Chapter 6 Horstmann Programs that make decisions: the IF command.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Chapter 5  Decisions 1 Chapter 5 Decisions. Chapter 5  Decisions 2 Chapter Goals  To be able to implement decisions using if statements  To understand.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
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.
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 6 Decisions. Chapter Goals To be able to implement decisions using if statements To understand how to group statements into blocks To learn how.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Chapter 5: Decisions. To be able to implement decisions using if statements To understand how to group statements into blocks To learn how to compare.
Chapter 6 - Decisions. Characters char char primitive data type primitive data type stores a single character stores a single character operations (same.
COM S 207 IF Statement Instructor: Ying Cai Department of Computer Science Iowa State University
Chapter 5 Decisions. Assignments  Written exercises pp 217 – 220 R5.1, R5.3, R5.5, R5.6, R5.9 – R5.15, R5.17, R R5.1, R5.3, R5.5, R5.6, R5.9 –
Chapter Goals To implement decisions using if statements
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. if (amount
Decisions CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 5, Horstmann*
Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester,
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
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.
Boolean expressions, part 2: Logical operators. Previously discussed Recall that there are 2 types of operators that return a boolean result (true or.
©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.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
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.
Copyright © 2013 by John Wiley & Sons. All rights reserved. DECISIONS CHAPTER Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 15,
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.
Java Programming Fifth Edition Chapter 5 Making Decisions.
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.
Input Validation 10/09/13. Input Validation with if Statements You, the C++ programmer, doing Quality Assurance (by hand!) C++ for Everyone by Cay Horstmann.
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.
Control statements Mostafa Abdallah
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC INTRO TO COMPUTING - PROGRAMMING If Statement.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
Decision Statements, Short- Circuit Evaluation, Errors.
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 5 - Decisions.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
CS0007: Introduction to Computer Programming
Chapter Goals To implement decisions using if statements
5.3 Multiple Alternatives (Part 1)
Chapter 5 – Decisions.
Lecture 2: Data Types, Variables, Operators, and Expressions
Chapter 5/6 Decisions.
Control Structure Chapter 3.
Chapter 5 – Decisions Big Java by Cay Horstmann
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 6 - Decisions.
Chapter 5 – Decisions Big Java by Cay Horstmann
Control Structure.
Presentation transcript:

Decisions

Bush decision making

The if Statement The if statement lets a program carry out different actions depending on a condition Continued… if (amount <= balance) balance = balance - amount;

The if/else Statement Continued… if (amount <= balance) balance = balance - amount; else balance = balance - OVERDRAFT_PENALTY;

Alternative to series of if/else statements Switch statement int digit; switch (digit) { case 1: System.out.println(“one”); break; case 2: System.out.println(“two”); break; Default: System.out.println(“Invalid input”); } Limited: test case must be integer, character or enumerated constant

Comparing Values: Relational Operators Relational operators compare values and evaluate to a Boolean The == denotes equality testing JavaMath NotationDescription >>Greater than >=≥Greater than or equal <<Less than <=≤Less than or equal ===Equal !=≠Not equal a = 5; // Assign 5 to a if (a == 5)... // Test whether a equals 5

More with Using Boolean Expressions: Predicate Method A predicate method returns a boolean value Use in conditions public boolean isOverdrawn() { return balance < 0; } if (harrysChecking.isOverdrawn())... Continued…

Using Boolean Expressions: Predicate Method Useful predicate methods in Character class: Useful predicate methods in Scanner class: hasNextInt() and hasNextDouble() isDigit isLetter isUpperCase isLowerCase if (Character.isUpperCase(ch))... if (in.hasNextInt()) n = in.nextInt();

Using Boolean Expressions: The Boolean Operators && and || or ! Not if (0 < amount && amount < 1000)... if (input.equals("S") || input.equals("M"))...

&& and || Operators Figure 6: Flowcharts for && and || Combinations

Truth Tables AB A || B TrueAnyTrue FalseTrue False AB A && B True False AnyFalse A !A!A TrueFalse True

Lazy Evaluation Logical expressions are evaluated left to right and evaluations stops as soon as truth value is determined If (a || b) - if a evaluates to true, b will never be evaluated If (a && b) - if a evaluates to false, b will never be evaluated

DeMorgan’s Law !(a && b) is equivalent to !a || !b !(a || b) is equivalent to !a && !b

Using Boolean Variables Set to truth value: Use in conditions: married = input.equals("M"); private boolean married; if (married)... else... if (!married)...

Using Boolean Variables Also called flag It is considered gauche to write a test such as Just use the simpler test if (married == true)... // Don't if (married)...

Self Check 7.When does the statement print false ? 8.Rewrite the following expression, avoiding the comparison with false : system.out.println (x > 0 || x < 0); if (Character.isDigit(ch) == false)...

Answers 7.When x is zero 8. if (!Character.isDigit(ch))...

Truth Tables AB A || B True FalseTrue FalseTrue False AB A && B True False TrueFalse A !A!A TrueFalse True

Java’s Precedence Highest precedence Unary operators: ++, --, !, unary - and +, type-cast Multiplication and division: *, /, % Addition and subtraction: +, - Relational operators:, = Equality and inequality: ==, != Boolean and: && Boolean or: || Conditional operator: ?: Assignment operators: =, +=, -=, *=, /=, %= Lowest precedence

AP Question using DeMorgan’s Law Assume that the boolean variables a, b, c, and d have been declared and initialized. Consider the following expression. !( !( a && b ) || ( c || !d )) Which of the following is equivalent to the expression? (A) ( a && b ) && ( !c && d ) (B) ( a || b ) && ( !c && d ) (C) ( a && b ) || ( c || !d ) (D) ( !a || !b ) && ( !c && d ) (E) !( a && b ) && ( c || !d )

Solution !( !( a && b ) || ( c || !d ))

Another one… Assume that the boolean variables a and b have been declared and initialized. Consider the following expression. (a && (b || !a)) == a && b Which of the following best describes the conditions under which the expression will evaluate to true? (A) Only when a is true (B) Only when b is true (C) Only when both a and b are true (D) The expression will never evaluate to true. (E) The expression will always evaluate to true.

Solution (a && (b || !a)) == a && b

Last one (for now) The Boolean expression (x==y && !(x==y)) ||( x!=y && !(x!=y)) can be simplified to which of the following? A) x != y B) x == y C) true D) false E) x < y

Solution (x==y && !(x==y)) ||( x!=y && !(x!=y))

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 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 Comparing Floating-Point Numbers

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Don't use == for strings! if (input == "Y") // WRONG!!! Use equals method: Boolean if (input.equals("Y")) == tests identity, equals tests equal contents Case insensitive test ("Y" or "y") if (input.equalsIgnoreCase("Y")) s.compareTo(t) < 0 means: int s comes before t in the dictionary Continued Comparing Strings

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. "car" comes before "cargo" All uppercase letters come before lowercase: "Hello" comes before "car" Comparing Strings (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. == tests for identity, equals for identical content Rectangle box1 = new Rectangle(5, 10, 20, 30); Rectangle box2 = box1; Rectangle box3 = new Rectangle(5, 10, 20, 30); box1 != box3, but box1.equals(box3) box1 == box2 Caveat: equals must be defined for the class Comparing Objects

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Object Comparison

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. null reference refers to 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 null is not the same as the empty string "" Testing for null

Multiple Alternatives: Sequences of Comparisons The first matching condition is executed Order matters Continued… if (condition1) statement1; else if (condition2) statement2;... else statement4; if (richter >= 0) // always passes r = "Generally not felt by people"; else if (richter >= 3.5) // not tested r = "Felt by many people, no destruction”;...

Multiple Alternatives: Sequences of Comparisons Don't omit else if (richter >= 8.0) r = "Most structures fall"; if (richter >= 7.0) // omitted else--ERROR r = "Many buildings destroyed”;

File Earthquake.java 01: /** 02: A class that describes the effects of an earthquake. 03: */ 04: public class Earthquake 05: { 06: /** 07: Constructs an Earthquake object. magnitude the magnitude on the Richter scale 09: */ 10: public Earthquake(double magnitude) 11: { 12: richter = magnitude; 13: } 14: 15: /** 16: Gets a description of the effect of the earthquake. the description of the effect 18: */ Continued…

File Earthquake.java 19: public String getDescription() 20: { 21: String r; 22: if (richter >= 8.0) 23: r = "Most structures fall"; 24: else if (richter >= 7.0) 25: r = "Many buildings destroyed"; 26: else if (richter >= 6.0) 27: r = "Many buildings considerably damaged, some collapse"; 28: else if (richter >= 4.5) 29: r = "Damage to poorly constructed buildings"; 30: else if (richter >= 3.5) 31: r = "Felt by many people, no destruction"; 32: else if (richter >= 0) 33: r = "Generally not felt by people"; 34: else 35: r = "Negative numbers are not valid"; 36: return r; 37: } Continued…

File Earthquake.java 38: 39: private double richter; 40: }

File EarthquakeTester.java 01: import java.util.Scanner; 02: 03: /** 04: A class to test the Earthquake class. 05: */ 06: public class EarthquakeTester 07: { 08: public static void main(String[] args) 09: { 10: Scanner in = new Scanner(System.in); 11: 12: System.out.print("Enter a magnitude on the Richter scale: "); 13: double magnitude = in.nextDouble(); 14: Earthquake quake = new Earthquake(magnitude); 15: System.out.println(quake.getDescription()); 16: } 17: }

Multiple Alternatives: Nested Branches Branch inside another branch if (condition1) { if (condition1a) statement1a; else statement1b; } else statement2;