Title: Conditional Statements
1Conditional Statements
- More about if and switch.
- by James Brucker
If you come to a fork in the road, take it.
-- Yogi Berra
2Simple if Statement
System.out.print("Enter an integer ") int num
scanner.nextInt( ) if ( num 2 0 )
System.out.println("Even")
Enter an integer 100 Even
System.out.print("Enter an integer ") int num
scanner.nextInt( ) if ( num 2 0 )
System.out.println("Even") else
System.out.println("Odd")
Enter an integer 999 Odd
3if Statement With Block
sum squares of 1 .. n if ( n gt 0 ) int sum
0 for (int k1 k lt n k) sum k
k System.out.println("sum of squares is
"sum) else System.out.println("nothing to
sum")
Enter an integer 10 sum of squares is 55
In Java, any place there you can put a single
statement you can substitute a block of
statements enclosed in ... . Variables
defined inside of a block have scope limited to
that block!
4Nested if Statement
roll two dice int die1 rollDice( ) int die2
rollDice( ) if ( die1 die2 11
) System.out.println("You win!") else if (
die1 6 ) if ( die2 6 )
System.out.println("Two 6es. Roll
again.") else System.out.println("You lose.")
What will be output for each case?
Roll 6 5 Output Roll 6 6 Output Roll 6
3 Output Roll 3 6 Output
5Nested if Statement dangling else
roll two dice int die1 rollDice( ) int die2
rollDice( ) if ( die1 die2 11
) System.out.println("You win!") else if (
die1 6 ) if ( die2 6 )
System.out.println("Two 6es. Roll
again.") else System.out.println("You lose.")
An "else" clause pairs with the nearest unmatched
"if" at the same block level.
Roll 6 5 Output You win! Roll 6 6 Output
Two 6es. Roll again. Roll 6 3 Output You
lose. Roll 3 6 Output (no output)
6Avoiding dangling else confusion
- enclose nested "if" in a ... block, or
roll two dice int die1 rollDice( ) int die2
rollDice( ) if ( die1 die2 11
) System.out.println("You win!") else if ( die1
6 ) if ( die2 6 ) System.out.println(
"Two 6es. Roll again.") else System.out.printl
n("You lose.")
This clarifies the logic, but not really what we
want.
7Avoiding dangling else confusion
- enclose nested "if" in a ... block, or
- structure the "if" as an if ... else if ... else
.
roll two dice int die1 rollDice( ) int die2
rollDice( ) if ( die1 die2 11
) System.out.println("You win!") else if ( die1
6 die2 6 ) System.out.println("Two 6es.
Roll again.") else System.out.println("You
lose.")
Much clearer -- every case has an action.
8Syntax diagrams for if
- if ( boolean_expression ) Statement_block1
if ( boolean_expression ) Statement_block1 else
Statement_block2
if ( boolean_expression ) Statement_block1 else
if ( boolean_expression2 ) Statement_block2
... else Statement_block_n
statement_block statement null
statement statement ...
9Simple Boolean Expressions (1)
- A boolean expression is anything with a
true/false value. Simple boolean expressions
are - Comparisons of primitive data types
- x gt y x gt y
- x lt y x lt y
- x y x ! y
- Comparison of object values
- obj1.equals( obj2 )
- ! obj1.equals( obj2 )
- Comparison of object references
- obj1 obj2
- is true of obj1 and obj2 refer to the same
object.
10Simple Boolean Expressions (2)
- Comparing primitive numeric data
double x 2.0 double y 2.00000001 if ( x
y ) System.out.println("x y") else
System.out.println("x ! y")
x ! y
double x input.nextDouble( ) // read x
value double y input.nextDouble( ) // read y
value if ( x lt y ) System.out.println("x lt
y") else if ( x y ) System.out.println("x
y") else if ( x gt y ) System.out.println("x gt
y") else System.out.println("Impossible.")
11Simple Boolean Expressions (3)
- Example of common error using for objects
Double x new Double(10.0) Double y new
Double(10.0) if ( x y ) System.out.println("x
y") else System.out.println("x ! y")
x ! y
- Use equals to compare the value of objects
Double x new Double(10.0) Double y new
Double(10.0) if ( x.equals(y) )
System.out.println("x equal y") else
System.out.println("x not equal y")
x equal y
12Compound Boolean Expressions
- Short-cut Boolean operators
- A B true if A is true and B is true
- A B true if A is true or B is true
- Stop as soon as the result is known
- A B if A is false, don't test B
- A B if A is true, don't test B
- Example
avoid division by zero if ( y ! 0
Math.sin(x/y) lt 0.5 ) ...
13More Boolean Operators
- Negation ! expression
- !( x y ) is same as (x ! y)
- !(A B) is same as !A !B
- !(A B) is same as !A !B
- and, or that always evaluate both expressions
- A B and, always evaluates A, B
- A B or, always evaluates A, B
- A B exclusive or, always evaluates A, B
A B A B A B A B ! (A B) true true true t
rue false false true false false true true true
false true false true true true false false false
false false true
Truth Table
14Comparing Strings
15Lexical Ordering
- Many classes implement the Comparable
interface.This means that the class provides a
meaningful compareTo( ) method for lexically
ordering objects. - Some classes that implement Comparable
- String, BigInteger, BigDecimal, the wrapper
classes (Integer, Float, Double, ...) - Example
String s1 input.next( ) // read a word String
s2 input.next( ) // read another word if (
s1.compareTo( s2 ) 0 ) / lexically equal /
else if ( s1.compareTo( s2 ) gt 0 ) / s1 AFTER
s2 / else if ( s1.compareTo( s2 ) lt 0 ) / s1
BEFORE s2 /
16Summary of Object Comparisons
- For variables that are object types (object
references) - (a b) tests if the variables refer to the same
object - a.equals(b) compares the value of two objects
- If the objects are of a class that implements
compareTo - a.compareTo(b) returnslt 0 if a comes "before"
b (in some lexical ordering) - 0 if a has same ordering as b
- gt 0 if a comes "after" b
Double x new Double(10.0) Double y new
Double(10.0) boolean test1 ( x y ) //
false boolean test1 x.equals(y) // true int
ordering x.compareTo(y) // 0
17Examples
18Copy Center
- The copy center (KU's most popular service)
charges according to the number of copies 1 - 9
copies 0.50 baht/copy 10-49 copies 0.45
baht/copy 50-99 copies 0.42 baht/copy 100
copies 0.40 baht/copy - Complete this method for computing copy charges
/ compute price of copy job. _at_param copies
number of copies in job / public static
double jobCost(int copies)
19Copy Center (2)
- The rate table 1 - 9 copies 0.50
baht/copy 10-49 copies 0.45 baht/copy 50-99
copies 0.42 baht/copy 100 copies 0.40 baht/copy - Simple answer
/ compute price of copy job. _at_param copies
number of copies in job / public static
double jobCost(int copies) double price if (
copies lt 10 ) price 0.50copies if ( copies
gt 10 copies lt 50 ) price 0.45copies if (
copies gt 50 copies lt100 ) price
0.42copies if ( copies gt 100 ) price
0.40copies return price
20Copy Center (3)
- This is inefficient because it performs redundant
tests. - Better answer
/ compute price of copy job. _at_param copies
number of copies in job / public static
double jobCost(int copies) double price if (
copies lt 10 ) price 0.50copies else if (
copies lt 50 ) price 0.45copies else if (
copies lt 100 ) price 0.42copies else price
0.40copies return price
- But there is a logic error here (missing case).
What?
21Copy Center (4)
- Be careful of the case copies lt 0. Two
solutions - Let the caller verify the data
- _at_precondition copies gt 0
- Check for the case copies lt 0.
/ compute price of copy job. _at_param copies
number of copies in job / public static
double jobCost(int copies) double price if (
copies lt 0 ) price 0.0 else if ( copies lt 10
) price 0.50copies else if ( copies lt 50 )
price 0.45copies else if ( copies lt 100 )
price 0.42copies else price
0.40copies return price
22Testing Yes/No Input
- String reply input.next( ) // read a word
- if ( reply null ) / do nothing /
- else if ( reply.equalsIgnoreCase("yes") ) ...
- else if ( reply.equalsIgnoreCase("no") ) ...
- else System.out.println("what?")
This works because Scanner.next( ) trims leading
and trailing blanks from the input word. If you
use some other input method, you should use
reply.trim( ) to trim leading and trailing blanks
before testing the reply.
23Common Errors
- This example contains a syntax error and a logic
error.
// binomial formula for ax2 bx c
0 double discrim bb - 4ac if ( discrim gt 0
) r Math.sqrt( discrim ) x ... /
compute a root / else System.out.println("No
real roots")
24Comparing Objects to null
- You can compare object references to null.
- Avoids NullPointerException, detect end of input.
Scanner input new Scanner( System.in ) // read
a line of input String line input.nextLine(
) // end of input? if ( line null ) return
/ no input / else processInputLine( line )
String reply JOptionPane.showInputDialog( null,
"What do you want?", ... ) // did the user
enter data or cancel? if ( reply null ) /
cancelled! /
25Avoid referencing null Objects
- Verify method parameters are not null.
- Here is a static version of "equals" for String
/ _at_return true if two strings are equal,
ignoring case of letters ("YES" "yes")
/ private boolean equals(String s1, String s2)
return s1.equalsIgnoreCase(s2)
- Problem run-time error if s1 is null!
private boolean equals(String s1, String s2) if
( s1 null s2 null ) return true if ( s1
null s2 null ) return false return
s1.equalsIgnoreCase(s2)
26Avoid referencing null Objects (2)
- Effective Java avoid too much defensive
programming - makes program longer and less efficient
- can hide logic errors in the program
- Alternate use preconditions and assertions (CJ,
p.594)
/ Compare two Strings ignoring case. _at_param
s1 first string _at_param s2 second string to
compare _at_precondition s1 ! null and s2 !
null _at_return true if strings are equal
/ private boolean equals(String s1, String s2)
assert (s1 ! null s2 ! null)
"Bug!" return s1.equalsIgnoreCase(s2)
27Bitwise operators
Bitwise operators compare or manipulate bits on
primitive data types. Bitwise Logic
Operators AND OR XOR bitwise NOT (ones
complement) Shift operators ltlt left-shift gtgt righ
t-shift gtgtgt unsigned right shift
28Bitwise operators
(Bitwise AND)
(Bitwise OR)
(Bitwise XOR)
0
0
0
1
1
1
0
0
0
0
1
0
0
1
0
0
1
1
1
1
0
1
1
1
(Bitwise NOT)
0
1
1
0
29Bitwise operators
Crude way to view the bit representation of an
integer
int n 12345 // show the bit in the 4th
position from right bit (n (1ltlt3)) n
000001000 // shift this bit all the way to the
right bit (n (1ltlt3)) gtgt 3 // 1 if 4th bit
of n is 1 // show all the bits using a loop for(
int k Integer.SIZE -1 kgt0 k-- ) bit (n
(1 ltlt k)) gtgt k System.out.print(""
bit) System.out.println("")
30(condition) ? expression1 expression2
- An inline version of if else .... The
only ternary (3 argument) operator in Java. The
usage is
String grade grade ( score gt 60 ) ? pass
fail
condition to test
do this if true
do this if false
// is the same as this if ( score gt 60 ) grade
pass else grade fail
31Conditional Examples
// Compute the quotient numerator / denom. //
Avoid dividing by zero in case denom
0 quotient numerator / ( denom ! 0 ) ? denom
1
// Announce new mail int numMessages
getNewMail( ) System.out.println("You have "
numMessages " new " (numMessages 1 ?
"message" "messages") )
You have 1 new message if numMessages 1 You
have 3 new messages any other value
32The switch Statement
- switch ( expression ) // Start switch block
- case value1
- statement
- case value2
- statement
- statement
- case value3
- ...
- default
- statement
- // end of switch block
compare expression to each of the values go to
the first one that matches.Then continue until
the end of switch block!
If no matches, then jump to the "default" case
(optional).
The expression can be of type char, byte, short,
or int. It cannot be a floating point or String
value.
33switch Example
- switch ( grade ) // Start switch block
- case 'A'
- gp 4.0
- case 'B'
- gp 3.0
- System.out.println("Still in case B")
- case 'C'
- gp 2.0
- System.out.println("Still in case
C") default - gp 1.0
- // end of switch block
- System.out.println("gp "gp)
Try this for different values of grade
34Using "break" in switch
- switch ( expression ) // Start switch block
- case value1
- statement
- case value2
- statement
- statement
- break
- case value3
- ...
- // end of switch block
- next_statement
when break is encountered, control will jump to
the instruction after end of the switch block.
break causes execution to "break out" of a switch
or loop. break causes execution to jump forward
to the end of block.
35switch with break Example
- switch ( grade ) // Start switch block
- case 'A'
- gp 4.0
- case 'B'
- gp 3.0
- System.out.println("Still in case B")
- break
- case 'C'
- gp 2.0
- System.out.println("Still in case
C") default - gp 1.0
- // end of switch block
- System.out.println("gp "gp)
Try this for different values of grade