2
Chapter Goals
• To be able to implement decisions using if statements
• To understand how to group statements into blocks
• To learn how to compare integers, floating-point
numbers, strings, and objects
• To recognize the correct ordering of decisions in
multiple branches
• To program conditions using Boolean operators and
variables
3
Comparing Strings
• Don't use == for strings!if (input == "Y") // WRONG!!!
• Use equals method:if (input.equals("Y"))
== tests identity, equals tests for equal contents
B Smith:
9/25: stopped here w/ morning section
B Smith:
9/25: stopped here w/ morning section B Smith:
9/25: stopped here with night section; spent time discussing project and misc questions.
B Smith:
9/25: stopped here with night section; spent time discussing project and misc questions.
B Smith:
9/27 Stopped her with morning section. Spent time discussing String representation, if and if-else, and the && and || constructs. Also completed this slide.
B Smith:
9/27 Stopped her with morning section. Spent time discussing String representation, if and if-else, and the && and || constructs. Also completed this slide.
5
Comparing Strings – IIIcompareTo()
• s.compareTo(t) < 0 means: s comes before t in the dictionary
• “car” comes before “cargo”
• All uppercase letters come before lowercase: “Hello” comes before “car”
6
Comparing Objects
== tests for identity, equals for identical contentRectangle box1 = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box1;
Rectangle box3 = new Rectangle(5, 10, 20, 30);
• box1 != box3, but box1.equals(box3)
• box1 == box2 Caveat: equals must
be defined for the class
7
Testing for null
• null reference refers to no object String middleInitial = null; // Not setif ( . . . ) middleInitial = middleName.substring(0, 1);
• 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 “”
B Smith:
clarify
B Smith:
clarifyB Smith:
Stopped here on 2/7/07
B Smith:
Stopped here on 2/7/07
8
Your Turn
• What is the value of s.length() if s is 1. the empty string ""? 2. the string " " containing a space? 3. null?
10
Your Turn• Which of the following comparisons are
syntactically incorrect? Which of them are syntactically correct, but logically questionable?
String a = "1";String b = "one";double x = 1;double y = 3 * (1.0 / 3);
a) a == "1"b) a == nullc) a.equals("")d) a == be) a == xf) x == yg) x - y == nullh) x.equals(y)
16
Multiple Alternatives: Sequences of Comparisons
if (condition1) statement1;else if (condition2) statement2;. . .else statement4;
• The first matching condition is executed• 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 elseif (richter >= 8.0) r = "Most structures fall";if (richter >= 7.0) // omitted else--ERROR r = "Many buildings destroyed
17
Multiple Alternatives: Nested Branches
• Branch inside another branchif (condition1){ if (condition1a) statement1a; else statement1b;}else statement2;
19
Compound if()• Recall the syntax for an if statement:
if (expression) statement1;
● Recall the syntax for an if-else statement:
if (expression) statement1;
else statement2;
● Note that only a single statement is permitted, but that single statement may be bracketed to form a compound statement
B Smith:
2/2/2005 9:56 AM: Start here Friday
B Smith:
2/2/2005 9:56 AM: Start here Friday
B Smith:
This should be L07 from here on for Fall05. L07 should be if-else, switch, while, and scanf. L08 should be
B Smith:
This should be L07 from here on for Fall05. L07 should be if-else, switch, while, and scanf. L08 should be
20
Compound if-else• The if-else statement:
● The compound if-else
if (expression) statement1;
else statement2;
● Note that only a single statement is permitted after if, but that single statement may be bracketed to form a compound statement
if (expression){
statement1; statement2; statement3;
}else
statement4;
21
Nested if statement• In general, any statement can be replaced with multiple
statements in braces• We can nest the if's to form a multi-condition if scenario,
changing this:
if (myMoney < 5.0) printf(“I'm nearly broke”);
else printf(“ I have more than 5 dollars.”);
● To something like this:
if (myMoney < 5.0) { if (myMoney > 3) printf(“I'm broke but I can buy a latte”); }else printf(“ I have more than 5 dollars.”);
22
Nested if statement (cont'd)• Braces in this statement are important
if (myMoney < 5.0) { if (myMoney > 3) printf(“I'm broke but I can buy a latte”); }else printf(“ I have more than 5 dollars.”);
● The same statement without braces would be evaluated as
if (myMoney < 5.0) if (myMoney > 3) printf(“I'm broke but I can buy a latte”); else printf(“ I have more than 5 dollars.”);
● The else is associated with the nearest if!
24
Using Boolean Expressions: The boolean Type
• George Boole (1815-1864): pioneer in the study of logic• value of expression amount < 1000 is true or false.• boolean type: one of these 2 truth values
25
Using Boolean Expressions: Predicate Method
• A predicate method returns a boolean value
public boolean isOverdrawn()
{
return balance < 0;
}
• Use in conditionsif (harrysChecking.isOverdrawn())
. . .
26
Predicate Methods II
• Useful predicate methods in Character class:isDigit
isLetter
isUpperCase
isLowerCase
• if (Character.isUpperCase(ch)) . . .
27
Predicate Methods II
Making code less fragile
• Useful predicate methods in Scanner class: hasNextInt() and hasNextDouble()
if (in.hasNextInt())
n = in.nextInt();
29
Using Boolean Expressions: The Boolean Operators
• && and• || or• ! not
if (0 < amount && amount < 1000) . . .
if (input.equals("S") || input.equals("M")) . . .
30
Using Boolean Variables
private boolean married;
• Set to truth value:married =
input.equals("M");
32
Reduce booleans
• It is unnecessary to write a test such asif (married == true) . . . // Don't
• Just use the simpler testif (married) . . .
33
Self Check
• When does the statementSystem.out.println (x > 0 || x < 0);print false?
• Rewrite the following expression, avoiding the comparison with false:
if (Character.isDigit(ch) == false) . . .
35
The switch statement• The earlier series of if-else statements can get pretty hairy when
checking multiple conditions. Imagine checking user input for a number of possible entries:
String input = keyboard.nextLine(); char ch = input.charAt(0);
System.out.println(“character entered is : “);if (ch == 'a')
System.out.println(“the letter a”);else if (ch == 'b')
System.out.println(“the letter b”);else if (ch == 'c')
System.out.println(“the letter c”);else if (ch == 'd')
System.out.println(“the letter d”);else if (ch == 'e')
System.out.println(“the letter e”);.
B Smith:
Point out that the text has an error in the source code.
B Smith:
Point out that the text has an error in the source code.
B Smith:
What does current pedagogy say regarding the teaching of switch? Should it be included?
B Smith:
What does current pedagogy say regarding the teaching of switch? Should it be included?
36
The switch statement (cont'd)• One option is to use the switch statement
char ch;System.out.println(“character entered is : “);switch (ch){
case 'a':System.out.println(“the letter a”);break;
case 'b':System.out.println(“the letter b”);break;
case 'c':System.out.println(“the letter c”);break;
default:System.out.println(“Invalid entry”);
}
Note the colon!
‘default:’When none of the cases are
met.
Good practice for unexpected conditions
B Smith:
Point out the efficiency advantages. A switch uses the “decide and jump to” algorithm vs looking at EVERY single condition!
B Smith:
Point out the efficiency advantages. A switch uses the “decide and jump to” algorithm vs looking at EVERY single condition!
37
The switch statement (cont'd)• You can use the switch statement with multiple scenarios,
or cases
switch (number){
case 1:System.out.println(“You like peaches”);break;
case 2:System.out.println(“You like oranges”);break;
case 3: case 4: case 5: System.out.println(“You like Fuji, Gala, or Washington apples”);break;
default:System.out.println(“You chose an unknown snack”);
}
Multiple cases