SlideShare a Scribd company logo
1 of 33
Copyright © 2014 by John Wiley & Sons. All rights reserved. 1
Chapter 5 - Decisions
Copyright © 2014 by John Wiley & Sons. All rights reserved. 2
Chapter Goals
 To implement decisions using if statements
 To compare integers, floating-point numbers, and strings
 To write statements using the boolean data type
 To develop strategies for testing your programs
 To validate user input
Copyright © 2014 by John Wiley & Sons. All rights reserved. 7
Syntax 5.1 The if Statement
Copyright © 2014 by John Wiley & Sons. All rights reserved. 15
Avoid Duplication in Branches
 If you have duplicate code in each branch, move it out of the if statement.
 Don't do this
if (floor > 13)
{
actualFloor = floor – 1;
System.out.println("Actual floor: " + actualFloor);
}
else
{
actualFloor = floor;
System.out.println("Actual floor: " + actualFloor);
}
 Instead do this:
if (floor > 13)
{
actualFloor = floor – 1;
}
else
{
actualFloor = floor;
}
System.out.println("Actual floor: " + actualFloor);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 18
What can be a Boolean Expression
 Boolean literals: true ,false
 Expressions with relational (comparison) operators
 Variables of boolean type
 Logical operators: && (and) , || (or), ! (not)
 Calls to boolean methods
Copyright © 2014 by John Wiley & Sons. All rights reserved. 19
Comparing Values: Relational Operators
 Relational operators compare values:
 The == denotes equality testing:
floor = 13; // Assign 13 to floor
if (floor == 13) // Test whether floor equals 13
 Relational operators have lower precedence than arithmetic
operators:
floor - 1 < 13
Copyright © 2014 by John Wiley & Sons. All rights reserved. 20
Syntax 5.2 Comparisons
Copyright © 2014 by John Wiley & Sons. All rights reserved. 21
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 4.440892098500626E-16
 This is due to round-off errors
 When comparing floating-point numbers, don’t test for
equality.
• Check whether they are close enough.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 22
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 commonly set to 10-14
Copyright © 2014 by John Wiley & Sons. All rights reserved. 23
Comparing Strings
 To test whether two strings are equal to each other, use
equals method:
if (string1.equals(string2)) . . .
 Don't use == for strings!
if (string1 == string2) // Not useful
 == tests if two strings are stored in the same memory location
 equals method tests equal contents
Copyright © 2014 by John Wiley & Sons. All rights reserved. 24
Comparing Strings – compareTo Method
 compareTo method compares strings in lexicographic order -
dictionary order.
 string1.compareTo(string2) < 0 means:
• string1 comes before string2 in the dictionary
 string1.compareTo(string2) > 0 means:
• string1 comes after string2 in the dictionary
 string1.compareTo(string2) == 0 means:
• string1 and string2 are equal
Copyright © 2014 by John Wiley & Sons. All rights reserved. 25
 Lexicographic Ordering
Lexicographic Ordering
Copyright © 2014 by John Wiley & Sons. All rights reserved. 26
 Differences in dictionary ordering and ordering in Java
• All uppercase letters come before the lowercase letters. "Z" comes
before "a"
• The space character comes before all printable characters
• Numbers come before letters
• Ordering of punctuation marks varies
 To see which of two terms comes first in the dictionary,
consider the first letter in which they differ
Lexicographic Ordering
Copyright © 2014 by John Wiley & Sons. All rights reserved. 27
Comparing Objects
 The == operator tests whether two object references are
identical,
• whether they refer to the same object.
 Look at this code
Rectangle box1 = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box1;
Rectangle box3 = new Rectangle(5, 10, 20, 30);
• box1 == box2 is true
• box1 == box3 is false
 Use the equals method to test if two rectangles have the same
content
box1.equals(box3)
• They have the same upper-left corner and the same width and height
 Caveat: equals must be defined for the class
Copyright © 2014 by John Wiley & Sons. All rights reserved. 28
Object Comparison
Copyright © 2014 by John Wiley & Sons. All rights reserved. 29
Testing for null
 null reference refers to no object:
String middleInitial = null; // Not set
if ( . . . )
{
middleInitial = middleName.substring(0, 1);
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 30
Testing for null
 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 ""
 Attempt to access object through null throws exception
Copyright © 2014 by John Wiley & Sons. All rights reserved. 40
Multiple Alternatives: Sequences of
Comparisons
 Example: damage done by earthquake of a given magnitude on
the Richter scale:
if (richter >= 8.0)
{
description = "Most structures fall”;
}
else if (richter >= 7.0)
{
description = "Many buildings destroyed”;
}
else if (richter >= 6.0)
{
description = "Many buildings considerably damaged, some collapse”;
}
else if (richter >= 4.5)
{
description = "Damage to poorly constructed buildings”;
}
else
{
description = "No destruction of buildings”;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 43
Multiple Alternatives - Flowchart
Copyright © 2014 by John Wiley & Sons. All rights reserved. 44
Multiple Alternatives: Cascaded If’s
 The order of the if and else if matters
 Error
if (richter >= 4.5) // Tests in wrong order
{
description = "Damage to poorly constructed buildings”;
}
else if (richter >= 6.0)
{
description = "Many buildings considerably damaged, some collapse”;
}
else if (richter >= 7.0)
{
description = "Many buildings destroyed”;
}
else if (richter >= 8.0)
{
description = "Most structures fall”;
}
 When using multiple if statements, test general conditions after
more specific conditions.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 45
Multiple Alternatives
 In this example, must use if/else if/else sequence, not just
multiple independent if statements
 Error
if (richter >= 8.0) // Didn't use else
{
description = "Most structures fall”;
}
if (richter >= 7.0)
{
description = "Many buildings destroyed”;
}
if (richter >= 6.0)
{
description = "Many buildings considerably damaged, some collapse”;
}
if (richter >= 4.5)
{
"Damage to poorly constructed buildings”;
}
 The alternatives are no longer exclusive.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 52
Nested Branches
 Nested set of statements:
• An if statement inside another
 Example: Federal Income Tax
• Tax depends on marital status and income
Copyright © 2014 by John Wiley & Sons. All rights reserved. 54
Nested Branches - Flowchart
Copyright © 2014 by John Wiley & Sons. All rights reserved. 55
section_4/TaxReturn.java
1 /**
2 A tax return of a taxpayer in 2008.
3 */
4 public class TaxReturn
5 {
6 public static final int SINGLE = 1;
7 public static final int MARRIED = 2;
8
9 private static final double RATE1 = 0.10;
10 private static final double RATE2 = 0.25;
11 private static final double RATE1_SINGLE_LIMIT = 32000;
12 private static final double RATE1_MARRIED_LIMIT = 64000;
13
14 private double income;
15 private int status;
16
17 /**
18 Constructs a TaxReturn object for a given income and
19 marital status.
20 @param anIncome the taxpayer income
21 @param aStatus either SINGLE or MARRIED
22 */
23 public TaxReturn(double anIncome, int aStatus)
24 {
25 income = anIncome;
26 status = aStatus;
27 }
28
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 56
section_4/TaxReturn.java
29 public double getTax()
30 {
31 double tax1 = 0;
32 double tax2 = 0;
33
34 if (status == SINGLE)
35 {
36 if (income <= RATE1_SINGLE_LIMIT)
37 {
38 tax1 = RATE1 * income;
39 }
40 else
41 {
42 tax1 = RATE1 * RATE1_SINGLE_LIMIT;
43 tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT);
44 }
45 }
46 else
47 {
48 if (income <= RATE1_MARRIED_LIMIT)
49 {
50 tax1 = RATE1 * income;
51 }
52 else
53 {
54 tax1 = RATE1 * RATE1_MARRIED_LIMIT;
55 tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT);
56 }
57 }
58
59 return tax1 + tax2;
60 }
61 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 80
Boolean Variables and Operators
 To store the evaluation of a logical condition that can be true or false,
you use a Boolean variable.
 The boolean data type has exactly two values, denoted false and
true.
boolean failed = true;
Boolean negative = x < 0;
 Later in your program, use the value to make a decision
if (failed==true) // Only executed if failed has been set to true
{ . . . }
 A Boolean variable is also called a flag because it can be either up
(true) or down (false).
Copyright © 2014 by John Wiley & Sons. All rights reserved. 81
Boolean Variables and Operators
 You often need to combine Boolean values when making
complex decisions
 An operator that combines Boolean conditions is called a
Boolean operator.
 The && operator is called and
• Yields true only when both conditions are true.
 The || operator is called or
• Yields the result true if at least one of the conditions is true.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 82
Boolean Variables and Operators
 To test if water is liquid at a given temperature
if (temp > 0 && temp < 100)
{
System.out.println("Liquid");
}
 Flowchart
Copyright © 2014 by John Wiley & Sons. All rights reserved. 83
Boolean Variables and Operators
 To test if water is not liquid at a given temperature
if (temp <= 0 || temp >= 100)
{
System.out.println(“Not liquid");
}
 Flowchart
Copyright © 2014 by John Wiley & Sons. All rights reserved. 84
Boolean Variables and Operators
Copyright © 2014 by John Wiley & Sons. All rights reserved. 85
Boolean Variables and Operators
 To invert a condition use the not Boolean operator
 The ! operator takes a single condition
• Evaluates to true if that condition is false and
• Evaluates to false if the condition is true
 To test if the Boolean variable frozen is false:
if (!frozen) { System.out.println("Not frozen"); }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 86
Logical Identities
 true && A yields A
 false && A yields false
 True || A yields true
 False || A yields A
 B == true yields B
 !(A && B) == (!A || !B)
 !(A || B) == (!A && !B)
Let A, B be an arbitrary boolean expressions:
Short Circuit Evaluation: Only evaluate what is required to determine truth value
Copyright © 2014 by John Wiley & Sons. All rights reserved. 87
De Morgan’s Law in Action
if ((obj != null) && (obj.getSomething() > 0)) {
// CODE
else
// Is obj == null here??

More Related Content

What's hot

What's hot (20)

Icom4015 lecture3-f16
Icom4015 lecture3-f16Icom4015 lecture3-f16
Icom4015 lecture3-f16
 
CIIC 4010 Chapter 1 f17
CIIC 4010 Chapter 1 f17CIIC 4010 Chapter 1 f17
CIIC 4010 Chapter 1 f17
 
CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17
 
Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016
 
Icom4015 lecture8-f16
Icom4015 lecture8-f16Icom4015 lecture8-f16
Icom4015 lecture8-f16
 
Icom4015 lecture7-f16
Icom4015 lecture7-f16Icom4015 lecture7-f16
Icom4015 lecture7-f16
 
Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016
 
Icom4015 lecture14-f16
Icom4015 lecture14-f16Icom4015 lecture14-f16
Icom4015 lecture14-f16
 
Icom4015 lecture10-f16
Icom4015 lecture10-f16Icom4015 lecture10-f16
Icom4015 lecture10-f16
 
Icom4015 lecture11-s16
Icom4015 lecture11-s16Icom4015 lecture11-s16
Icom4015 lecture11-s16
 
Chapter 4 Powerpoint
Chapter 4 PowerpointChapter 4 Powerpoint
Chapter 4 Powerpoint
 
06slide
06slide06slide
06slide
 
07slide
07slide07slide
07slide
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
C sharp chap4
C sharp chap4C sharp chap4
C sharp chap4
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONSVISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
 

Similar to Icom4015 lecture4-f16

chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)It Academy
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and StringsIt Academy
 
Chapter 3 : Programming with Java Operators and Strings
Chapter 3 : Programming with Java Operators and  StringsChapter 3 : Programming with Java Operators and  Strings
Chapter 3 : Programming with Java Operators and StringsIt Academy
 
Programming in Java: Control Flow
Programming in Java: Control FlowProgramming in Java: Control Flow
Programming in Java: Control FlowMartin Chapman
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statementsmaznabili
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysDevaKumari Vijay
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My HeartBui Kiet
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupDror Helper
 
Java_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.pptJava_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.pptGovind Samleti
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenGraham Royce
 

Similar to Icom4015 lecture4-f16 (20)

chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and Strings
 
Chapter 3 : Programming with Java Operators and Strings
Chapter 3 : Programming with Java Operators and  StringsChapter 3 : Programming with Java Operators and  Strings
Chapter 3 : Programming with Java Operators and Strings
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Programming in Java: Control Flow
Programming in Java: Control FlowProgramming in Java: Control Flow
Programming in Java: Control Flow
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statements
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Chapter3
Chapter3Chapter3
Chapter3
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
Ch3
Ch3Ch3
Ch3
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Java unit 3
Java unit 3Java unit 3
Java unit 3
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet Soup
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.pptJava_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.ppt
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 
Java tut1
Java tut1Java tut1
Java tut1
 
Javatut1
Javatut1 Javatut1
Javatut1
 

Recently uploaded

Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfrs7054576148
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 

Recently uploaded (20)

Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdf
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 

Icom4015 lecture4-f16

  • 1. Copyright © 2014 by John Wiley & Sons. All rights reserved. 1 Chapter 5 - Decisions
  • 2. Copyright © 2014 by John Wiley & Sons. All rights reserved. 2 Chapter Goals  To implement decisions using if statements  To compare integers, floating-point numbers, and strings  To write statements using the boolean data type  To develop strategies for testing your programs  To validate user input
  • 3. Copyright © 2014 by John Wiley & Sons. All rights reserved. 7 Syntax 5.1 The if Statement
  • 4. Copyright © 2014 by John Wiley & Sons. All rights reserved. 15 Avoid Duplication in Branches  If you have duplicate code in each branch, move it out of the if statement.  Don't do this if (floor > 13) { actualFloor = floor – 1; System.out.println("Actual floor: " + actualFloor); } else { actualFloor = floor; System.out.println("Actual floor: " + actualFloor); }  Instead do this: if (floor > 13) { actualFloor = floor – 1; } else { actualFloor = floor; } System.out.println("Actual floor: " + actualFloor);
  • 5. Copyright © 2014 by John Wiley & Sons. All rights reserved. 18 What can be a Boolean Expression  Boolean literals: true ,false  Expressions with relational (comparison) operators  Variables of boolean type  Logical operators: && (and) , || (or), ! (not)  Calls to boolean methods
  • 6. Copyright © 2014 by John Wiley & Sons. All rights reserved. 19 Comparing Values: Relational Operators  Relational operators compare values:  The == denotes equality testing: floor = 13; // Assign 13 to floor if (floor == 13) // Test whether floor equals 13  Relational operators have lower precedence than arithmetic operators: floor - 1 < 13
  • 7. Copyright © 2014 by John Wiley & Sons. All rights reserved. 20 Syntax 5.2 Comparisons
  • 8. Copyright © 2014 by John Wiley & Sons. All rights reserved. 21 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 4.440892098500626E-16  This is due to round-off errors  When comparing floating-point numbers, don’t test for equality. • Check whether they are close enough.
  • 9. Copyright © 2014 by John Wiley & Sons. All rights reserved. 22 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 commonly set to 10-14
  • 10. Copyright © 2014 by John Wiley & Sons. All rights reserved. 23 Comparing Strings  To test whether two strings are equal to each other, use equals method: if (string1.equals(string2)) . . .  Don't use == for strings! if (string1 == string2) // Not useful  == tests if two strings are stored in the same memory location  equals method tests equal contents
  • 11. Copyright © 2014 by John Wiley & Sons. All rights reserved. 24 Comparing Strings – compareTo Method  compareTo method compares strings in lexicographic order - dictionary order.  string1.compareTo(string2) < 0 means: • string1 comes before string2 in the dictionary  string1.compareTo(string2) > 0 means: • string1 comes after string2 in the dictionary  string1.compareTo(string2) == 0 means: • string1 and string2 are equal
  • 12. Copyright © 2014 by John Wiley & Sons. All rights reserved. 25  Lexicographic Ordering Lexicographic Ordering
  • 13. Copyright © 2014 by John Wiley & Sons. All rights reserved. 26  Differences in dictionary ordering and ordering in Java • All uppercase letters come before the lowercase letters. "Z" comes before "a" • The space character comes before all printable characters • Numbers come before letters • Ordering of punctuation marks varies  To see which of two terms comes first in the dictionary, consider the first letter in which they differ Lexicographic Ordering
  • 14. Copyright © 2014 by John Wiley & Sons. All rights reserved. 27 Comparing Objects  The == operator tests whether two object references are identical, • whether they refer to the same object.  Look at this code Rectangle box1 = new Rectangle(5, 10, 20, 30); Rectangle box2 = box1; Rectangle box3 = new Rectangle(5, 10, 20, 30); • box1 == box2 is true • box1 == box3 is false  Use the equals method to test if two rectangles have the same content box1.equals(box3) • They have the same upper-left corner and the same width and height  Caveat: equals must be defined for the class
  • 15. Copyright © 2014 by John Wiley & Sons. All rights reserved. 28 Object Comparison
  • 16. Copyright © 2014 by John Wiley & Sons. All rights reserved. 29 Testing for null  null reference refers to no object: String middleInitial = null; // Not set if ( . . . ) { middleInitial = middleName.substring(0, 1); }
  • 17. Copyright © 2014 by John Wiley & Sons. All rights reserved. 30 Testing for null  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 ""  Attempt to access object through null throws exception
  • 18. Copyright © 2014 by John Wiley & Sons. All rights reserved. 40 Multiple Alternatives: Sequences of Comparisons  Example: damage done by earthquake of a given magnitude on the Richter scale: if (richter >= 8.0) { description = "Most structures fall”; } else if (richter >= 7.0) { description = "Many buildings destroyed”; } else if (richter >= 6.0) { description = "Many buildings considerably damaged, some collapse”; } else if (richter >= 4.5) { description = "Damage to poorly constructed buildings”; } else { description = "No destruction of buildings”; }
  • 19. Copyright © 2014 by John Wiley & Sons. All rights reserved. 43 Multiple Alternatives - Flowchart
  • 20. Copyright © 2014 by John Wiley & Sons. All rights reserved. 44 Multiple Alternatives: Cascaded If’s  The order of the if and else if matters  Error if (richter >= 4.5) // Tests in wrong order { description = "Damage to poorly constructed buildings”; } else if (richter >= 6.0) { description = "Many buildings considerably damaged, some collapse”; } else if (richter >= 7.0) { description = "Many buildings destroyed”; } else if (richter >= 8.0) { description = "Most structures fall”; }  When using multiple if statements, test general conditions after more specific conditions.
  • 21. Copyright © 2014 by John Wiley & Sons. All rights reserved. 45 Multiple Alternatives  In this example, must use if/else if/else sequence, not just multiple independent if statements  Error if (richter >= 8.0) // Didn't use else { description = "Most structures fall”; } if (richter >= 7.0) { description = "Many buildings destroyed”; } if (richter >= 6.0) { description = "Many buildings considerably damaged, some collapse”; } if (richter >= 4.5) { "Damage to poorly constructed buildings”; }  The alternatives are no longer exclusive.
  • 22. Copyright © 2014 by John Wiley & Sons. All rights reserved. 52 Nested Branches  Nested set of statements: • An if statement inside another  Example: Federal Income Tax • Tax depends on marital status and income
  • 23. Copyright © 2014 by John Wiley & Sons. All rights reserved. 54 Nested Branches - Flowchart
  • 24. Copyright © 2014 by John Wiley & Sons. All rights reserved. 55 section_4/TaxReturn.java 1 /** 2 A tax return of a taxpayer in 2008. 3 */ 4 public class TaxReturn 5 { 6 public static final int SINGLE = 1; 7 public static final int MARRIED = 2; 8 9 private static final double RATE1 = 0.10; 10 private static final double RATE2 = 0.25; 11 private static final double RATE1_SINGLE_LIMIT = 32000; 12 private static final double RATE1_MARRIED_LIMIT = 64000; 13 14 private double income; 15 private int status; 16 17 /** 18 Constructs a TaxReturn object for a given income and 19 marital status. 20 @param anIncome the taxpayer income 21 @param aStatus either SINGLE or MARRIED 22 */ 23 public TaxReturn(double anIncome, int aStatus) 24 { 25 income = anIncome; 26 status = aStatus; 27 } 28 Continued
  • 25. Copyright © 2014 by John Wiley & Sons. All rights reserved. 56 section_4/TaxReturn.java 29 public double getTax() 30 { 31 double tax1 = 0; 32 double tax2 = 0; 33 34 if (status == SINGLE) 35 { 36 if (income <= RATE1_SINGLE_LIMIT) 37 { 38 tax1 = RATE1 * income; 39 } 40 else 41 { 42 tax1 = RATE1 * RATE1_SINGLE_LIMIT; 43 tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT); 44 } 45 } 46 else 47 { 48 if (income <= RATE1_MARRIED_LIMIT) 49 { 50 tax1 = RATE1 * income; 51 } 52 else 53 { 54 tax1 = RATE1 * RATE1_MARRIED_LIMIT; 55 tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT); 56 } 57 } 58 59 return tax1 + tax2; 60 } 61 }
  • 26. Copyright © 2014 by John Wiley & Sons. All rights reserved. 80 Boolean Variables and Operators  To store the evaluation of a logical condition that can be true or false, you use a Boolean variable.  The boolean data type has exactly two values, denoted false and true. boolean failed = true; Boolean negative = x < 0;  Later in your program, use the value to make a decision if (failed==true) // Only executed if failed has been set to true { . . . }  A Boolean variable is also called a flag because it can be either up (true) or down (false).
  • 27. Copyright © 2014 by John Wiley & Sons. All rights reserved. 81 Boolean Variables and Operators  You often need to combine Boolean values when making complex decisions  An operator that combines Boolean conditions is called a Boolean operator.  The && operator is called and • Yields true only when both conditions are true.  The || operator is called or • Yields the result true if at least one of the conditions is true.
  • 28. Copyright © 2014 by John Wiley & Sons. All rights reserved. 82 Boolean Variables and Operators  To test if water is liquid at a given temperature if (temp > 0 && temp < 100) { System.out.println("Liquid"); }  Flowchart
  • 29. Copyright © 2014 by John Wiley & Sons. All rights reserved. 83 Boolean Variables and Operators  To test if water is not liquid at a given temperature if (temp <= 0 || temp >= 100) { System.out.println(“Not liquid"); }  Flowchart
  • 30. Copyright © 2014 by John Wiley & Sons. All rights reserved. 84 Boolean Variables and Operators
  • 31. Copyright © 2014 by John Wiley & Sons. All rights reserved. 85 Boolean Variables and Operators  To invert a condition use the not Boolean operator  The ! operator takes a single condition • Evaluates to true if that condition is false and • Evaluates to false if the condition is true  To test if the Boolean variable frozen is false: if (!frozen) { System.out.println("Not frozen"); }
  • 32. Copyright © 2014 by John Wiley & Sons. All rights reserved. 86 Logical Identities  true && A yields A  false && A yields false  True || A yields true  False || A yields A  B == true yields B  !(A && B) == (!A || !B)  !(A || B) == (!A && !B) Let A, B be an arbitrary boolean expressions: Short Circuit Evaluation: Only evaluate what is required to determine truth value
  • 33. Copyright © 2014 by John Wiley & Sons. All rights reserved. 87 De Morgan’s Law in Action if ((obj != null) && (obj.getSomething() > 0)) { // CODE else // Is obj == null here??