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.

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

String and Object Comparison Comparison operator.
Math 130 Decisions II Wed, Sept 12, 2007 Notes: ref. C. Horstmann, Java Concepts.
Chapter 5 – Decisions Big Java by Cay Horstmann
Chapter 6 Horstmann Programs that make decisions: the IF command.
Chapter 5  Decisions 1 Chapter 5 Decisions. Chapter 5  Decisions 2 Chapter Goals  To be able to implement decisions using if statements  To understand.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
If Statement if (amount
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Chapter 5 – Decisions Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
C++ for Engineers and Scientists Third Edition
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.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
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.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
1 Chapter 7: Advanced Control Flow  Chapter Goals To recognize the correct ordering of decisions in multiple branchesTo recognize the correct ordering.
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
©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.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
1 Chapter 4: Basic Control Flow ► Chapter Goals  To be able to implement decisions using if statements  To understand statement blocks  To learn how.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
If Statement if (amount
Chapter Making Decisions 4. Relational Operators 4.1.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
Week 7 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 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.
1 CSC 221: Computer Programming I Fall 2005 Class design & strings  design principles  cohesion & coupling  class examples: Hurricane, TaxReturn  objects.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Week 7 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Decisions Bush decision making.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
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.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Chapter 4: Control Structures I
Chapter Goals To implement decisions using if statements
Chapter 4: Control Structures I
Program Control Flow: Making Decision
5.3 Multiple Alternatives (Part 1)
Chapter 4: Making Decisions.
Chapter 5 – Decisions.
2.5 Another Java Application: Adding Integers
Nested Branches Nested set of statements: Example: Federal Income Tax
Chapter 4: Making Decisions.
Chapter 5/6 Decisions.
Selected Topics From Chapter 6 Iteration
Chapter 4: Control Structures I
Control Structure Chapter 3.
Chapter 5 – Decisions Big Java by Cay Horstmann
Chapter 2 Programming Basics.
Chapter 6 - Decisions.
Chapter 5 – Decisions Big Java by Cay Horstmann
Control Structure.
Presentation transcript:

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 to group statements into blocks To understand how to group statements into blocks To learn how to compare integers, floating- point numbers, strings, and objects To learn how to compare integers, floating- point numbers, strings, and objects To recognize the correct ordering of decisions in multiple branches To recognize the correct ordering of decisions in multiple branches To program conditions using Boolean operators and variables To program conditions using Boolean operators and variables

if Statement if (amount <= balance) balance = balance - amount; if/else Statement if (amount <= balance) balance = balance - amount; else balance = balance - OVERDRAFT_PENALTY; Flowchart

Syntax 5.1. The if Statement Syntax: Syntax: Format 1: Format 1: if (condition) statement Format 2: Format 2: if (condition) statement1 else statement2 Example: Example: Format 1: Format 1: if (amount <= balance) balance = balance - amount; Format 2: Format 2: if (amount <= balance) balance = balance - amount; else balance = balance - OVERDRAFT_PENALTY; Purpose: Purpose: To execute a statement when a condition is true or false

Syntax 5.2. Block Statement Syntax: Syntax: { statement... } Example: Example: if (amount <= balance) { double newBalance = balance - amount; double newBalance = balance - amount; balance = newBalance; balance = newBalance;} Purpose: To group several statements together to form a single statement Purpose: To group several statements together to form a single statement

Statement Types  Simple statement balance = balance - amount;  Compound statement if (balance >= amount) balance = balance - amount;  Also while, for, etc. (see chapter 6)  Block statement { double newBalance = balance - amount; balance = newBalance; }

Relational Operators Equality Testing vs. Assignment The == operator tests for equality: if (x == 0).. // if x equals zero The == operator tests for equality: if (x == 0).. // if x equals zero The = operator assigns a value to a variable: x = 0; // assign 0 to x The = operator assigns a value to a variable: x = 0; // assign 0 to x Java == is the same as mathematical = Java == is the same as mathematical =

Comparing Floating-Point Numbers  Consider the code: double r = Math.sqrt(2); double d = r * r -2; if (d == 0) System.out.println( "sqrt(2)squared minus 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); 2 is not 0 but " + d); It prints: sqrt(2)squared minus 2 is not 0 but E-16 It prints: sqrt(2)squared minus 2 is not 0 but E-16  Don't use == to compare floating-point numbers  Two numbers are close to one another if |x - y| <= ε  ε is a small number such as  Not good enough if x, y very large or very small. Then use |x - y| / max(|x|, |y|) <= ε  But if one of the numbers is zero, don't divide by max(|x |, |y|)

String Comparison  Don't use == for strings! if (input == "Y") // WRONG!!!  Use equals method: if (input.equals("Y"))  == tests identity, equals tests equal contents  Case insensitive test ("Y" or "y") if (input.equalsIgnoreCase(“Y"))  Lexicographic Comparison  s.compareTo(t) < 0 means: s comes before t in the dictionary  "car"comes before "cargo" "cargo" comes before "cathode"  All uppercase letters come before lowercase "Hello" comes before "car"

Object Comparison  == tests for identity, equals for identical content  Rectangle cerealBox = new Rectangle(5, 10, 20, 30); Rectangle oatmealBox = new Rectangle(5, 10, 20, 30); Rectangle r = cerealBox;  cerealBox != oatmealBox, but cerealBox.equals(oatmealBox)  cerealBox == r and cerealBox.equals(r)  Caveat: equals must be defined for the class (see chapter 11)

The null Reference  null reference refers to no object at all  Can be used in tests: if (account == null)...  Use ==, not equals, to test for null  showInputDialog returns null if the user hit the cancel button: String input = JOptionPane.showInputD ialog("..."); if (input != null) {... }  null is not the same as the empty string "" Multiple Alternatives if (condition1) statement1; else if (condition2) statement2; else if (condition3) statement3; else statement4; if (condition1) statement1; else if (condition2) statement2; else if (condition3) statement3; else statement4; The first matching condition is executed. The first matching condition is executed. Order matters. Order matters.

Earthquake.java 1 /** 2 A class that describes the effects of an earthquake. 3 */ 4 public class Earthquake 5 { 6 /** 7 Constructs an Earthquake object. magnitude the magnitude on the Richter scale 9 */ 10 public Earthquake(double magnitude) 11 { 12 richter = magnitude; 13 } 15 /** 16 Gets a description of the effect of the earthquake. the description of the effect 18 */ 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 } 39 private double richter; 40 }

EarthquakeTest.java 1 import javax.swing.JOptionPane; 3 /** 4 A class to test the Earthquake class. 5 */ 6 public class EarthquakeTest 7 { 8 public static void main(String[] args) 9 { 10 String input = JOptionPane.showInputDialog( 11 "Enter a magnitude on the Richter scale:"); 12 double magnitude = Double.parseDouble(input); 13 Earthquake quake = new Earthquake(magnitude); 14 System.out.println(quake.getDescription()); 15 System.exit(0); 16 } 17 }

Multiple Alternatives  Order matters: 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";...  Don't omit else if (richter >= 8.0) r = "Most structures fall"; if (richter >= 7.0) // omitted else--ERROR r = "Many buildings destroyed  Nested Branches: Branch inside another branch if (condition1) { if (condition1a) statement1a; else statement1b; } else statement2;

An Example: Tax Return If your filing status is Single If your filing status is Single If your filing status is Married If your filing status is Married

Tax Return: Flowchart

TaxReturn.java 1 /** 2 A tax return of a taxpayer in */ 4 class TaxReturn 5 { 6 /** 7 Constructs a TaxReturn object for a given income and marital status. anIncome the taxpayer income aStatus either SINGLE or MARRIED 11 */ 12 public TaxReturn(double anIncome, int aStatus) 13 { 14 income = anIncome; 15 status = aStatus; 16 } 18 public double getTax() 19 { 20 double tax = 0; if (status == SINGLE) 23 { 24 if (income <= SINGLE_CUTOFF1) 25 tax = RATE1 * income; 26 else if (income <= SINGLE_CUTOFF2) 27 tax = SINGLE_BASE RATE2 * (income - SINGLE_CUTOFF1); 29 else 30 tax = SINGLE_BASE RATE3 * (income - SINGLE_CUTOFF2); 32 }

33 else 34 { 35 if (income<=MARRIED_CUTOFF1) 36 tax = RATE1 * income; 37 else if (income<=MARRIED_CUTOFF2) 38 tax = MARRIED_BASE RATE2 * (income - MARRIED_CUTOFF1); 40 else 41tax = MARRIED_BASE RATE3 * (income - MARRIED_CUTOFF2); 43 } 45 return tax; 46 } 48 public static final int SINGLE = 1; 49 public static final int MARRIED = 2; 51 private static final double RATE1 = 0.15; 52 private static final double RATE2 = 0.28; 53 private static final double RATE3 = 0.31; 55 private static final double SINGLE_CUTOFF1 = 21450; 56 private static final double SINGLE_CUTOFF2 = 51900; private static final double SINGLE_BASE2 = ; 59 private static final double SINGLE_BASE3 = ; 60 private static final double MARRIED_CUTOFF1 = 35800; 61 private static final double MARRIED_CUTOFF2 = 86500; 61 private static final double MARRIED_CUTOFF2 = 86500; 63 private static final double MARRIED_BASE2 = 5370; 64 private static final double MARRIED_BASE3 = 19566; private double income; 67 private int status; 68 }

TaxReturnTest.java 1 import javax.swing.JOptionPane; 2 3 /** 4 A class to test the TaxReturn class. 5 */ 6 public class TaxReturnTest 7 { 8 public static void main(String[] args) 9 { 10 String input = JOptionPane.showInputDialog( 11 "Please enter your income:"); 12 double income = Double.parseDouble(input); 14 input = JOptionPane.showInputDialog( 15 "Please enter S (single) or M (married)"); 16 int status = 0; 18 if (input.equalsIgnoreCase("S")) 19 status = TaxReturn.SINGLE; 20 else if (input.equalsIgnoreCase("M")) 21 status = TaxReturn.MARRIED; 22 else 23 { 24 System.out.println("Bad input."); 24 System.out.println("Bad input."); 25 System.exit(0); 26 } 28 TaxReturn aTaxReturn = new TaxReturn(income, status); 30 System.out.println("The tax is " 31 + aTaxReturn.getTax()); 33 System.exit(0); 34 } 35 }

The boolean Type  boolean type:  George Boole ( ): pioneer in the study of logic  value of expression amount < 1000 is true or false.  boolean type: one of these 2 truth values  Predicate Method  return type boolean  Example: public boolean isOverdrawn() { return balance < 0; }  Use in conditions if (aChecking.isOverdrawn())...  Useful predicate methods in Character class: isDigit isLetter isUpperCase isLowerCase  if (Character.isUpperCase(ch))...  boolean Operators  && and  || or  ! not  if (0 < amount && amount < 1000)...  if (input.equals("S") || input.equals("M"))...

&& and || Operators

Truth Tables

De Morgan's Law  Negating a complex condition can be confusing: if (!(0 < amount && amount < 1000))  De Morgan's law states that !(A && B) is the same as !A || !B !(A || B) is the same as !A && !B  Note that the && and || flip when moving the ! inwards  (!(0 = amount || amount >= 1000  Note that the opposite of =

Boolean Variables  private boolean married;  Set to truth value: married = input.equals("M");  Use in conditions: if (married)... else... if (!married)...  Also called flag  Don't test Boolean variables against truth values--sign of cluelessness: if (married == true) // DON'T:  if (married)  if (married == false) // DON'T:  if (!married)  if (married != false) // NO!!!