310 likes | 463 Views
Intro to CS – Honors I Control Flow: Branches. Georgios Portokalidis gportoka@stevens.edu. Control Flow. Control flow is very important! Control flow allows a program to take decisions Choose an option from a list of options. If-Else. if you_have_money_in_the_bank then
E N D
Intro to CS – Honors IControl Flow: Branches Georgios Portokalidis gportoka@stevens.edu
Control Flow • Control flow is very important! • Control flow allows a program to take decisions • Choose an option from a list of options
If-Else if you_have_money_in_the_bank then balance = balance + (INTEREST_RATE * balance) / 12; else balance = balance - OVERDRAWN_PENALTY; Condition or Boolean expression do you have money? Actions False True Execute balance = balance + (INTEREST_RATE * balance) / 12; Execute balance = balance - OVERDRAWN_PENALTY;
Boolean Expressions • Compare two operands
If-Else Revisited if (balance >= 0) balance = balance + (INTEREST_RATE * balance) / 12; else balance = balance - OVERDRAWN_PENALTY; if (Boolean_Expression) Statement_1 else Statement_2 balance >= 0 False True Execute balance = balance + (INTEREST_RATE * balance) / 12; Execute balance = balance - OVERDRAWN_PENALTY;
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
Logical Operators • Same operators as in binary numbers • (Sub_Expression_1) operator (Sub_Expression_2)
Using AND and OR Are parentheses necessary? 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");
The Negation Operator • if (!(number >= min)) System.out.println("Too small"); • else System.out.println("OK")
If-without-else • if (balance >= 0) • balance = balance + (INTEREST_RATE * balance) / 12; System.out.println(“New balance: “ + balance); do you have money? False True Execute balance = balance + (INTEREST_RATE * balance) / 12; Execute next statement
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 < max)) (!(pressure > min) || (!(pressure < max)) • (pressure <= min) || (pressure >= max)
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;
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;
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;
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");
The Conditional Operator if (n1 > n2) max = n1; else max = n2; max = (n1 > n2) ? n1 : n2;
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); }
Comparing Strings Use the equals() method Use equalsIgnoreCase() for case insensitive comparison How about using == with strings? How about now? String objects if (“hello”.equals(“hello”)) System.out.println(“All is well”); 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?”);
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);
The Boolean Type • Using Boolean variables can make your programs easier to read if ((temperature <= 100) && (thrust >= 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) booleansystemsAreOK = ((temperature <= 100) && (thrust >= 12000) && (cabinPressure > 30) if (systemsAreOK) System.out.println("Initiate launch sequence."); else System.out.println("Abort launch sequence.");
Short-Circuit Evaluation (expressionA) || (expressionB) (expressionA) && (expressionB) Can we optimize the common case?
After … using switch The switch Statement • 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; • } Before using multibranch if-else statements 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.");
Switch Syntax • SYNTAX • switch (Controlling_Expression) • { • case Case_Label: • Statement; • ... • Statement; • break; • case Case_Label: • Statement; • ... • Statement; • break; • default: • Statement; • ... • Statement; • break; • } • The Controlling_Expressionmust 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
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: letter = ‘a’; letter = ‘B’; letter = ‘c’;
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: • intmovieStars; // 0 bad, 1 average, 2excellent • Approach 2: • enumMovieRating { EXCELLENT, AVERAGE, BAD }; • MovieRatingmovieStars = MovieRating.AVERAGE;
Using Enumerations with the Switch statement Case labels are assumed to belong to the enumeration in the switch expression • 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."); • }