Objectives • learn about Java branching statements • learn about loops Flow of Control • learn about the type boolean Chapter 3 Flow of Control Branching Statements: Outline • Flow of control is the order in which a • The if-else Statement program performs actions. • Introduction to Boolean Expressions – Up to this point, the order has been • Nested Statements and Compound sequential. Statements • A branching statement chooses between two • Multibranch if-else Statements or more possible actions. • The switch Statament • A loop statement repeats an action until a • (optional) The Conditional Operator stopping condition occurs. The if-else Statement, The if-else Statement cont. • A branching statement that chooses between • example two possible actions. if (count < 3) • syntax total = 0; if ( Boolean_Expression ) else Statement_1 total = total + count; else Statement_2 1
The if-else Statement, Compound Statements cont. • class BankBalance • To include multiple statements in a branch, enclose the statements in braces. if (count < 3) { total = 0; count = 0; } Introduction to Boolean Omitting the else Part Expressions • If the else part is omitted and the expression after the if is false, no action occurs. • The value of a boolean expression is either true or false. • syntax if ( Boolean_Expression ) • examples Statement time < limit • example balance <= 0 if (weight > ideal) caloriesPerDay -= 500; Compound Boolean Java Comparison Operators Expressions • Boolean expressions can be combined using the “and” ( && ) operator. • example if ((score > 0) && (score <= 100)) ... • not allowed if (0 < score <= 100) ... 2
Compound Boolean Compound Boolean Expressions, cont. Expressions, cont. • syntax • Boolean expressions can be combined using the “or” ( || ) operator. ( Sub_Expression_1 ) && ( Sub_Expression_2 ) • Parentheses often are used to enhance • example readability. if ((quantity > 5) || (cost < 10)) ... • The larger expression is true only when both • syntax of the smaller expressions are true. ( Sub_Expression_1 ) || ( Sub_Expression_2 ) Compound Boolean Negating a Boolean Expressions, cont. Expression • The larger expression is true • Boolean negation – when either of the smaller expressions is – “not” ( ! ) operator. true • syntax – when both of the smaller expressions are ! Boolean_Expression true. • Example: • “or” in Java is inclusive or Boolean walk = false; – either or both to be true. System.out.println(!walk); • exclusive or – one or the other, but not both to be true. Truth Tables Primary Logical Operators • Primary logical operators: and, or, not • Any logical expression can be composed • Example: exclusive or (a || b) && !(a && b) • Either work or play: (work || play) && !(work && play) • ^ is exclusive-or in Java – work ^ play – not a logical operator in most languages 3
Using == Using == , cont . • == is appropriate for determining if two • == is not appropriate for determining if two integers or characters have the same value. objects have the same value. if (a == 3) – if (s1 == s2) where a is an integer type • determines only if s1 and s2 are at the same memory location. • == is not appropriate for determining if two floating point values are equal. – If s1 and s2 refer to strings with identical sequences of characters, but stored in – Use < and some appropriate tolerance instead. if (Math.abs(b - c) < epsilon) different memory locations – b , c , and epsilon are of floating point type • (s1 == s2) is false. [ www.cs.fit.edu/~pkc/classes/cse1001/FloatEquality.java ] equals and Using == , cont . equalsIgnoreCase • To test the equality of objects of class String, • syntax use method equals. String .equals( Other_String ) String .equalsIgnoreCase( Other_String ) s1.equals(s2) or s2.equals(s1) www.cs.fit.edu/~pkc/classes/cse1001/StringEqual.java • To test for equality ignoring case, use method equalsIgnoreCase. (“Hello”.equalsIgnoreCase(“hello”)) Testing Strings for Equality Lexicographic Order • class StringEqualityDemo • Lexicographic order is similar to alphabetical order, but is it based on the order of the characters in the ASCII (and Unicode) character set. – All the digits come before all the letters. – All the uppercase letters come before all the lower case letters. 4
Method compareTo Lexicographic Order, cont. • Strings consisting of alphabetical characters • syntax can be compared using method compareTo and String_1 .compareTo( String_2 ) method toUpperCase or method toLowerCase. • Method compareTo returns String s1 = “Hello”; – a negative number if String_1 precedes String lowerS1 = s1.toLowerCase(); String_2 String s2 = “hello”; – zero if the two strings are equal if (lowerS1.compareTo(s2) == 0) – a positive number of String_2 precedes System.out.println(“Equal!”); String_1 //or use s1.compareToIgnoreCase(s2) – Tip: Think of compareTo is subtraction Comparing Numbers vs. Nested Statements Comparing Strings • An if-else statement can contain any sort of Integer and floating- String objects statement within it. point values • In particular, it can contain another if-else equals( ) == statement. equalsIgnoreCase( ) != – An if-else may be nested within the “if” part. compareTo( ) > – An if-else may be nested within the “else” [lexicographical < part. ordering] >= – An if-else may be nested within both parts. <= Nested if Example Nested Statements, cont. • syntax if (temperature > 90) // int temperature if ( Boolean_Expression_1 ) if (sunny) // boolean sunny if ( Boolean_Expression_2 ) System.out.println(“Beach”); Statement_1 else else System.out.println(“Movie”); Statement_2 else else if (sunny) if ( Boolean_Expression_3 ) System.out.println(“Tennis”); Statement_3 else else System.out.println(“Volleyball”); Statement_4 5
Nested Statements, cont. Nested Statements, cont. • Each else is paired with the nearest • Different indentation unmatched if. first form second form • Indentation can communicate which if goes if (a > b) if (a > b) if (c > d) if (c > d) with which else. e = f; e = f; • Braces are used to group statements. else else g = h; g = h; Same to the compiler! Nested Statements, cont. Nested Statements, cont. • Are these different? • Proper indentation and nested if-else statements first form second form “else” with outer “if” “else” with inner “if” if (a > b) if (a > b) { if (c > d) if (a > b) if (a > b) if (c > d) e = f; { if (c > d) e = f; else if (c > d) e = f; } g =h; e = f; else else } g =h; g = h ; else g = h ; Compound Statements Compound Statements, cont. • When a list of statements is enclosed in • A compound statement can be used braces ( {} ), they form a single compound wherever a statement can be used. statement. • example • syntax if (total > 10) { { sum = sum + total; Statement_1; total = 0; Statement_2; } … } 6
Multibranch if-else Multibranch if-else Statements, cont. Statements • class Grader • syntax if ( Boolean_Expression_1 ) Statement_1 else if ( Boolean_Expression_2) Statement_2 else if ( Boolean_Expression_3) Statement_3 else if … else Default_Statement Multibranch if-else switch Statement Statements, cont. • The switch statement is a multiway branch • equivalent logically that makes a decision based on an integral if (score >= 90) (integer or character) expression. grade = ‘A’; if ((score >= 80) && (score < 90)) • The switch statement begins with the keyword grade = ‘B’; switch followed by an integral expression in if ((score >= 70) && (score < 80)) parentheses and called the controlling grade = ‘C’; if ((score >= 60) && (score < 70)) expression. grade = ‘D’; if (score < 60) grade = ‘F’; switch Statement, cont. switch Statement, cont. • A list of cases follows, enclosed in braces. • The action associated with a matching case label is executed. • Each case consists of the keyword case followed by • If no match is found, the case labeled – a constant called the case label default is executed. – a colon – The default case is optional, but recommended, even if it simply prints a – a list of statements. message. • The list is searched for a case label matching • Repeated case labels are not allowed. the controlling expression. 7
Recommend
More recommend