P1258847108NPSRE - PowerPoint PPT Presentation

1 / 54
About This Presentation
Title:

P1258847108NPSRE

Description:

in Java, the ___ symbol is an _operator whereas the ____ operator denotes ... Dictionary ordering is slightly different than a normal dictionary because Java ... – PowerPoint PPT presentation

Number of Views:29
Avg rating:3.0/5.0
Slides: 55
Provided by: david2844
Category:

less

Transcript and Presenter's Notes

Title: P1258847108NPSRE


1
Honors Computer Programming 1-2
Introduction To Chapter 5 Decisions
2
Chapter Goals
  • To be able ______________________________________

to implement decisions using if statements
  • To understand how ______________________________

to group statements into blocks
to compare integers, floating-point
numbers, strings, and objects
  • To learn how ____________________________________
    ____

correct ordering of decisions in multiple branches
  • To recognize the ____________________________
  • To ______________________________________________
    ______

program conditions using Boolean operators and
variables
3
The If Statement
Let's implement the withdraw method of the
BankAccount so that you cannot withdraw more
money than you have in the account.
decision
That is, the withdraw method must make a
_________ whether to allow the withdrawal or
not.
The if statement has two parts a ______ and
a ______ .
The ___ statement is used to implement a
decision.
if
test
body
If the test succeeds, the body of the statement
is __________ .
The if statement consists of
executed
if (amount lt balance) balance balance -
amount
lt
The assignment is carried out when the amount is
_____ the balance.
4
The If Statement
most banks not only disallow withdrawals that
exceed your account balance
Let's make the if statement more realistic
they also charge you a penalty for every attempt
to do so.
You can't simply program two complementary if
statements
if (amount lt balance) balance balance -
amount if (amount gt balance) balance balance
- OVERDRAFT_PENALTY
There are two problems with this approach.
First, if you need to modify the condition
____________________ then you must remember to
update the condition __________________ as well.
amount lt balance
amount gt balance
More importantly, if you modify the value of
________ in the body of the first if statement,
then the second if statement uses the new value.
balance
5
The If Statement
To implement a choice between alternatives, use
the if/else statement
if (amount lt balance) balance balance -
amount else balance balance -
OVERDRAFT_PENALTY
Now there is only _____ condition.
If it is satisfied the _____ statement is
executed.
one
first
Otherwise, the ________ statement is executed.
second
6
The If Statement
if (amount lt balance) balance balance -
amount else balance balance -
OVERDRAFT_PENALTY
The flowchart below is a representation of the
branching behavior.
7
The If Statement
Quite often, the body of the if statement
consists of _________ statements that must be
executed in sequence.
multiple
These statements must be _________ together to
form a ______ statement by enclosing them in
___________ .
grouped
block
Here is an example
braces
if (amount lt balance) double newBalance
balance - amount balance newBalance
a block of statements within braces
8
The If Statement
is called a _______ statement.
balance balance - amount
A statement such as
A conditional statement such as
simple
if (x gt 0) y x
is called a ___________ statement.
compound
The body of an if statement must be a
_________________ , a ____________________ ,
or a ________________ .
simple statement
compound statement
block statement
9
Comparing Values
Relational Operators
test
Every ___ statement performs a _____ .
In many cases, the test compares _____ values.
if
two
For example, in the previous example, we tested
___________________ .
Comparison operators such as ____ are called
__________ operators.
amount lt balance
relational
6
Java has ___ relational operators as shown.
lt
10
Comparing Values
Relational Operators
The ____ operator is sometimes confusing


in Java, the ___ symbol is an ____________
operator whereas the ____ operator denotes
_______________
assignment

equality testing
a 5 // assign 5 to a if (a 5) . . . //
test whether a equals 5
11
Comparing Floating Point Numbers
Floating-point numbers have a limited precision
and calculations can introduce _________ errors.
Consider the following code
round off
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)
Mathematically, this should print ______ but in
fact prints _______________________ .
zero
4.440892098500626E-16
12
Comparing Floating Point Numbers
Unfortunately, such _________ errors are
unavoidable.
It does not make sense to __________
floating-point numbers exactly.
round off
compare
Instead, we test whether they are ______________
.
close enough
To test whether a number x is close to ______
we test as follows
zero
Math.abs(x) lt EPSILON
where we define
final double EPSILON 1E-14
Similarly, you can test whether two numbers x
and y are _______ by checking whether their
___________ is close to ______
equal
difference
zero
if(Math.abs(x - y) lt EPSILON) . . .
13
Comparing Strings
To test whether two strings are equal to each
other, you must use the method called ________
if (string1.equals(string2)) ...
equals
The expression
Do not use the ____ operator to compare strings!

has an unrelated meaning.
if (string1 string2) // not useful
It tests whether two string variables refer to
the same _______ .
object
14
Comparing Strings
In Java, letter case matters.
For example, _______ and ________ are not
the same string.
Harry
HARRY
To ignore case, use the _________________
method
equalsIgnoreCase
if (string1.equalsIgnoreCase(string2)) ...
15
Comparing Strings
If two strings are not identical to each other,
you may want to know the relationship between
them.
The __________ method compares two strings in
dictionary order.
compareTo
If
then string1 comes _______ string2 in the
dictionary.
string1.compareTo(string2) lt 0
before
For example, that is the case if string1 is
______ and string2 is ________ .
If
Harry
Holden
then string1 comes ______ string2 in
dictionary order.
string1.compareTo(string2) gt 0
after
Finally, if
then string1 and string2 are ______ .
string1.compareTo(string2) 0
equal
16
Comparing Strings
Dictionary ordering is slightly different than a
normal dictionary because Java is ______________
and sorts characters by putting _________
first, then ___________ letters, then
___________ letters.
case sensitive
numbers
uppercase
lowercase
For example, 1 comes before ___ which comes
before ___ .
B
The _______ character comes before all other
characters.
a
space
17
Comparing Strings
The process of comparing strings for dictionary
order is called _____________ comparison.
car
For example, compare
with
lexicographic
The first three characters _______ and we
reach the end of the first string so _____
comes before _______ .
cargo
.
match
Now compare
car
cargo
The first two characters _______ and in the
third character position ________________ so
_______ comes before ________ .
cathode
cargo
with
.
match
r comes before t
cargo
cathode
18
Comparing Objects
If you compare two object references with the
operator, you test whether the references refer
to the ____________ .
Here is an example
same object
Rectangle cerealBox new Rectangle(5, 10, 20,
30) Rectangle r cerealBox Rectangle
oatmealBox new Rectangle(5, 10, 20, 30)
19
Comparing Objects
is _____ since both variables refer to the
same object.
cerealBox r
The comparison
true
But the comparison
is ______ since the variables refer to
different objects.
cerealBox oatmealBox
false
It does not matter that both objects have
__________________ .
the same contents
20
Comparing Objects
You can use the ________ method to test whether
two rectangles have the same _________ .
equals
For example, the test
contents
However, not all classes use the ________
method.
cerealBox.equals(oatmealBox)
is _____ .
true
In this case, the ___________ class does have
the method, so we can use it.
equals
Rectangle
21
Testing for null
An object reference can have the special value
_____ if it refers to _______________ .
null
You use the ____ operator and not ________
to test whether an object reference is a null
reference
no object at all
equals

if (account null) . . . // account is a
null reference
22
Testing for null
Frequently methods return null if they are not
able to return a ____________ .
method of the JOptionPane class returns _____
showInputDialog
For example, the
valid object
if the user hits the ________ button of the
input dialog
cancel
null
String input JOptionPane.showInputDialog
("How many nickels do you
have?") if (input null) . . . // user
canceled dialog
Note that the null reference is not the same as
an _____________ .
empty string
The empty string is a valid string of length ___
whereas a null reference indicates that a string
variable refers to ______________ .
0
no string at all
The showInputDialog method returns an empty
string if the user _________________________
and then hits the _____ button.
leaves the input field blank
OK
23
Multiple Alternatives
Multiple alternatives can be made with the style
shown.
if (...) // 1st alternative ... else
if(...) // 2nd alternative ... else
if(...) // 3rd alternative ... else
// final else may be omitted ...
24
Multiple Alternatives
The following example demonstrates this pattern.
file Earthquake.java
file EarthquakeTest.java
public class Earthquake public
Earthquake(double magnitude) // constructor
richter magnitude public
String getDescription( ) String r
if (richter gt 8.0) r "Most
structures fall" else if (richter gt 7.0)
r "Many buildings destroyed"
else if (richter gt 6.0) r "Many
buildings collapse" else if (richter gt
4.5) r "Damage to poorly constructed
buildings" else if (richter gt 3.5)
r "Felt by many people no destruction"
else if (richter gt 0) r "Generally
not felt by people" else r
"Negative Numbers are not valid" return
r private double richter
import javax.swing.JOptionPane public class
EarthquakeTest public static void
main(String args) String input
input JOptionPane("Enter the Richter
value" double magnitude
Double.parseDouble(input) Earthquake quake
new Earthquake(magnitude)
System.out.println(quake.getDescription( ))
System.exit(0)
nested if/else
25
Switch Statement
A sequence of if/else/else that compares a
___________________ against several _________
alternatives can be implemented as a _______
statement.
single integer value
constant
For example
switch
int digit ... switch (digit) case 1
System.out.print("one") break case 2
System.out.print("two") break case 3
System.out.print("three") break case 4
System.out.print("four") break case 5
System.out.print("five") break case 6
System.out.print("six") break case 7
System.out.print("seven") break case 8
System.out.print("eight") break case 9
System.out.print("nine") break default
System.out.print("error") break
26
Switch Statement
This is a short cut for
nested if/else statement
int digit ... if(digit 1) System.out.print("on
e") else if(digit 2) System.out.print("two")
else if(digit 3) System.out.print("three") e
lse if(digit 4) System.out.print("four") else
if(digit 5) System.out.print("five") else
if(digit 6) System.out.print("six") else
if(digit 7) System.out.print("seven") else
if(digit 8) System.out.print("eight") else
if(digit 9) System.out.print("nine") else
System.out.print("error")
27
int digit ... switch (digit) case 1
System.out.print("one") break case 2
System.out.print("two") break case 3
System.out.print("three") break case 4
System.out.print("four") break case 5
System.out.print("five") break case 6
System.out.print("six") break case 7
System.out.print("seven") break case 8
System.out.print("eight") break case 9
System.out.print("nine") break default
System.out.print("error") break
Switch Statement
Using the switch statement has one advantage.
All branches test the _______ value, namely
______ .
same
digit
28
Switch Statement
The switch statement can only be applied in
narrow circumstances.
The test cases must be ___________ , and they
must be _________ or ___________ .
constants
You cannot use a switch statement to branch on
_____________ numbers or ________ values.
integers
characters
floating-point
strings
For example, the following is an error
switch (name) case "one" ... break //
error can't use a string for a case label
...
case label must be a constant
29
Switch Statement
Note how every branch of the switch was
terminated by a _______ instruction.
break
If the break is missing, execution
_____________ to the next branch, and so on
until finally a _______ or the
_________________ is reached.
falls through
break
For example, consider the following switch
statement
end of switch
switch (digit) case 1 System.out.print("one"
) // oops no break case 2
System.out.print("two") break ...
If digit has the value 1, then the statement
________________ label is executed since there
is no _______ .
after the case 1
In this situation the output would be
__________ .
break
"onetwo"
30
Nested Branches
Let us compute the taxes due, using the 1992 tax
rates (when the form was simpler).
The key point is that there are two ______ of
decision making.
levels
First we must branch on the ____________ .
filing status
Then for each filing status we must have another
branch on _____________ .
The code is based on the forms shown below.
income level
31
Nested Branches
The code for TaxReturn.java and
TaxReturnTest.java is shown on the handout.
32
Nested Branches
Note the two levels of decision making.
The flowchart for the TaxReturn program is shown
below.
33
The Dangling else Problem
When an ____________ is nested inside another
____________ , the following error may occur.
if statement
if statement
if (richter gt 0) if (richter lt 4)
System.out.println("The earthquake is
harmless") else // Pitfall!
System.out.println("Negative value not allowed")
The indentation level seems to suggest that the
_____ is grouped with the test ______________ .
else
Unfortunately, that is not the case.
richter gt 0
The _________ ignores all indentation and
follows the rule that an ______ always belongs
to the nearest ___ .
compiler
else
if
34
The Dangling else Problem
if (richter gt 0) if (richter lt 4)
System.out.println("The earthquake is
harmless") else // Pitfall!
System.out.println("Negative value not allowed")
That is, the code is actually
if (richter gt 0) if (richter lt 4)
System.out.println("The earthquake is
harmless") else // Pitfall!
System.out.println("Negative value not allowed")
35
The Dangling else Problem
That isn't what we want.
We want to group the else with the first if.
For that, we must use ________ .
braces
if (richter gt 0) if (richter lt 4)
System.out.println("The earthquake is
harmless") else System.out.println("Negative
value not allowed")
36
The Dangling else Problem
It is recommended that you always use ________
when the body of an _____________ contains
another ___ statement.
braces
This ambiguous else is referred to as a
__________ else .
if statement
if
dangling
37
Using boolean Expressions The boolean Type
An expression such as _______________ has a
value.
The value of a __________ expression is _____
or ______ .
amount lt 1000
The program fragment
relational
true
false
double amount 0 System.out.println(amount lt
1000)
will display _____ .
The values ______ and ______ are not
numbers, nor are they objects.
true
true
false
They belong to a separate type called _________
which is named after the mathematician
______________ , a pioneer in the study of logic.
boolean
George Boole
38
Using boolean Expressions
Predicate Methods
A _________________ is a method that returns a
_________ value.
predicate method
boolean
Here is an example
public boolean isOverdrawn( ) return balance
lt 0
You should use the return value of the method as
the condition of an ____________
if statement
if (harrysChecking.isOverdrawn( )) . . .
There are several useful static __________
methods in the Character class
predicate
isDigit isLetter isUpperCase isLowerCase
These let you test whether a __________ is a
digit, a letter, an uppercase letter, or a
lowercase letter
character
if (Character.isUpperCase(ch)) ...
39
Using boolean Expressions
The Boolean Operators
Suppose you want to find out whether amount is
_________ 0 and 1000.
between
Then two conditions have to be true
amount must be _____
In Java, you use the _____ operator to
represent the _____ to combine test conditions.
amount must be ________ .
and
gt 0
lt 1000

and
You write the test as follows
if (0 lt amount amount lt 1000) ...
The operator combines several tests into a
new test that passes only when ____ conditions
are true.
An operator that combines test conditions is
called a ________ operator.
all
logical
40
Using boolean Expressions
The Boolean Operators
The ________ operator also combines two or more
conditions.
(or)
The result succeeds if ____________ condition
is true.
For example, here is a test to check whether the
string input is a "S"
at least one
or "M"
if (input.equals("S") input.equals("M")) ...
Sometimes you have to invert a condition with the
________ logical operator.
! (not)
For example, we may want to carry out a certain
action only if two strings are not equal
if (!input.equals("S")) ...
The ! operator takes a single condition and
evaluates to true if that condition is ______
and to false if the condition is _____ .
false
true
41
Using boolean Expressions
The Boolean Operators
Here is a summary of the logical operations
42
Using boolean Expressions
Multiple Relational Operators Error
Consider the expression
if (0 lt amount lt 1000) ... // error
This looks just like the mathematical expression
for amount ___________ 0 and 1000.
But in Java, it is a ____________ .
is between
syntax error
Let's dissect the condition.
The first part, ___________ ,
is a test with outcome either ______ or
______ .
0 lt amount
This outcome is then compared against 1000.
true
false
This does not make any sense to compare
____________ and numbers.
Is true larger than 1000 or not?
truth values
In any event, the _________ rejects this
statement.
compiler
Instead you should use ______ to combine two
separate tests

if (0 lt amount amount lt 1000) ...
43
Using boolean Expressions
Multiple Relational Operators Error
Another common error is to write
if (ch 'S' 'M') ... // error
to test whether ch is either 'S' or 'M'.
Again, the Java compiler flags this construct as
an ______ .
You cannot apply the ___ operator to
___________ .
error

You need to write two __________ expressions
and join them with the ____ operator
characters
boolean

if (ch 'S' ch 'M') ...
44
Using boolean Expressions
Lazy (Short Circuit) Evaluation of boolean
Operators
The ____ and ___ operators are computed in
Java using _____ or ____________ evaluation.


lazy
In other words, ________ expressions are
evaluated from ___________ and evaluation
_______ when the truth value is determined.
short circuit
logical
left to right
When an _______ is evaluated and the first
condition is ______ then the second condition
is _________ since the combined condition will
be ______ regardless of the outcome of the
second condition.
stops
and
false
skipped
When an ____ is evaluated and the first
condition is _____ then the second condition is
_____________ since the combined condition will
be ______ regardless of the outcome of the
second condition.
false
or
true
not evaluated
true
45
Using boolean Expressions
Lazy (Short Circuit) Evaluation of boolean
Operators
Here is an example
if (input ! null Integer.parseInt(input) gt 0)
...
If ____________ then the first condition is
______ and thus the combined condition is
______ no matter what the outcome of the second
test is.
false
input is null
false
The second condition is ________________ if
input is null and there is no danger of parsing
a null string which would cause an error.
never evaluated
46
Using boolean Expressions
De Morgan's Laws
De Morgan's Law shows how to _________
expressions in which a __ operator is applied
to terms joined by an ____ or an ___ .
simplify
In the preceding section, we programmed a test
to see whether amount was between 0 and 1000.


!
Suppose we want to find out whether the opposite
is true
if (!(0 lt amount amount lt 1000)) ...
47
Using boolean Expressions
De Morgan's Laws
if (!(0 lt amount amount lt 1000)) ...
De Morgan's Law (named after the logician
Augustus de Morgan) can be used to simplify this
expression.
It has two forms one for an _____ expression
and one for an ____ expression.
and
or
!(A B) is the same as !A !B !(A B) is
the same as !A !B
Using these Laws, we can rewrite our if statement
if(0 gt amount amount gt 1000) ...
negation
48
Using boolean Expressions
De Morgan's Laws
if (!(0 lt amount amount lt 1000)) ...
De Morgan's Law (named after the logician
Augustus de Morgan) can be used to simplify this
expression.
It has two forms one for an _____ expression
and one for an ____ expression.
and
or
!(A B) is the same as !A !B !(A B) is
the same as !A !B
Using these Laws, we can rewrite our if statement
if(0 gt amount amount gt 1000) ...
negation
49
Using boolean Expressions
De Morgan's Laws
if (!(0 lt amount amount lt 1000)) ...
De Morgan's Law (named after the logician
Augustus de Morgan) can be used to simplify this
expression.
It has two forms one for an _____ expression
and one for an ____ expression.
and
or
!(A B) is the same as !A !B !(A B) is
the same as !A !B
Using these Laws, we can rewrite our if statement
if(0 gt amount amount gt 1000) ...
and changes to or
50
Using boolean Expressions
De Morgan's Laws
The negation of " the input is S or the input is
M "
!(input.equals("S") input.equals("M"))
can be rewritten as
!input.equals("S") !input.equals("M")
negation
51
Using boolean Expressions
De Morgan's Laws
The negation of " the input is S or the input is
M "
!(input.equals("S") input.equals("M")
can be rewritten as
!input.equals("S") !input.equals("M")
negation
52
Using boolean Expressions
De Morgan's Laws
The negation of " the input is S or the input is
M "
!(input.equals("S") input.equals("M")
can be rewritten as
!input.equals("S") !input.equals("M")
or changes to and
53
Using boolean Expressions
Using boolean Variables
You can use a _________ variable if you know
that there are only _____ possible values.
boolean
Here is another look at the tax program
discussed earlier.
two
The marital status is either _______ or
_________ .
single
Instead of using an integer, you can use a
variable of type boolean
married
private boolean married
Then you can use the variable in a test
if (married) ... else ...
54
Using boolean Expressions
Using boolean Variables
Sometimes boolean variables are called ______ .
That is because they can just have two states
____ or _______ .
flags
up
down
It is not considered good style to write a test
such as
if (married true) ... // Don't
Just use the simpler test
if (married) ...
Write a Comment
User Comments (0)
About PowerShow.com