0% found this document useful (0 votes)
6 views60 pages

Java Decision-Making Techniques

Chapter 3 of the document focuses on decision-making in programming using if statements, comparisons of numbers and strings, and input validation strategies. It covers the syntax and structure of if statements, including multiple alternatives and nested branches, as well as common errors to avoid. Additionally, it discusses Boolean variables and operators for combining conditions in decision-making processes.

Uploaded by

mrarther48
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views60 pages

Java Decision-Making Techniques

Chapter 3 of the document focuses on decision-making in programming using if statements, comparisons of numbers and strings, and input validation strategies. It covers the syntax and structure of if statements, including multiple alternatives and nested branches, as well as common errors to avoid. Additionally, it discusses Boolean variables and operators for combining conditions in decision-making processes.

Uploaded by

mrarther48
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CALIFORNIA UNIVERSITY OF

SCIENCE AND TECHNOLOGY


CALIFORNIA UNIVERSITY OF SCIENCE AND TECHNOLOGY
Information Technology and Artificial Intelligence
CHAPTER 3
DECISIONS

Slides by Donald W. Smith Final Draft


Copyright © 2013 by John Wiley & Sons. All rights reserved. [Link] Oct 15, 2011
Chapter Goals
• To implement decisions using the if statement
• To compare integers, floating-point numbers, and
Strings
• To write statements using the Boolean data type
• To develop strategies for testing your programs
• To for validate user input

In this chapter, you will learn how to


program simple and complex decisions.
You will apply what you learn to the task
of checking user input.

Page 4 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Contents
• The if Statement
• Comparing Numbers
and Strings
• Multiple Alternatives
• Nested Branches
• Problem Solving: Flowcharts
• Problem Solving: Test Cases
• Boolean Variables and Operators
• Application: Input Validation

Page 5 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
3.1 The if Statement
• A computer program often needs to make decisions based on
input, or circumstances
• For example, buildings often ‘skip’ the 13th floor, and elevators
should too
• The 14th floor is really the 13th floor
• So every floor above 12 is really ‘floor - 1’
• If floor > 12, Actual floor = floor - 1
• The two keywords of the if statement are:
• if The if statement allows a program to
• else carry out different actions depending on
the nature of the data to be processed.
Page 6 Copyright © 2013 by John Wiley & Sons. All
rights reserved.
Flowchart of the if statement
• One of the two branches is executed once
• True (if) branch or False (else) branch

Page 7 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Flowchart with only true branch
• An if statement may not need a ‘False’ (else) branch

Page 8 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Syntax 3.1: The if statement

Page 9 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
[Link]

Page 10 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Tips On Using Braces
• Line up all pairs of braces vertically
• Lined up Not aligned (saves lines)

• Always use braces


• Although single statement clauses do not require them

Most programmer’s editors have a


tool to align matching braces.

Page 11 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Tips on indenting blocks
• Use Tab to indent a consistent number of spaces

This is referred to as ‘block-


structured’ code. Indenting
consistently makes code much
easier for humans to follow.

Page 12 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Common Error 3.1
A semicolon after an if statement
• It is easy to forget and add a semicolon
after an if statement.
• The true path is now the space just before the semicolon
if (floor > 13) ;
{
floor--;
}
• The ‘body’ (between the curly braces) will always be executed in this
case

Page 13 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
3.2 Comparing Numbers and Strings

• Every if statement has a condition


• Usually compares two values with an operator

if (floor > 13)


..
if (floor >= 13)
..
if (floor < 13)
..
if (floor <= 13)
..
if (floor == 13)
..
Beware!

Page 14 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Syntax 3.2: Comparisons

Page 15 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Operator Precedence

• The comparison operators have lower precedence than


arithmetic operators
• Calculations are done before the comparison
• Normally your calculations are on the ‘right side’ of the comparison or
assignment operator
Calculations

actualFloor = floor + 1;

if (floor > height + 1)

Page 16 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Relational Operator Use (1)

Page 17 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Relational Operator Use (2)

Page 18 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Comparing Strings

• Strings are a bit ‘special’ in Java


• Do not use the == operator with Strings
• The following compares the locations of two strings, and not their
contents

if (string1 == string2) ...

• Instead use the String’s equals method:


if ([Link](string2)) ...

Page 19 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Common Error 3.3
• Using == to compare Strings
• == compares the locations of the Strings
• Java creates a new String every time a new word inside double-
quotes is used
• If there is one that matches it exactly, Java re-uses it
String nickname = "Rob";
. . .
if (nickname == "Rob") // Test is true

String name = "Robert";


String nickname = [Link](0, 3);
. . .
if (nickname == "Rob") // Test is false

Page 20 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Lexicographical Order
• To compare Strings in ‘dictionary’ order
• When compared using compareTo, string1 comes:
• Before string2 if
[Link](string2) < 0
• After string2 if
[Link](string2) > 0
• Equal to string2 if

• Notes [Link](string2) == 0
• All UPPERCASE letters come before lowercase
• ‘space’ comes before all other printable characters
• Digits (0-9) come before all letters
• See Appendix A for the Basic Latin Unicode (ASCII) table

Page 21 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Implementing an if Statement
1) Decide on a branching condition

2) Write pseudocode for the true branch

3) Write pseudocode for the false branch

4) Double-check relational operators


• Test values below, at, and above the comparison (127,
128, 129)

Page 22 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Implementing an if Statement (cont.)

5) Remove duplication

6) Test both branches

7) Write the code in Java

Page 23 Copyright © 2011 by John Wiley & Sons. All


rights reserved.
Implemented Example
• The university bookstore has a Kilobyte Day sale every October 24, giving an 8
percent discount on all computer accessory purchases if the price is less than $128,
and a 16 percent discount if the price is at least $128.
if (originalPrice < 128)
{
discountRate = 0.92;
}
else
{
discountRate = 0.84;
}
discountedPrice = discountRate * originalPrice;

Page 24 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
3.3 Multiple Alternatives
• What if you have more than two branches?
• Count the branches for the following earthquake effect example:
• 8 (or greater)
• 7 to 7.99
• 6 to 6.99
• 4.5 to 5.99
• Less than 4.5

When using multiple if statements,


test general conditions after more
specific conditions.

Page 25 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Flowchart of Multiway branching
True
> 8.0? Most Structures Fall

False
True
>= 7.0? Many Buildings Destroyed

False
True Many buildings considerably damaged,
>= 6.0?
some collapse

False
True
>= 4.5? Damage to poorly constructed buildings

False
No destruction of buildings

Page 26 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
if, else if multiway branching
if (richter >= 8.0) // Handle the ‘special case’ first
{
[Link]("Most structures fall");
}
else if (richter >= 7.0)
{
[Link]("Many buildings destroyed");
}
else if (richter >= 6.0)
{
[Link]("Many buildings damaged, some collapse");
}
else if (richter >= 4.5)
{
[Link]("Damage to poorly constructed buildings");
}
else // so that the ‘general case’ can be handled last
{
[Link]("No destruction of buildings");
}
Page 27 Copyright © 2013 by John Wiley & Sons. All
rights reserved.
What is wrong with this code?
if (richter >= 8.0)
{
[Link]("Most structures fall");
}
if (richter >= 7.0)
{
[Link]("Many buildings destroyed");
}
if (richter >= 6.0)
{
[Link]("Many buildings damaged, some collapse");
}
if (richter >= 4.5)
{
[Link]("Damage to poorly constructed buildings");
}

Page 28 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
3.4 Nested Branches
• You can nest an if inside either branch of an if
statement.

Page 29 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Tax Example: Nested ifs

• Four outcomes (branches)

• Single
• <= 32000
• > 32000
• Married
• <= 64000
• > 64000

Page 30 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Flowchart for Tax Example

• Four branches

Page 31 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
[Link] (1)

Page 32 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
[Link] (2)
• The ‘True’ branch (Married)
• Two branches within this branch

Page 33 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
[Link] (3)
• The ‘False’ branch (not Married)

Page 34 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Hand-Tracing
• Hand-tracing helps you understand whether a program works
correctly
• Create a table of key variables
• Use pencil and paper to track their values
• Works with pseudocode or code
• Track location with a marker such as a
paper clip
• Use example input values that:
• You know what the correct outcome should be
• Will test each branch of your code

Page 35 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Hand-Tracing Tax Example (1)
• Setup
• Table of variables
• Initial values

Page 36 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Hand-Tracing Tax Example (2)
• Input variables
• From user
• Update table

Because marital status is not “s” we skip to the ❑


else on line 41

Page 37 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Hand-Tracing Tax Example (3)
• Because income is not <= 64000, we move to the else clause
on line 47
• Update variables on lines 49 and 50
• Use constants

Page 38 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Hand-Tracing Tax Example (4)
• Output
• Calculate
• As expected?

Page 39 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Common Error 3.4
The Dangling else Problem
• When an if statement is nested inside another if statement, the
following can occur:
double shippingCharge = 5.00; // $5 inside continental U.S.
if ([Link]("USA"))
if ([Link]("HI"))
shippingCharge = 10.00; // Hawaii is more expensive
else // Pitfall!
shippingCharge = 20.00; // As are foreign shipment

• The indentation level suggests that the else is related to the if


country (“USA”)
• Else clauses always associate to the closest if

Page 40 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
3.7 Boolean Variables
• Boolean Variables
• A Boolean variable is often called a flag because it can be either up
(true) or down (false)
• boolean is a Java data type
• boolean failed = true;
• Can be either true or false
• Boolean Operators: && and ||
• They combine multiple conditions
• && is the and operator
• || is the or operator

Page 41 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Character Testing Methods
• The Character class has a number of handy methods that
return a boolean value:

if ([Link](ch))
{
...
}

Page 42 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Combined Conditions: &&
• Combining two conditions is often used in range checking
• Is a value between two other values?
• Both sides of the and must be true for the result to be true

if (temp > 0 && temp < 100)


{
[Link]("Liquid");
}

Page 43 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Combined Conditions: ||
• If only one of two conditions need to be true
• Use a compound conditional with an or:
if (balance > 100 || credit > 100)
{
[Link](“Accepted");
}

• If either is true
• The result is true

Page 44 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
The not Operator: !
• If you need to invert a boolean variable or comparison, precede
it with !
if (!attending || grade < 60)
{
[Link](“Drop?");
}
if (attending && !(grade < 60))
{
[Link](“Stay");
}
• If using !, try to use simpler logic:
if (attending && (grade >= 60))

Page 45 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
and Flowchart
if (temp > 0 && temp < 100)
{
[Link]("Liquid");
}

• This is often called ‘range


checking’
• Used to validate that input is
between two values

Page 46 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
or Flowchart

• Another form of
‘range checking’
• Checks if value is
outside a range

if (temp <= 0 || temp >= 100)


{
[Link](“Not Liquid");
}

Page 47 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Boolean Operator Examples

Page 48 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Boolean Operator Examples

Page 49 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Common Error 3.5
• Combining Multiple Relational Operators
if (0 <= temp <= 100) // Syntax error!

• This format is used in math, but not in Java!


• It requires two comparisons:
if (0 <= temp && temp <= 100)
• This is also not allowed in Java:
if (input == 1 || 2) // Syntax error!
• This also requires two comparisons:

if (input == 1 || input == 2)

Page 50 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Common Error 3.6

Confusing && and ||Conditions


• It is a surprisingly common error to confuse && and || conditions.
• A value lies between 0 and 100 if it is at least 0 and at most 100.
• It lies outside that range if it is less than 0 or greater than 100.
• There is no golden rule; you just have to think carefully.

Page 51 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Short-Circuit Evaluation: &&
• Combined conditions are evaluated from left to right
• If the left half of an and condition is false, why look further?

if (temp > 0 && temp < 100)


{
[Link]("Liquid");
}
Done!

• A useful example:

if (quantity > 0 && price / quantity < 10)

Page 52 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Short-Circuit Evaluation: ||
• If the left half of the or is true, why look further?
if (temp <= 0 || temp >= 100)
{
[Link](“Not Liquid");
}

• Java doesn’t!
• Don’t do these second:
• Assignment
• Output

Done!

Page 53 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
De Morgan’s Law
• De Morgan’s law tells you how to negate && and ||
conditions:
• !(A && B) is the same as !A || !B
• !(A || B) is the same as !A && !B
• Example: Shipping is higher to AK and HI
if (!([Link]("USA") if ![Link]("USA")
&& ![Link]("AK") || [Link]("AK")
&& ![Link]("HI"))) || [Link]("HI")
shippingCharge = 20.00; shippingCharge = 20.00;

• To simplify conditions with negations of and or or


expressions, it is usually a good idea to apply De Morgan’s
Law to move the negations to the innermost level.

Page 54 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
3.8 Input Validation
• Accepting user input is dangerous
• Consider the Elevator program:
• The user may input an invalid character or value
• Must be an integer if ([Link]())
• Scanner can help! {
• hasNextInt int floor = [Link]();
// Process the input value
• True if integer }
• False if not else
{
[Link]("Not integer.");
• Then range check value }
• We expect a floor number to be between 1 and 20
• NOT 0, 13 or > 20

Page 55 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
[Link]

Input value validity checking

Input value range checking

Page 56 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
[Link]

Page 57 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Summary: if Statement
• The if statement allows a program to carry out different actions depending
on the nature of the data to be processed.
• Relational operators ( < <= > >= == != ) are used to compare numbers
and Strings.
• Do not use the == operator to compare Strings.
• Use the equals method instead.
• The compareTo method compares Strings in lexicographic order.
• Multiple if statements can be combined to evaluate complex decisions.
• When using multiple if statements, test general conditions after more
specific conditions.

Page 58 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Summary: Flowcharts and Testing
• When a decision statement is contained inside the branch
of another decision statement, the statements are nested.
• Nested decisions are required for problems that have two
levels of decision making.
• Flow charts are made up of elements for tasks, input/
output, and decisions.
• Each branch of a decision can contain tasks and further
decisions.
• Never point an arrow inside another branch.
• Each branch of your program should be covered by a test
case.
• It is a good idea to design test cases before implementing a
program.

Page 59 Copyright © 2013 by John Wiley & Sons. All


rights reserved.
Summary: Boolean
• The Boolean type boolean has two values, true and false.
• Java has two Boolean operators that combine conditions: && (and) and
|| (or).
• To invert a condition, use the ! (not) operator.
• The && and || operators are computed lazily: As soon as the truth
value is determined, no further conditions are evaluated.
• De Morgan’s law tells you how to negate && and || conditions.
• You can use Scanner hasNext methods to ensure that the
data is what you expect.

Page 60 Copyright © 2011 by John Wiley & Sons. All


rights reserved.

You might also like