Download presentation
Presentation is loading. Please wait.
Published byRobyn Yearsley Modified over 9 years ago
1
Intro to CS – Honors I Control Flow: Branches GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU
2
Control Flow Control flow is very important! Control flow allows a program to take decisions ◦Choose an option from a list of options
3
If-Else if you_have_money_in_the_bank then balance = balance + (INTEREST_RATE * balance) / 12; else balance = balance - OVERDRAWN_PENALTY; do you have money? Execute balance = balance + (INTEREST_RATE * balance) / 12; Execute balance = balance - OVERDRAWN_PENALTY; True False Condition or Boolean expression Actions
4
Boolean Expressions Compare two operands
5
If-Else Revisited if (balance >= 0) balance = balance + (INTEREST_RATE * balance) / 12; else balance = balance - OVERDRAWN_PENALTY; balance >= 0 Execute balance = balance + (INTEREST_RATE * balance) / 12; Execute balance = balance - OVERDRAWN_PENALTY; True False if (Boolean_Expression) Statement_1 else Statement_2
6
Common Errors Using = instead of == Example: if (balance = 2) What is the effect of the above? Comparing floating-point values with == or != Remember that floating-point numbers are an approximation Better to check if a number is within a range! Example: min < pressure < max This is not a valid expression
7
Logical Operators Same operators as in binary numbers (Sub_Expression_1) operator (Sub_Expression_2) Logical operatorJava operator AND&& OR|| NOT!
8
Using AND and OR if ((pressure > min) && (pressure < max)) System.out.println("Pressure is OK."); else System.out.println("Warning: Pressure is out of range."); if ((salary > expenses) || (savings > expenses)) System.out.println("Solvent"); else System.out.println("Bankrupt"); Are parentheses necessary?
9
The Negation Operator if (!(number >= min)) System.out.println("Too small"); else System.out.println("OK")
10
Avoiding Negation
11
If-without-else if (balance >= 0) balance = balance + (INTEREST_RATE * balance) / 12; System.out.println(“New balance: “ + balance); do you have money? Execute balance = balance + (INTEREST_RATE * balance) / 12; Execute next statement True False
12
Avoiding Negation II Consider the following: if (!((pressure > min) && (pressure < max))) System.out.println(“Houston we have a problem!"); Is there an equivalent without negation? !((pressure > min) && (pressure min) || (!(pressure < max)) (pressure = max)
13
Nested if-else Statements if (balance >= 0) Apply interest rate expression else balance = balance − OVERDRAWN_PENALTY; if (balance >= 0) if (INTEREST_RATE >= 0) balance = balance + (INTEREST_RATE * balance) / 12; else System.out.println("Cannot have a negative interest."); else balance = balance − OVERDRAWN_PENALTY;
14
Use Braces for Clarity if (balance >= 0) { if (INTEREST_RATE >= 0) balance = balance + (INTEREST_RATE * balance) / 12; else System.out.println("Cannot have a negative interest."); } else balance = balance − OVERDRAWN_PENALTY;
15
Use Braces for Correction else always matches the last unmatched if //First Version − Braces if (balance >= 0) { if (INTEREST_RATE >= 0) balance = balance + (INTEREST_RATE * balance)/12; } else balance = balance − OVERDRAWN_PENALTY; //Second Version - No Braces if (balance >= 0) if (INTEREST_RATE >= 0) balance = balance + (INTEREST_RATE * balance)/12; else balance = balance − OVERDRAWN_PENALTY;
16
Multibranch if-else Statements if (balance > 0) System.out.println("Positive balance"); else if (balance < 0) System.out.println("Negative balance"); else if (balance == 0) System.out.println("Zero balance"); if (balance > 0) System.out.println("Positive balance"); else if (balance < 0) System.out.println("Negative balance"); else if (balance == 0) System.out.println("Zero balance");
18
The Conditional Operator if (n1 > n2) max = n1; else max = n2; max = (n1 > n2) ? n1 : n2;
19
Using exit to End a Program if (numberOfWinners == 0) { System.out.println("Error: Dividing by zero."); System.exit(0); } else { oneShare = payoff / numberOfWinners; System.out.println("Each winner will receive $" + oneShare); }
20
Comparing Strings Use the equals() method Use equalsIgnoreCase() for case insensitive comparison How about using == with strings? How about now? if (“hello”.equals(“hello”)) System.out.println(“All is well”); String objects if (“hello”.equalsIgnoreCase(“Hello”)) System.out.println(“All is well”); if (“hello” == “hello”) System.out.println(“Should this work?”); String s1 = new String(“hello”); String s2 = new String(“hello”); if (s1 == s2) System.out.println(“Should this work?”);
21
Lexicographic Comparison s1.compareTo(s2) Returns ◦A negative number if s1 comes before s2 ◦Zero if the strings are equal ◦A positive number if s1 comes after s2 if (s1.compareTo(s2) < 0) System.out.println(s1 + " precedes " + s2 + " in lexicographic ordering"); else if (s1.compareTo(s2) > 0) System.out.println(s1 + " follows " + s2 + " in lexicographic ordering"); else //s1.compareTo(s2) == 0 System.out.println(s1 + " equals " + s2);
22
The Boolean Type Using Boolean variables can make your programs easier to read boolean systemsAreOK = ((temperature = 12000) && (cabinPressure > 30) if (systemsAreOK) System.out.println("Initiate launch sequence."); else System.out.println("Abort launch sequence."); if ((temperature = 12000) && (cabinPressure > 30)) System.out.println("Initiate launch sequence."); else System.out.println("Abort launch sequence."); Boolean variables can be assigned (booleanVariable) can be used instead of (booleanVariable == true)
23
Short-Circuit Evaluation (expressionA) || (expressionB)(expressionA) && (expressionB) expressionAexpressionB&& false truefalse truefalse true expressionAexpressionB|| false truefalsetrue falsetrue Can we optimize the common case?
24
Revisiting Operator Precedence OperatorsPrecedence postfixexpr++ expr-- unary++expr --expr +expr -expr ~ ! multiplicative* / % additive+ - shift > >>> relational = instanceof equality== != bitwise AND& bitwise exclusive OR^ bitwise inclusive OR| logical AND&& logical OR|| ternary? : assignment= += -= *= /= %= &= ^= |= >= >>>=
25
The switch Statement if (numberOfBabies == 1) System.out.println("Congratulations."); else if (numberOfBabies == 2) System.out.println("Wow. Twins."); else if (numberOfBabies == 3) System.out.println("Wow. Triplets."); else if (numberOfBabies == 4 || numberOfBabies == 5) { System.out.print("Unbelievable; "); System.out.println(numberOfBabies + " babies."); } else System.out.println("I don't believe you."); Before using multibranch if-else statements switch (numberOfBabies) { case 1: System.out.println("Congratulations."); break; case 2: System.out.println("Wow. Twins."); break; case 3: System.out.println("Wow. Triplets."); break; case 4: case 5: System.out.print("Unbelievable; "); System.out.println(numberOfBabies + " babies."); break; default: System.out.println("I don't believe you."); break; } After … using switch
26
Switch Syntax The Controlling_Expression must be of an integer type ◦int, short, byte or char Each Case_Label is a constant of the same type as the Controlling_Expression Each case must have a different Case_Label A break may be omitted ◦Without a break, execution just continues to the next case Any number of cases is allowed A default case is optional ◦Without one, no action occurs in the event of a mismatch SYNTAX switch (Controlling_Expression) { case Case_Label: Statement;... Statement; break; case Case_Label: Statement;... Statement; break; default: Statement;... Statement; break; }
27
Omitting break switch (letter) { case'A': case'a': System.out.println("Some kind of A."); case'B': case'b': System.out.println("Some kind of B."); break; default: System.out.println("Something else."); break; } What happens in this example, when: 1.letter = ‘a’; 2.letter = ‘B’; 3.letter = ‘c’;
28
Enumerations An enumeration provides a way to restrict the value of a variable For example: you want to create an application for rating movies as excellent, average, or bad Approach 1: int movieStars; // 0 bad, 1 average, 2 excellent Approach 2: enum MovieRating { EXCELLENT, AVERAGE, BAD }; MovieRating movieStars = MovieRating.AVERAGE;
29
Using Enumerations with the Switch statement switch (rating) { case E: //Excellent System.out.println("You must see this movie!"); break; case A: //Average System.out.println("This movie is OK, but not great."); break; case B: //Bad System.out.println("Skip it!"); break; default: System.out.println("Something is wrong."); } Case labels are assumed to belong to the enumeration in the switch expression
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.