1 / 124

Flow of Control

Flow of Control.

ling
Download Presentation

Flow of Control

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Flow of Control A word about PowerPoint. PowerPoint was released by Microsoft in 1990 as a way to euthanize cattle using a method less cruel than hitting them over the head with iron mallets. After PETA successfully argued in court that PowerPoint actually was more cruel than iron mallets, the program was adopted by corporations for slide show presentations. Conducting a PowerPoint presentation is a lot like smoking a cigar. Only the person doing it likes it. The people around him want to hit him with a chair. PowerPoint is usually restricted to conference rooms where the doors are locked from the outside. It is, therefore, considered unsuited for large rallies, where people have a means of escape and where the purpose is to energize rather than daze. - Roger Simon, Politico

  2. Flow of Control Java branching statements: if-else statement switch statement The Conditional Operator Loops: while for repeat-until The type boolean Reading => Section 1.3

  3. Flow of Control Flow of control is the order in which a program performs actions. So far, the order has been sequential. A branching statement chooses between two or more possible actions. A loop statement repeats an action until a stopping condition occurs.

  4. The if-else Statement The if-else statement is one type of branching statement. Syntax: if (Boolean_Expression) Statement_1 else Statement_2 Example: if (age >= 21) numberOfBeers = 2; else numberOfBeers = 0;

  5. The if-else Statement, cont.

  6. Omitting the else Part The else clause is optional; if the expression after the if is false, no action occurs. Syntax: if (Boolean_Expression) Statement Example: numberOfBeers = 0; // Initial assumption System.out.print(“Enter Age:”); age = keyboard.nextInt(); if (age >= 21) numberOfBeers = 2; System.out.println(“Dont Drink and Drive!”);

  7. Compound Statements To include multiple statements in a branch, enclose the statements in braces. if (count < 10) { total = 0; count = 0; } else { System.out.println(“today is Friday”); System.out.println(“tomorrow is Saturday”); } if (x == y) { // Note the equality comparison operator x = x + 1; y = 0; }

  8. Compound Statements A common mistake: if (x == y) x = x + 1; y = 0; Similarly: if (count < 10) { total = 0; count = 0; } else System.out.println(“today is Friday”); System.out.println(“tomorrow is Saturday”);

  9. Introduction to Boolean Expressions The condition in an if-statement (or loop) is a boolean expression. The value of a boolean expression is either true or false. Simple examples: time < limit balance <= 0 ch == ‘a’ x >= y+Z*w x != y // Note the inequality operator

  10. Java Comparison Operators • Boolean expressions are composed using individual “terms” which typically use Java Comparison operators.

  11. Primary Logical Operators Individual terms can be connected using logical operators: && “and” or “conjunction” || “or” or “disjunction” ! “not” or “negation” Arbitrarily complex logical expressions can be composed. (x < y) && (z >= w) !(x < y) || ((x + y) == z) && (w != u) ((x >= w) || (z == y)) && !((u <= v) && (x == y)) Note this adds to our rules of precedence: Parentheses can be used to enhance readability.

  12. Compound Boolean Expressions Example using the “and” (&&) operator. if ((score >= 0) && (score <= 100)) ... Not allowed: if (0 <= score <= 100) ...

  13. Compound Boolean Expressions, cont. Example using the “or” (||) operator. Example: if ((quantity > 5) || (cost < 10)) ... Example using negation: “not” (!) operator. Example: If (!(x > 10)) ...

  14. Truth Tables

  15. Boolean Variables Recall that boolean is a Java primitive type. Variables can be declared and initialized: boolean b1, b2; boolean b3 = true; b1 = true; b2 = false; b3 = b1 && (b2 || !b3); Personal Opinion – boolean variables can be helpful, but are frequently unnecessary and frequently over complicate a program.

  16. Boolean Variables Boolean variables frequently appear in the condition of an if-statement: if (b3 == true) // rookie “mistake” ... if (b3) ... if (!b3) // instead of if (b3 == false) ...

  17. Nested Statements An if-else statement can contain any sort of statement within it. In particular, it can contain another if-else statement in the: “if” part. “else” part. or both. In such a case the if statement is referred to as nested, and as having an inner and outerif statements.

  18. Nested Statements, cont. if (Boolean_Expression_1) if (Boolean_Expression_2) Statement_1 else Statement_2 else if (Boolean_Expression_3) Statement_3 else Statement_4

  19. Nested if Example System.out.print(“Enter temp:”); int temperature = keyboard.nextInt(); System.out.print(“Is it sunny?”); char sunny = keyboard.nextChar(); // user enters ‘y’ or ‘n’ if (temperature > 90) // int temperature if (sunny == ‘y’) // char sunny System.out.println(“Beach”); else System.out.println(“Movie”); else if (sunny == ‘y’) System.out.println(“Tennis”); else System.out.println(“Stay home”);

  20. Nested if Example System.out.print(“Enter temp:”); int temperature = keyboard.nextInt(); System.out.print(“Is it sunny?”); boolean sunny = keyboard.nextBoolean(); // user enters true or false if (temperature > 90) // int temperature if (sunny) // boolean sunny System.out.println(“Beach”); else System.out.println(“Movie”); else if (sunny) System.out.println(“Tennis”); else System.out.println(“Volleyball”);

  21. Nested Statements, cont. The inner if statement, outer if statement, or both, may contain only an else part; consequently there are many forms of nesting. if (Boolean_Expression_1) Statement_1 else if (Boolean_Expression_3) Statement_2 else Statement_3

  22. Nested Statements, cont. if (Boolean_Expression_1) if (Boolean_Expression_2) Statement_1 else Statement_2 else Statement_3

  23. Nested Statements, cont. if (Boolean_Expression_1) if (Boolean_Expression_2) Statement_1 else Statement_2 else if (Boolean_Expression_3) Statement_3

  24. Nested Statements, cont. Why is the following example confusing? if (Boolean_Expression_1) if (Boolean_Expression_2) Statement_1 else if (Boolean_Expression_3) Statement_2 else Statement_3

  25. Nested Statements, cont. Which is it? if (Boolean_Expression_1) if (Boolean_Expression_2) Statement_1 else if (Boolean_Expression_3) Statement_2 else Statement_3

  26. Nested Statements, cont. Each else is paired with the nearest preceding unmatchedif. Braces can be used to group statements and over-ride the above rule. Indentation can communicate which if goes with which else. Indentation does not determine which else goes with which if.

  27. Nested Statements, cont. Indentation does NOT matter; the compiler parses both the same: First formSecond form if (a > b) if (a > b) if (c > d) if (c > d) e = f; e = f; else else g = h; g = h; Second form is preferable; indentation should reflect the nesting of if-else statements.

  28. Nested Statements, cont. These, however, are different: First formSecond form if (a > b) if (a > b) { if (c > d) if (c > d) e = f; e = f; else } g =h; else g = h; Note how the braces force the else to be associated with the outer if.

  29. Multibranch if-else Statements The following pattern of nested if-else statements is common: if (Boolean_Expression_1) Statement_1 else if (Boolean_Expression_2) Statement_2 else if (Boolean_Expression_3) Statement_3 else if(Boolean_Expression_4) Statement_4 else Default_Statement

  30. Multibranch if-else Statements int grade; : if (grade >=90) System.out.print(“A”); else if (grade >= 80) System.out.print(“B”); else if (grade >= 70) System.out.print(“C”); else if(grade >= 60) System.out.print(“D”); else System.out.print(“F”);

  31. Multibranch if-else Statements It is common practice to format this case as follows: if (Boolean_Expression_1) Statement_1 else if (Boolean_Expression_2) Statement_2 else if (Boolean_Expression_3) Statement_3 else if(Boolean_Expression_4) Statement_4 else Default_Statement

  32. Multibranch if-else Reformatted int grade; : if (grade >=90) System.out.print(“A”); else if (grade >= 80) System.out.print(“B”); else if (grade >= 70) System.out.print(“C”); else if(grade >= 60) System.out.print(“D”); else System.out.print(“F”);

  33. Multibranch if-else Statements, cont. • Logically, the preceding is equivalent to: • if (score >= 90) • grade = ‘A’; • if ((score >= 80) && (score < 90)) • grade = ‘B’; • if ((score >= 70) && (score < 80)) • grade = ‘C’; • if ((score >= 60) && (score < 70)) • grade = ‘D’; • if (score < 60) • grade = ‘F’;

  34. Multibranch if-else Statements, cont. • Is the following equivalent? • if (score >= 90) • grade = ‘A’; • if (score >= 80) • grade = ‘B’; • if (score >= 70) • grade = ‘C’; • if (score >= 60) • grade = ‘D’; • if (score < 60) • grade = ‘F’;

  35. Branch Statement Examples See the following for examples of branching with if statements: http://www.cs.fit.edu/~pbernhar/teaching/cse1001/max.txt http://www.cs.fit.edu/~pbernhar/teaching/cse1001/median.txt

  36. Using the Equality Operator == The == operator is used for determining if two integers or characters have the same value: int a = keyboard.nextInt(); if (a == 3) . . . Recall that only a finite number of real numbers can be represented in any fixed number, e.g., 32, of bits. For real numbers, this results in: Round-off error – results from inexact representation of real numbers. Error propagation – results from applying arithmetic operations to values that have been approximated.

  37. Using the Equality Operator == Because of round-off error and error propagation, the == operator is not appropriate for determining if two real number values are equal. It is common to use < and some appropriate tolerance instead: // The “boss” gives you the specific value static final double EPSILON = 0.000001; : if (Math.abs(b - c) < EPSILON) : where b and c are of a floating point type, i.e., double or float

  38. Using the Equality Operator ==, cont. The == operator is also not appropriate for determining if two objects, such as strings, have the same value. String s1 = “hello”; String s2 = “hello”; : if (s1 == s2) System.out.println(“Strings are equal!”); else System.out.println(“Strings are not equal!”);

  39. Using ==, cont. To test the equality of objects of class String, use method equals: String s1 = “hello”; String s2 = “hello”; if (s1.equals(s2)) System.out.println(“Strings are equal!”); else System.out.println(“Strings are not equal!”); Could have used s2.equals(s1) in the above.

  40. Using the Equality Operator ==, cont. Another example: String s1 = “dog”; String s2 = “cat”; if (s1 == s2) System.out.println(“Strings are equal!”); else System.out.println(“Strings are not equal!”); // Correct answer, but //for the wrong reason!!! s1 = s2; // What happens to the memory used by s1? System.out.println(s1); // What is output here? if (s1 == s2) System.out.println(“Strings are equal!”); else System.out.println(“Strings are not equal!”); => “a CAT, is NOT, a DOG!” (from the musical Cats) ≠

  41. equals and equalsIgnoreCase Note that equals is case-sensitive! (what does that mean?) To test for equality ignoring case, use equalsIgnoreCase: if (s1.equalsIgnoreCase(“HelLo”)) would evaluate to true. Normally these methods are called on variables, but not always: s1.equals(s2) // The typical case s1.equals(“dog”) // Also very common “dog”.equals(s1) // Unusual, but occasionally used “dog”.equals(“cat”) // Least likely

  42. Testing Strings for Equality

  43. Some (odd) Terminology Get ready, because “this” is going to be a bit strange… Note on terminology – method calls in Java take the following form: object.method(parameter_1, parameter_2,…,parameter_N) In such cases object is frequently referred to as “this.” Example: equals(Other_String) – Returns true if this string and Other_String are equal. Otherwise, returns false. s1.equals(s2) – Here, s1 is “this.”

  44. Lexicographic Order Lexicographic order is similar to alphabetical order. Based on the order of all the ASCII and Unicode characters: All digits come before all the letters. All uppercase letters come before all lower case letters. The same as alphabetical ordering when all characters are either upper or lower, but not when upper and lower case are mixed. Zip comes before apple Sorting and ordering are really big deals, both algorithmically and historically (check the wikipedia).

  45. Lexicographic Order Some additional string methods: toUpperCase() – Returns a new string having the same characters as this string, but with any lowercase letters converted to uppercase. toLowerCase() - Returns a new string having the same characters as this string, but with any uppercase letters converted to lowercase. compareTo(A_String) – Compares this string with A_String to see which string comes first in lexicographic ordering. Returns a negative integer if this string is first, returns zero if the two strings are equal, and returns a positive integer if A_String is first.

  46. Lexicographic Order Example: String s1 = “Hello”; String s2 = s1.toLowerCase(); String s3 = “hello”; if (s2.compareTo(s3) == 0) System.out.println(“Equal!”); else if (s2.compareTo(s3) < 0) System.out.println(“s2 comes first lexicographically!”); else System.out.println(“s3 comes first lexicographically!”);

  47. Lexicographic Order Example: String s1 = “Hello”; String s2 = “dog”; String s3 = “hello”; if (s2.compareTo(s3) == 0) System.out.println(“Equal!”); else if (s2.compareTo(s3) < 0) System.out.println(“s2 comes first lexicographically!”); else System.out.println(“s3 comes first lexicographically!”);

  48. Lexicographic Order Example: String s1 = “Hello”; String s2 = “dog”; String s3 = “Hello”; if (s2.compareTo(s3) == 0) System.out.println(“Equal!”); else if (s2.compareTo(s3) < 0) System.out.println(“s2 comes first lexicographically!”); else System.out.println(“s3 comes first lexicographically!”);

  49. Lexicographic Order Example ignoring upper and lower case: //or use s1.compareToIgnoreCase(s2) String s1 = “Hello”; String s2 = “hello”; if (s1.compareToIgnoreCase(s2) == 0) System.out.println(“Equal!”); else if (s1.compareToIgnoreCase(s2) < 0) System.out.println(“s1 comes first lexicographically!”); else System.out.println(“s2 comes first lexicographically!”);

  50. switch Statement The switch statement is another multi-way branch statement. More restricted than if-else statements Branching decision based on an integer, char or String expression. See http://www.cs.fit.edu/~pbernhar/teaching/cse1001/switch

More Related