Download presentation
Presentation is loading. Please wait.
Published byMyra Goodman Modified over 9 years ago
1
Control Structures special statements whose purpose is to change the order of execution in a program. Sequential structures – Statements executed sequentially Selection structures Repetition structures (loop) decision.ppt
2
Selection Given hours worked and pay rate, calculate total pay
How about if you work overtime? How do you indicate if your work overtime? How about double overtime? decision.ppt
3
Selection Single-selection structure Double-selection structure
The if structure selects or ignores a single action. Double-selection structure The if/else structure selects between two different actions. Multiple-selection structure The switch structure selects one of many possible actions (to be discussed later) decision.ppt
4
What is truth? 0 is false anything other than 0 is true decision.ppt
5
Relational Operators < Less than <= less than or equal to >
greater than >= Greater than or equal to == equals != not equal to decision.ppt
6
examples: int x = 4; int y = 6 ;
EXPRESSION VALUE x < y true x + 2 < y false x != y true x + 3 >= y true y == x false y == x + 2 true 'r' < 't' true decision.ppt
7
Beware: == vs = Hard to find bug = assignment == test for equality
x = 5; if (x == 5) if (x=5) Has two unexpected results Assigns x a 5 Evaluates to true Hard to find bug decision.ppt
8
Java Operator Precedence
Description operator Unary ++, --, +, - Multiplicative *, /, % Additive +, - Relational <, >, <=, >= Equality ==, != Assignment =, +=, -=, *=, /=, %= decision.ppt
9
Comparing strings str1.compareTo(str2)
Compares two string lexicographically A negative integer value if str1 < str2 0 if str1 is equivalent to str2 A positive integer if str1 > str2 compareTo public int compareTo(String anotherString) The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true. This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value: this.charAt(k)-anotherString.charAt(k) If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value: this.length()-anotherString.length() Specified by: compareTo in interface Comparable<String> Parameters: anotherString - the String to be compared. Returns: the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument. decision.ppt
10
Example >String str1 = "Hello"; >String str2 = "Hi";
>System.out.println(str1.compareTo(str2)); -4 > System.out.println(str2.compareTo("Hi")); > System.out.println(str2.compareTo("Big")); 6 decision.ppt
11
equals – tests objects for equality
str1.equals(str2) str1.equalsIgnoreCase(str2); if (s.equalsIgnoreCase("yes")) decision.ppt
12
Logical Operators Operator Meaning Syntax && AND exp1 && exp2 || OR
! NOT !exp1 decision.ppt
13
&& - Logical AND P Q P && Q true false decision.ppt
14
|| - Logical OR P Q P || Q true false decision.ppt
15
! Not P !P true false decision.ppt
16
Equivalent Expression
DeMorgan's Law: not(P and Q) is equivalent to (not P) or (not Q), !(P && Q) = (!P) || (!Q) not(P or Q) is equivalent to (not P) and (not Q), !(P || Q) = (!P) && (!Q) Expression Equivalent Expression !(P == Q) P != Q !(P == Q | | P == R) P != Q && P != R !(P == Q && P == R) P != Q | | P != R !(P == Q && R > S) P !=Q | | R <=S Note: left expression is equivalent to right expression with! added and the relational and logical operators reversed decision.ppt
17
Java Operator Precedence
Description operator Unary ++, --, +, -, ! Multiplicative *, /, % Additive +, - Relational <, >, <=, >= Equality ==, != Assignment =, +=, -=, *=, /=, %= Logical And && Logical Or || = decision.ppt
18
Examples: Do not depend on operator precedence while using expressions containing side-effects x>3 && x++ 5 > 2 && 4 > 7 false 5 > 2 || 4 < 7 true !(4 < 7) false if ((sex == 'F') && (cityCode == 18) && (gpa >= 3.8)) if ((zipCode.equals("48002")) || (zipCode.equals("48003")) || (zipCode.equals( "48004")) !(hours > 40) same as: hours <= 40 decision.ppt
19
Short-Circuit Evaluation
evaluation proceeds from left to right the computer stops evaluating sub-expressions as soon as the truth value of the entire expression can be determined Exercise caution when the operands following the first operand contain side effects (see notes) Rule of thumb: first true in OR => Entire expression is true first false in AND => Entire expression is false The conditional AND and OR operators (&& and ||, respectively) exhibit short-circuit behavior. That is, the second operand is evaluated only when the result cannot be deduced solely by evaluating the first operand. Exercise caution when the operands following the first operand contain side effects. In the following code, the value of i is incremented only when i >= 0. int i = // initialize to user supplied value if ((i >= 0) && ((i++) <= Integer.MAX_VALUE)) { // ... } Although the behavior is well defined, it is unclear whether i gets incremented. For more information see: EXP07-J. Be aware of the short-circuit behavior of the conditional AND and OR operators decision.ppt
20
Short-Circuit Examples:
int age = 25; int weight = 150; (age > 50) && (weight > 140) // false Evaluation can stop after determining that (age > 50) is false, it is already determined that the entire expression will be false. (weight >= 150)||(age > 40) // true Evaluation can stop after determining that (weight >= 50) is true, it is already determined that the entire expression will be true. (age < 50) && (weight > 140) // true After determining that (age < 50) is true, we have to determine the truth value of the second part. (age < 20) || (weight < 140) // false After determining that (age < 20) is false, we have to determine the truth value of the second part. decision.ppt
21
Exercises Write an expression for the following:
taxRate is over 25% and income is less than $20000 temperature is less than or equal to 75 or humidity is less than 70% age is over 21 and age is less than 60 age is 21 or 22 For what value(s) of x would this condition be true? (x < 1) && (x > 10) For what value(s) of y would this condition be true? (y >= 1) && (y <= 10) decision.ppt
22
Example x > y + 2 => x > (y + 2) x + 3 <= y * 10
a <= b > c < d >= e will be executed as: ( ) > c ( ) < d ( ) >= e ( ) decision.ppt
23
Relational Operators with Floating Point Types
Do not compare floating-point numbers for equality; approximate values, they are rarely exactly equal. test for near equality compute the difference between the 2 numbers and check if the result is less than some max difference. Example: float x = 1.0; float y = 3.0; float z; z = x/y; if (x == z * y)... // x will not be 1.0, but if (abs(x - z * y) < )... // close enough decision.ppt
24
Compound Logical Expressions
if (a < b < c) syntax error In this expression, c is compared with 1 or 0 (the result of evaluating a < b int total = 50; if (80 < total < 90) System.out.println("Final grade is B"); According to the precedence chart, the expression (80 < total < 90) means (80 < total) < 90 because "<" is left associative, (80 < total ) is false (false < 90) is invalid. if ((80 < total) && (total < 90)) //correction decision.ppt
25
if Syntax if ( Expression ) Statement
NOTE: Statement can be a single statement, a null statement, or a block (compound statement). decision.ppt
26
if statement is a selection
of whether or not to execute a statement (which can be a single statement or an entire block) TRUE expression FALSE statement decision.ppt
27
if Single statement EX1: if (number % 2 == 0)
System.out.println("Even number!"); EX2: if (i) { //defensive programming System.out.println(i is nonzero"; } decision.ppt
28
compound statement Multiple statements where one is allowed
if (state == MD) { amt = amt + (amt * .05); cout <<amt; } decision.ppt
29
if else syntax if (Expression )
StatementA else StatementB NOTE: StatementA and StatementB each can be a single statement, a null statement, or a compound statement. decision.ppt
30
if..else provides two-way selection
between executing one of 2 clauses (the if clause or the else clause) TRUE FALSE expression if clause else clause decision.ppt
31
Example: if (i >= 0) { System.out.println("positive"); } else
System.out.println("negative"); if (i >= 0) System.out.println("positive"); else System.out.println("negative"); braces may be omitted if there is only one clause: Recommended - leaving the braces in case another statement is added. decision.ppt
32
=> Watch out for null statement
if (x > 0); //does nothing if (x > 0); //hard to find bug System.out.println("Positive"); decision.ppt
33
Nested IF Statements The body of an if-clause or else-clause can contain another if or if-else statement this is called a nested control structure or a nested if In general, any problem that involves a multiway branch (more than 2 alternative solutions) can use nested if statements. decision.ppt
34
System.out.println("Positive"); else // nested if else if (x < 0)
System.out.println("Negative"); else System.out.println("Zero"); decision.ppt
35
change indentation (remove whitespace)
if (x > 0) System.out.println("Positive"); else if (x < 0) System.out.println("Negative"); else System.out.println("Zero"); decision.ppt
36
3 way choice version 1:separate ifs if (x > 0) posCount++;
negCount++; if (x==0) zeroCount++; How many branches are tested, best case, worst case? decision.ppt
37
3 way choice Version 2: Nested ifs if (x > 0) posCount++; else
negCount++; zeroCount++; How many branches are tested, best case, worst case? decision.ppt
38
3 way choice Version 3: Nested ifs, special indentation (preferred version) if (x > 0) posCount++; else if (x < 0) negCount++; else zeroCount++; How many branches are tested, best case, worst case? decision.ppt
39
else if if (cond) statement else if (cond) else
evaluated in order, if any expression is true, that statement and that statement only is executed. only difference is whitespace preferred method - shows we are making a choice decision.ppt
40
Example: if (temp <= 32) System.out.println("freeze");
System.out.println("boil"); if ((temp >= 32) and (temp <= 212)) System.out.println("liquid"); if (temp <= 32) System.out.println("freeze"; else if (temp >= 212) System.out.println("boil"); else System.out.println("liquid"); decision.ppt
41
Situation Construct Basic form
You want to execute any combination of control statements Sequentials ifs if (<test1>) <statement1>; if (<test2>) <statement2>; if (<testn>) <statementn>; You want to execute zero or one of the control statements Nested ifs ending in test else if (<test2>) else if (<testn>) You want to execute exactly one of the controlled statements Nested ifs ending in else else decision.ppt
42
Dangling else: else matches with most recent unmatched if
if (n > 0) if (a > b) z = a; else z = b; if (n > 0) if (a > b) z = a; else z = b; autoformatting in IDEs is a good way to catch many of these kinds of errors decision.ppt
43
Dangling else if ( num > 0 ) if ( num < 10 )
System.out.println("aaa") ; else System.out.println("bbb") ; decision.ppt
44
Overtime example if (hours <= 40) totalPay = hours * payRate;
else if (hours <= 60) { regPay = 40 * payRate; otPay = (hours – 40) * payRate * 1.5; totalPay = regPay + otPay; } else otPay = 20 * payRate * 1.5; doubleOtPay =(hours – 60)* 2 * payRate; totalPay = regPay + otPay + doubleOtPay; decision.ppt
45
Overtime example if ((hours < 0 || (hours > 168))
System.out.println("Invalid"); else if (hours <= 40) totalPay = hours * payRate; else if (hours <= 60) { regPay = 40 * payRate; otPay = (hours – 40) * payRate * 1.5; totalPay = regPay + otPay; } else otPay = 20 * payRate * 1.5; doubleOtPay =(hours – 60)* 2 * payRate; totalPay = regPay + otPay + doubleOtPay; decision.ppt
46
Grade Example // Get grade System.out.println( "Enter the grade:");
int grade; // Get grade System.out.println( "Enter the grade:"); grade = console.nextInt(); System.out.println( "Your grade of " + grade + " is "); // Print letter grade if (grade >= 90) System.out.println( "A." ); else if (grade > 80) System.out.println( "B." ); else if (grade >= 70) System.out.println( "C." ); else if (grade >= 60) System.out.println( "D." ); else System.out.println( "F." ) decision.ppt
47
?: expression1 ? expression2:expression3 max = (a>=b) ? a : b;
if (a >= b) max = a; else max = b; decision.ppt
48
switch switch (expression) { case value1: statements break;
… default: } decision.ppt
49
switch switch works with:
byte, short, char, and int primitive data types. enumerated types the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, Int All switch statements can be re-written as if..else Not all if..else can be rewritten as switch An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object decision.ppt
50
break Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered. decision.ppt
51
public static void main (String [] args) {
import java.util.*; public class Switch { public static void main (String [] args) { Scanner console = new Scanner(System.in); int yearLevel; System.out.print("Enter year Level: "); yearLevel = console.nextInt(); switch (yearLevel) { case 1: System.out.println("You are a freshman!"); break; case 2: System.out.println("You are a sophomore!"); case 3: System.out.println("You are a junior!"); case 4: System.out.println("You are a Senior!"); default: System.out.println("Invalid entry!"); } decision.ppt
52
import java.util.*; public class SwitchDemo { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Enter month: "); int month = console.nextInt(); switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Invalid month.");break; } decision.ppt
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.