decision structures if, if/else conditions. selection decision: determine which of 2 paths to follow...
TRANSCRIPT
Decision Structures
if, if/else conditions
Selection
DECISION:
determine which of 2 paths
to follow
(1 or more statements in each path)
Selection options (in Java)
[selection, guard, decision, conditional]
Single selection if
Double selection if ... else
Multiple selectionswitch
or
if … else if … else if … else …
Plain if’s (3 variations)
if (condition true)
action;
------------------
if (condition true){
action;}
| if (condition true)| {| action1;| . . .| actionN;| }|||
if … else (3 variations)
if (condition true)action1;
elseaction2;
------------------if (condition true){ action1;}else{ action2;}
| if (condition true)| { action1A;| . . .| action7A;| }| else| { action1B;| . . .| action5B;| }
Each action could be:
• A simple action:• Assignment statement
with arithmetic expression or method call
• I/O from keyboard / file / window• Call to another method
• Another selection statement:if or if. . .else or switch
• A while or do… while or for loop
• [or do absolutely NOTHING] ;
Conditions
Comparison (equality, relational) operators:
== != < > <= >=
NOTE: == compare for equality
= the assignment operator
Compare 2 operands, which can be:
variables, constants, arithmetic expressions,
returned values from a method call, . . .
But NOT Strings (different methods to compare them)
Conditions are true or false
(ageOfStudent < MI_DRINKING_AGE)
(age != 25)
(michiganResident) // a boolean variable
( (a + 2 * 3) <= ( (b - 4) % 3) )
( (Math.PI * r * r) < maxSize )
NOTE: need ( ) around whole condition
Logic operators in conditions
&& (and) || (or) ! (not)
( !(a == 25) ) [same as (a != 25)]
( (a < b) && (c < d) )
( (a == 3) || (c == 1) )
[Note: use truth tables to determine results]
Order of precedence ?
NOTE: need ( ) around whole condition ( (a == b) && (c > -14) ) typical (a == b) && (c > -14) WRONG ( a == b && c > -14 ) OK
“All juniors and seniors with a gpa of at least a 3.0”
(gpa >= 3.0 && classStatus == 3 || classStatus == 4) WRONG
Order of precedence of operators
Unary operators - + !Arithmetic operators * / %
+ -Relational operators < > <= >=
equality operators == !=Logic operators && [AND]
important: “and before or” || [OR]
Assignment operator =
but ( ) can over-ride these
Translation from English?
“All juniors and seniors should get bonus points”
if (classStatus == 3 && classStatus == 4){ . . .} WRONG
classStatus is a variable that holds ONE value
if (classStatus == 3 || classStatus == 4){ . . .} RIGHT
Actions
total = total + exam;
counter++;
System.out.println(“blah blah”);
num = keyboard.nextInt();
. . .
“do nothing” ( ; )Action
if (maritalStatus != ‘M’)numNotMarried = numNotMarried + 1;
OK, but if it’s clearer (less likely to lead to bugs) to specify POSITIVE condition vs. NEGATIVE
if (maritalStatus == ‘M’)
; // empty statement - do nothing
elsenNotMarried = nNotMarried + 1;
Caution with ;(it’s “Empty block of actions”)
WRONG
if (a < b);System.out.println(“a<b”);// println will ALWAYS happens; not related to
if
RIGHTif (a < b) // no ; here
System.out.println(“a<b”);// println MAY happen, depending on if
condition
Nested if/else
if (a == 4) // note indent/align formattingif (b == 5)
answer = 1;else
answer = 2;else
if (b == 5)answer = 3;
elseanswer = 4;
Trace this code using: a: 4, b: 5, answer >> a: 2, b: 5, answer >> a: 4, b: 2, answer >> a: 2, b: 2, answer >>
Empty statement
if (a == 4)if (b == 5)
; // do nothing here, OK
elseanswer = 2;
elseif (b == 5)
answer = 3;else
answer = 4;
Dangling else ?
if (a == 4)if (b == 5)
answer = 1;// WRONG ? Indentation suggests…, but...
else // this else paired with if (b==5)if (b == 5)
answer = 3;else
answer = 4;
// NOTE: compiler ignores formattingand does what instructions actually “say to do”
Prior example actually “says”:
if (a == 4)if (b == 5)
answer = 1;else // so b != 5 falls
hereif (b == 5)
answer = 3;else
answer = 4;Trace this code using: a: 4, b: 5, answer >> a: 2, b: 5, answer >> a: 4, b: 2, answer >> a: 2, b: 2, answer >>
Dangling else - the FIX
if (a == 4){ if (b == 5)
answer = 1;}else // else now applies to 1st if
if (b == 5)answer = 3;
elseanswer = 4;
Nested if/else if/else . . . [works, but NOT TYPICAL
FORMATTING]if (total >= 90) System.out.println(‘A’);else if (total >= 80) System.out.println(‘B’); else if (total >= 70) System.out.println(‘C’); else if (total >= 60)
System.out.println(‘D’); else System.out.println(‘E’);
Nested… generally written as:
if (total >= 90) System.out.println(‘A’);else if (total >= 80) System.out.println(‘B’);else if (total >= 70) System.out.println(‘C’);else if (total >= 60) System.out.println(‘D’);else System.out.println(‘E’);
Stacked (vs. Nested) if’s
int bonus = 0;
if (attendancePercent >= 90)
bonus = bonus + 5;
if (labPoints >= 600)
bonus = bonus + 35;
Stacked - WRONG
if (total >= 90) System.out.println(‘A’);if (total >= 80) System.out.println(‘B’);if (total >= 70) System.out.println(‘C’);if (total >= 60) System.out.println(‘D’);System.out.println(‘E’);
Nested vs. Stacked
NESTED if/else’scontrol goes to ONLY 1 block (the 1st condition that’s true),
so ONLY 1 set of actions is done (or none)• used for:
– mutually exclusive categories - which state to use for tax– FIRST category that applies - grades example– ~ GUI radio buttons
STACKED if’scontrol goes to ALL blocks (& checks all conditions),
so ALL/many sets of actions MIGHT be done
• used for:– ALL categories that apply - cumulative bonus– ~ GUI check boxes
Nested if/else’s
Since control goes to ONLY 1 (or 0) action block(the 1st condition that applies)and none of the subsequent else if blocks
(nor the final else block)(or, if there’s no final else maybe 0 actions occur)
So the ORDER of conditions MAY be important– NO for mutually exclusive categories - state – YES for “use “1st category that applies” - grade example
(shown in earlier slide)• NOTE: grades are really mutually exclusive, but example
didn’t specify conditions in mutually exclusive way
Switch statement
Equivalent to nested if/else
Shown later