1 / 72

Chapter 6 Boolean Variables & Nested Loops

Chapter 6 Boolean Variables & Nested Loops. Go. Section 1 - Review of Logical & Relational Operators Section 2 - Simple & Compound Boolean Expressions Section 3 - Truth Tables Section 4 - String Methods: trim, length, & compareTo Section 5 - Boolean Variables

Download Presentation

Chapter 6 Boolean Variables & Nested Loops

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. Chapter 6Boolean Variables & Nested Loops Go Section 1 - Review of Logical & Relational Operators Section 2 - Simple & Compound Boolean Expressions Section 3 - Truth Tables Section 4 - String Methods: trim, length, & compareTo Section 5 - Boolean Variables Section 6 - Nested For and While Loops Section 7 - Software Systems Go Go Go Go Go Go 1

  2. Chapter 6 Section 1 Review of Logical and Relational Operators 2

  3. 6.1 Logical Operators Logical operators are used with if, while, and for statements to control the order of execution. Logical Operators allow us to modify simple boolean expressions or combine simple boolean expressions into compound ones. These are the three logical operators: Do not place a space between the operators that use two symbols … && and | | 3

  4. 6.1 Relational Operators Relational operators are used to form simple Boolean Expressions. Here are the six relational operators: Do not place a space between the operators that use two symbols … >= <= == or != 4

  5. 6.1 Precedence Rules for Java Operators 5

  6. Chapter 6 Section 2 Review of Simple and Compound Boolean Expressions 6

  7. 6.2 Simple Boolean Conditions The ! (“NOT”) operator can be applied to a simple boolean condition or a boolean variable. Here it is applied to a simple boolean expression: if ( !(grade > 59) ) System.out.println(“Your grade is an F”); When applied to a boolean variable or expression, ! changes the overall value to the opposite value. In the boolean expression above, if grade > 59 evaluates to true, then !(grade > 59) evaluates to false. In the boolean expression above, if grade > 59 evaluates to false, then !(grade > 59) evaluates to true. 7

  8. 6.2 Compound Boolean Expressions • The && and || operators are used to form compound boolean expressions. • && (referred to as “AND”) • | | (referred to as “OR”) • We have looked at these examples before: • if (grade >= 90 && grade <= 100) • System.out.println (“Your grade is A”); • if (grade < 0 | | grade > 100) • System.out.println (“Grade not possible.”); 8

  9. 6.2 Extended Ifs withSimple Boolean Expressions if (testAverage >= 60) System.out.print(“Grade is D. ”); else if (testAverage >= 70) System.out.print(“Grade is C. ”); else if (testAverage >= 80) System.out.print(“Grade is B. ”); else if (testAverage >= 90) System.out.print(“Grade is A. ”); else System.out.print(“Grade is F. ”); The order of this extended if statement is problematic because if testAverage holds the value 93, then “Grade is D.” will be printed. If we change the conditions of the extended-if so that it contains compound boolean expressions, then the order of the branches doesn’t matter and we can guarantee the accuracy of an extended if. 9

  10. 6.2 Extended if Statementswith compound boolean expressions Here is the rewritten extended-if where the order of the branches doesn’t matter, because compound boolean expressions are used in the test conditions. if (testAverage >= 70 && testAverage < 80) System.out.print(“Grade is C. ”); else if (testAverage >= 80 && testAverage < 90) System.out.print(“Grade is B. ”); else if (testAverage >= 90 && testAverage <= 100 ) System.out.print(“Grade is A. ”); else if (testAverage >= 60 && testAverage < 70) System.out.print(“Grade is D. ”); else System.out.print(“Grade is F. ”); However, having an un-logical order to the branches as seen here makes the code less readable and more difficult to verify. 10

  11. 6.2 Extended if Statementswith compound boolean expressions Here is the rewritten extended-if where the order of the branches doesn’t matter, because compound boolean expressions are used in the test conditions. if (testAverage >= 90 && testAverage <= 100) System.out.print(“Grade is A. ”); else if (testAverage >= 80 && testAverage < 90) System.out.print(“Grade is B. ”); else if (testAverage >= 70 && testAverage < 80) System.out.print(“Grade is C. ”); else if (testAverage >= 60 && testAverage < 70) System.out.print(“Grade is D. ”); else System.out.print(“Grade is F. ”); This order is much more logical and adds to the readability of the code. 11

  12. Chapter 6 Section 3 Truth Tables 12

  13. 6.3 Truth Tables Truth tablesare essential tools for helping us verify the accuracy of logical expressions, whether they are simple or compound. For compound boolean expressions involving logical operators, truth tables show how the value of the overall expression depends on the values of the operands. Here, the operands are A and B. • With two operands we must consider all four possible combinations of values that A and B can have to know what the expression A && B will evaluate to. Here is a truth table that shows the results of evaluating A && B. 13

  14. 6.3 Truth Table for A && B Two operands, A and B.Four possible outcomes for A && B depending on the four possible combinations of true and false. The operands A or B can be simple boolean expressions, like x > 0. The truth table shows you the following results: If A is true and B is true, then A && B evaluates to true. If A is true and B is false, then A && B evaluates to false. If A is false and B is true, then A && B evaluates to false. If A is false and B is false, then A && B evaluates to false. Notice that for A && B to evaluate to true,both and A and B must be true individually. 14

  15. Here is why this is important. You can assume that A and B are simple boolean expressions like: A is grade >= 90 and B is grade <= 100 You could then use a truth table to verify the results of an if condition like: if (grade >= 90 && grade <= 100) when grade holds the value 95. 6.3 Truth Table for A && B This helps verify that the code is correct when various values are tested. 15

  16. 6.3 Truth Table for A || B Two operands, A and B.Four possible outcomes for A || B depending on the four possible combinations of true and false. The truth table shows you the following results: If A is true and B is true, then A || B evaluates to true. If A is true and B is false, then A || B evaluates to true. If A is false and B is true, then A || B evaluates to true. If A is false and B is false, then A || B evaluates to false. Notice that A || B is false,only whenboth A and B are individually false. 16

  17. 6.3 Truth Table for ! A One operand, A.Two possible outcomes for ! A depending on the two possible values of true and false. The truth table shows you the following results: If A is true, then ! A evaluates to false. If A is false, then ! A evaluates to true. 17

  18. 6.3 Possible Combinations in Truth Tables If there aren operands, then there are 2n combinations of true and false. So if there is one operand (like the expression ! A) , there are two possible values of true and false … 21 = 2. If there are 2 operands (like A && B) , there are 4 possible combinations of true and false, and there are 4 possible results … 22 = 4. If there are 3 operands (like A && B && C), there are 8 possible combinations of true and false, and there are 8 possible results … 23 = 8. If there are 4 operands (like A || B || C || D), there are 16 possible combinations of true and false, and there are 16 possible results … 24 = 16. 18

  19. 6.3 Short-Circuit Evaluation using && • In Java, the JVM may know the result of a compound Boolean expression before evaluating all of its parts. Most compilers and systems allow this and will stop evaluation as soon as the result is known. This is called short-circuit evaluation. • If the first operand A is false and the second operand B is true as in if( A && B ) … then the JVM knows the entire condition is falseonce it sees the first operand is falsebecause && is being used and Java knows that both operands must be true for the entire expression to be true. So the second operand B is not examined at all! 19

  20. 6.3 Short-Circuit Evaluation using || For the OR operator ||, if the first operand A is true and the second operand B is false as in if( A || B ) … then the JVM knows the entire condition is trueonce it sees the first operand is true because the OR operator || is being used and Java knows that only one operand must be true for the entire expression to be true. So the second operand is not examined at all. 20

  21. 6.3 Utilizing Short-Circuit Protections This code takes advantage of short-circuit evaluation: Scanner reader = new Scanner(System.in); int count, sum; System.out.print(“Enter the count: ”); count = reader.nextInt(); System.out.print(“Enter the sum: ”); sum = reader.nextInt(); if (count > 0 && sum/count > 10) // count > 0 must be first for this to work! System.out.println(“average > 10”); else System.out.println(“count = 0 or average <= 10”); Note: if count is <= 0, the second part of the boolean expression is NOT evaluated and in particular, if count was 0, then the expression is protected against division by zero. 21

  22. 6.3 DeMorgan’s Law DeMorgan’s Law helps define some useful Boolean equivalences. For instance, the following pairs of Boolean expressions are equivalent as truth tables readily confirm. The first two are what are called DeMorgan’s Law. ! (A || B) equivalent to !A && !B ! (A && B) equivalent to !A || !B A || (B && C) equivalent to (A || B) && (A || C) A && (B || C) equivalent to (A && B) || (A && C) You only need to remember these two. 22

  23. 6.3 Avoid Complicated Logic Its best to avoid complicated logical expressions, because they can be difficult to prove even with a truth table. For example: if (A || B && C) or if (A && B || C) however you might need to use logic that says that four different things must be true before a segment of code is executed or any of four different things must be false before a segment of code is executed. You completed code like this in the program RectangleDrawer. if (x < 0 || y < 0 || width < 1 || height < 1) JOptionPane.showMessageDialog(“null”, “You entered … 23

  24. Chapter 6 Section 4 The String Methods trim(), length(), and compareTo() 24

  25. 6.4 The String Method trim() The String class has a method named trim. When a trim message is sent to a string, a new string that contains no leading or trailing blank spaces is returned. Example: System.out.print(“Enter a name: ”); String name = reader.nextLine(); // if the following is entered from the keyboard: “ Jill ” // then if we printed it out with … System.out.println(name); we would see in the output window … “ Jill ” However, (see next slide) …. 25

  26. 6.4 The String Method trim() If the code was … System.out.print(“Enter a name: ”); String name = reader.nextLine(); // and again we enter from the keyboard: “ Jill ” // and then we use the following lines of code: name = name.trim(); // trim the value in name and restore in name System.out.println(name); then we would see in the output window … “Jill” Again, when we call name.trim(); the String value in name is trimmed and a new String value is created and returned. By restoring the new value that is returned back into name, then the old value in name is overwritten (deleted). 26

  27. 6.4 The String Method length() We learned earlier this year that thelength ( ) method returns the number of characters in a String object. Example: System.out.print(“Enter a name: ”); String name = reader.nextLine(); intlength = name.length(); System.out.println(length); If nothing is entered from the keyboard, not even a blank space, and the return/enter key is pressed, then the variable length would hold the value zero. Therefore, we can also stop a while ( ! done ) loop if we use an if statement to test whether length holds the value zero as follows: if (name.length() == 0) done = true; 27

  28. 6.4 The String Method compareTo() intcompareTo (String other) <--- from the Java API The string method compareTo can be used to check to see if the contents of two String objects are equal, in other words to see if they contain exactly the same characters. Example: String name = reader.nextLine(); if (name.compareTo(“Bill”) == 0) System.out.println(“The names are equal.”); else System.out.println(“The names are NOT equal.”); If “Bill” is entered from the keyboard, then obviously the output will be: “The names are equal.” You cannot use: if (name == “Bill”) You cannot use the == operator to see if two strings contain exactly the same characters. == checks to see if two string variables point at the same string object, not that the contents of the two strings are equivalent. 28

  29. 6.4 Using compareTo() to Check Inequality You can also test to see if two strings are unequal by using != as follows: String name = reader.nextLine(); if (name.compareTo(“Bill”) != 0) System.out.println(“The name entered is not Bill.”); else System.out.println(“The name is Bill.”); You can see what the output would be depending on what is entered. 29

  30. Chapter 6 Section 5 Boolean Variables 30

  31. 6.5 Boolean Variables • Boolean variablescan hold a value of true or false. • A boolean is a primitive data typelike int, double, or char. Example: boolean startGame = true; if ( startGame ) // there is no reason to use(startGame == true) {// but you can … code that sets up and starts the game } Java will simply inspect the boolean value inside startGame and decide whether to run the code in the if branch based on its value. 31

  32. 6.5 Unintended Boolean Assignments It is easy to make the mistake of using =when you mean ==. This is another reason why you should NOT use … if (startGame == true) because if you accidentally coded … if (startGame = true)// this assigns true to the variable startGame When startGame holds the value false, then you have just given startGame the value true when you didn’t want to. This would give erroneous results in a program where you don’t want to execute the lines of code in the if statement when startGame is false. Eclipse and other compilers will not show a syntax or compile error when you do this! What is important to realize is that if (startGame = true)doesn’t give a syntax error in Java. Java lets you do this for boolean variables but not for other variables. See the demo program for this. 32

  33. 6.5 Boolean Variable Use Example boolean done = false; int sum = 0; // note that since done is false … ! false equals true and the loop runs while (! done) { System.out.print(“Enter a value to sum: ”); int x = reader.nextInt(); sum += x; reader.nextLine(); // consume newline character System.out.print (“Type Y to continue or N to stop (Y/N): ”); String ans = reader.nextLine(); if ( ! (ans.compareTo(“Y”) == 0) ) // if ans is not equal to Y stop. done = true;// while (! true) will stop the loop since ! true = false } Note: when checking to see if two strings are equal, we can’t use ==. We must call the compareTo() method of the String class. 33

  34. 6.5 Compound Boolean Example Assume factory company XYZ gives two tests to prospective employees to see if they are qualified for any of three levels of positions. The company has jobs available in these areas: managerial, supervisory, and line worker. For a person to qualify for a management level position, they must score above 90 on both tests. For a person to qualify for a supervisory level position, they must score above 90 on at least one of the tests. For a person to qualify for a line worker level position, they must score above 70 on at least one of the tests and they must not score below 50 on either one of the tests. 34

  35. 6.5 Compound Boolean Example If score1 and score2 are two variables that hold the results of the two tests for a prospective employee, then how could we write the code using an if statement to properly test the values of both scores so it can be determined what positions they are qualified for? 35

  36. 6.5 Compound Boolean Example If score1 and score2 are two variables that hold the results of the two tests for a prospective employee, then how could we write the code using an if statement to properly test the values of both scores so it can be determined what positions they are qualified for? if ( score1 >= 90 && score2 >= 90) System.out.println(“Qualified to be a Manager.”); if ( score1 >= 90 || score2 >= 90) System.out.println(“Qualified to be a Supervisor.”); if ( (score1 >= 70 || score2 >= 70) && ! (score1 < 50 || score2 < 50)) System.out.println(“Qualified to be a Line Worker.”); 36

  37. 6.5 Priority of Logical Operators You can use parentheses with complex expressions as seen on the last slide. Obviously, expressions in parentheses are evaluated first. In the expression below what is executed first? the && or the ! ??? if ( (score1 >= 70 || score2 >= 70) &&! (score1 < 50 || score2 < 50)) System.out.println(“Qualified to be a Line Worker.”); 37

  38. 6.5 Priority of Logical Operators You can use parentheses with complex expressions as seen previously. Obviously, expressions in parentheses are evaluated first. In the expression below what is executed first? the && or the ! ??? Answer:the ! (Not) if ( (score1 >= 70 || score2 >= 70) &&! (score1 < 50 || score2 < 50)) System.out.println(“Qualified to be a Line Worker.”); 38

  39. Scanner reader = new Scanner (System.in); System.out.print(“Enter the first test score: ”); int score1 = reader.nextInt(); System.out.print(“Enter the second test score: ”); int score2 = reader.nextInt(); if ( score1 >= 90 && score2 >= 90) System.out.println(“Qualified to be a Manager.”); if ( score1 >= 90 || score2 >= 90) System.out.println(“Qualified to be a Supervisor.”); if ( (score1 >= 70 || score2 >= 70) && ! (score1 < 50 || score2 < 50)) System.out.println(“Qualified to be a Line Worker.”); 6.5 Code Without Boolean Variables So let’s review the code again and see how it might be made better by using boolean variables. 39

  40. 6.5 Code Without Boolean Variables The last if statement on the previous slide allows us to give a great example of DeMorgan’s Law. The final part of the boolean condition below …. if ( (score1 >= 70 || score2 >= 70) && ! (score1 < 50 || score2 < 50)) System.out.println(“Qualified to be a Line Worker.”); ! (score1 < 50 || score2 < 50)) can also be written as … (score1 >= 50 && score2 >= 50)) 40

  41. 6.5 Code With Boolean Variables By using boolean variables, we can make the code much easier to read and understand, plus the variables may be used later on in different lines of code for other purposes if desired. However, it requires a little more coding. We need to declare some boolean variables and then give them values. (See next two slides) 41

  42. 6.5 Code With Boolean Variables • boolean bothHigh, atLeastOneHigh, • atLeastOneModerate, noLow; • ….. // input code as before • bothHigh = (score1 >= 90 && score2 >= 90); • atLeastOneHigh = (score1 >= 90 || score2 >= 90); • atLeastOneModerate = (score1 >= 70 || score2 >= 70); • noLow = ! (score1 < 50 || score2 < 50); • Any of the expressions on the right can be changed if necessary without changing any other code and the program will work as intended. For example, we might want to change the 50s to 60, the 70s to 80, and the 90s to 95. Now let’s substitute on the next slide 42

  43. 6.5 Code With Boolean Variables • Look how nice and readable the code becomes when we use the boolean variables. • if (bothHigh) • System.out.println(“Qualified to be a Manager.”); • if (atLeastOneHigh ) • System.out.println(“Qualified to be a Supervisor.”); • if (atLeastOneModerate && noLow ) • System.out.println(“Qualified to be a Clerk.”); 43

  44. 6.5 Second Example of Boolean Variables String day = reader.nextLine(); booleanweekday = day.compareTo(“Monday”) == 0 || day.compareTo(“Tuesday”) == 0 || day.compareTo(“Wednesday”) == 0 || day.compareTo(“Thursday”) == 0 || day.compareTo(“Friday”) == 0; if (weekday ) System.out.println(“The day is a weekday”); Code similar to this will be used on the Birthday Month program. 44

  45. 6.5 Precedence Rules for Logical Operators • Don’t forget the precedence rules for Logical Operators • ! has the highest precedence & the same precedence as the other unary operators plus and minus … + -. • && and || only have higher precedence than the assignment operators. • && has higher precedence than ||. 45

  46. 6.5 Precedence Rules for Java Operators 46

  47. 6.5 Invalid Conjunction Code Don’t forget … in algebra, we might write a conjunction as: 0 < x < 20 but we cannot do this in Java We cannot do that in Java, C++, or most other languages. We must write a compound boolean expression as follows: (x > 0) && (x < 20) Note the convention is to place x first in both simple boolean expressions. You should practice doing it this way. 47

  48. Notice how the boolean variable done is used to start and end the loop appropriately. This loop continues until the user enters an 8 letter word. boolean done = false; while ( ! done ) { System.out.print("Enter a word that you think has 8 letters: "); String word = reader.nextLine(); if (word.length() == 8) { System.out.println("The word " + word + " has 8 letters in it. This loop is over."); done = true; } else { System.out.println("The word " + word + " does NOT have 8 letters in it."); System.out.println(); } } 6.5 Using Boolean Variables to Control Loops 48

  49. Chapter 6 Section 6 Nested For and While Loops 49

  50. 6.6 Using Loop Control Variables i and j It has been traditional for over 50 years to use i, j, and k as loop control variables. This stems from the fact that programmers might have more than one loop in a program and you couldn’t use a variable multiple times like modern languages. So programmers would always use i for their first loop control variable, j for their second loop lcv, and k for their third loop lcv, etc. They also liked using one letter loop control variables, because it cut down on typing, especially when punch cards were used. It turns out we will use I and j for loop control variables when we have nested loops. You’ll see shortly. 50

More Related