Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Conditions, logical expressions, and selection Introduction to control structures.

Similar presentations


Presentation on theme: "1 Conditions, logical expressions, and selection Introduction to control structures."— Presentation transcript:

1 1 Conditions, logical expressions, and selection Introduction to control structures

2 2 Flow of control In a program, statements execute in a particular order sequentiallyBy default, statements are executed sequentially: –One after another, from top to bottom –One at a time –Exactly once control structuresThis sequential flow of control can be altered through the use of control structures

3 3 Control structures There are two general types of control structures: –Selection (aka branching) structures: cause flow of control to take, or not take, a particular direction –Repetition (aka iteration, looping) structures: cause a set of statements to execute several times Both of these type of structures depend on the evaluation of logical expressions

4 4 Logical expressions booleanLogical expressions evaluate to true or false; the result of a logical expression is always a value of data type boolean Most logical expressions use relational and logical operators In Java the form of a simple logical expression is: Operand1operatorOperand2 –The operands can be simple or compound expressions of any type –The operator is a relational operator

5 5 Relational operators The relational operators in Java include: <: is less than <=:is less than or equal to ==:equals >:is greater than >=:is greater than or equal to !=:does not equal

6 6 Logical expression examples Suppose you had the following declarations: int x = 3, y = 7; Then the following expressions would have the values indicated: x > y // (false) y >= x // (true) x != y // (true) (x > y) == true // (false) ((y >= x) == (x != y)) // true x = y // value is 7; not a logical expression

7 7 Logical expressions & floating-point numbers In general, it isn’t a good idea to compare two floating-point numbers for equality This is because floats and doubles always represent approximations of values, and, although 2 equals 2, 2.000000000003 does not equal 2.00000000000019 A better method for comparing floating- point numbers involves deciding how close is close enough to equal

8 8 Comparing floating-point numbers for equality The expression below assumes numbers are close enough to equal if they are within 1/100,000,000 of one another: Math.abs(a-b) < 1.0e-10 Notes: –“Math.abs” is the absolute value function –The expression is true if the absolute value of the difference between variable a and b is less than.0000000001

9 9 Comparing Objects When comparing primitive-type variables, constants, and values, the relational operators are adequate When comparing objects, we can use the relational operators, but they don’t mean the same thing they mean with the primitive types

10 10 Comparing Objects Recall that, when we declare an object, the identifier in the declaration doesn’t contain an object until we initialize it by calling the object’s constructor (using the new operator) When we invoke the constructor, a new object is created, and its memory address is associated with the identifier from the declaration

11 11 Example 1 JFrame w1, w2;// declares 2 window objects w1 = new JFrame();// creates a new window w2 = new JFrame();// creates a 2 nd window In the code above, w1 and w2 are assigned the addresses of 2 different window objects Although the two new windows are identical, it is intuitively obvious that they are not the same window What happens if we compare them for equality?

12 12 Example 1 continued The expression w1 == w2 will evaluate to false The reason for this is, we are not really comparing the two window objects (which should be identical) Instead, we’re comparing their addresses – since each has its own address, and each address is unique, the comparison evaluates false

13 13 Example 2 JFrame w1, w2;// declares 2 window objects w1 = new JFrame();// creates new object w2 = w1;// assigns address of object to 2 nd variable In this example, only one window object has been created The expression w1 == w2 evaluates to true, because both object variables refer to the same object

14 14 Comparing objects: method equals Because the relational operator == compares only the addresses of objects, many objects have a member method to compare object contents for equality The equals method performs a comparison that depends on its definition within the class For example, for String objects, the equals method performs a letter-by-letter comparison between two Strings, evaluating true if the Strings’ contents are identical

15 15 Example 3: comparing Strings String s1, s2; s1 = new String (“a string”); s2 = new String (“a string”); The expression s1 == s2 evaluates false The expressions s1.equals(s2) and s2.equals(s1) evaluate true

16 16 More String comparison methods The equals method returns true if the calling object and its argument are identical in both spelling and case A second method, equalsIgnoreCase, can be used to compare Strings for spelling only; for example: String s1 = new String (“hello”); String s2 = new String (“HELLO”); –s1.equals(s2) returns false –s1.equalsIgnoreCase(s2) returns true

17 17 More String comparison methods The String class includes two comparison methods besides equals and equalsIgnoreCase: –compareTo is similar to equals; it is case- sensitive –compareToIgnoreCase, as the name implies, ignores case

18 18 String compare methods Both compare methods work as follows: –if the calling object is less than the argument, the method returns a negative number –if the calling object is greater than the argument, the method returns a positive number (greater than 0) –if the Strings are equal, the method returns 0 In this context, “less than” and “greater than” refer to alphabetical order – so, for example, “abc” is less than “bcd” because “a” comes before (is less than) “b”

19 19 String compare methods If the case-sensitive compare method is used, then if two Strings have the same spelling but one contains capital letters, the one with the capital letters will evaluate as less than the one with equivalent lowercase letters So, for example, “Hello” is less than “hello”

20 20 Exception to the rules One important point about Strings – they can sometimes act like primitive objects If a String is instantiated without the new operator, as in the example below: String s1 = “no news is good news”; String s2 = “no news is good news”; –then the expression s1 == s2 evaluates true –this is because, if the same String literal is assigned without “new” to 2 different objects, both objects refer to the same memory location –however, if s1 then gets assigned a different String literal, the expression s1 == s2 will be false, because now s2 refers to the original address, but s1 now refers to a new address

21 21 Logical operators Three operators in Java can be used to form compound logical expressions (expressions that combine simple logical, or relational expressions) They are: && - logical and || - logical or ! – logical not

22 22 Logical operators Logical and (&&) combines two expressions; if both sub-expressions are true, then the compound expression is true – otherwise, the compound expression is false Logical or also combines two expressions; the compound expression is true if one or both sub- expressions is true, false otherwise Logical not reverses the truth value of an expression; if the original expression was true, not makes it false, and vice versa

23 23 Truth table Graphical display of relationships between truth values of propositions Shows all possible values of propositions, or combinations of propositions Suppose p represents an expression; then the truth table for !p is as show below: p!p T F F T

24 24 Truth table for p && q pq p && q TT T TF F FT F FF F Suppose p and q represent two logical sub-expressions; then the compound expression p && q has the following truth table:

25 25 Truth table for p || q pq p || q TT T TF T FT T FF F Suppose p and q represent two logical sub-expressions; then the compound expression p || q has the following truth table:

26 26 OperatorMeaning Associativity ! NOTRight *, /, % Multiplication, Division, Modulus Left +, - Addition, SubtractionLeft < Less thanLeft <= Less than or equal toLeft > Greater thanLeft >= Greater than or equal toLeft == Is equal toLeft != Is not equal to Left && ANDLeft || OR Left = AssignmentRight Partial listing of operator precedence in Java – more complete list, p 241 of Wu

27 27 int age ; boolean isSenior, hasFever ; double temperature ; age = 20; temperature = 102.0; isSenior = (age >= 55) ; hasFever = (temperature > 98.6) ; EXPRESSIONVALUE isSenior && hasFever false isSenior || hasFever true ! isSeniortrue ! hasFeverfalse

28 28 What is the value? int age, height; age = 25; height = 70; EXPRESSIONVALUE ! (age < 10) ? ! (height > 60) ?

29 29 “Short-Circuit” Evaluation Java uses short circuit evaluation of logical expressions This means logical expressions are evaluated left to right and evaluation stops as soon as the final truth value can be determined

30 30 Short-Circuit Example int age, height; age = 25; height = 70; EXPRESSION (age > 50) && (height > 60) false Evaluation can stop now because result of && is only true when both sides are true. It is already determined that the entire expression will be false.

31 31 More Short-Circuiting int age, height; age = 25; height = 70; EXPRESSION (height > 60) || (age > 40) true Evaluation can stop now because result of || is true if one side is true. It is already determined that the entire expression will be true.

32 32 What happens? int age, weight; age = 25; weight = 145; EXPRESSION (weight = 20) true Must still be evaluated because truth value of entire expression is not yet known. Why? Result of && is only true if both sides are true.

33 33 What happens? int age, height; age = 25; height = 70; EXPRESSION ! (height > 60) || (age > 50) true false Does this part need to be evaluated?

34 34 Write an expression for each 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

35 35 Use Precedence Chart int number ; float x ; number ! = 0 && x < 1 / number / has highest priority < next priority != next priority && next priority What happens if Number has value 0?

36 36 Short-Circuit Benefits one boolean expression can be placed first to “guard” a potentially unsafe operation in a second boolean expression Time is saved in evaluation of complex expressions using operators || and &&

37 37 Our Example Revisited int number; float x; ( number ! = 0) && ( x < 1 / number ) is evaluated first and has value false Because operator is &&, the entire expression will have value false. Due to short-circuiting the right side is not evaluated in Java.

38 38 Summary of logical expressions in Java “boolean expression” means an expression whose value is true or false An expression is any valid combination of operators and operands Use of parentheses is encouraged; otherwise, use precedence chart to determine order

39 39 Logical expressions & program control Relational expressions can be used to control the flow of logic in a program Depending on the truth value of an expression, a program can be made to perform one task or another (but not both) A control structure that fits this description is called a selection structure

40 40 Selection & Java if statementIn Java, a simple selection structure is created using an if statement, which has the following syntax: if (relational expression) { statement(s); } If only one statement follows the if clause, the curly brackets are unnecessary

41 41 Payroll example in Java double otpay = 0.0;// overtime pay – time and 1/2 if (hours > 40) { otpay = hours – 40; otpay = otpay * wage * 1.5; } pay = otpay + hours * wage;

42 42 What can go wrong here? float average;// average price float total;// sum of prices // entered int howMany;// number of // prices entered... average = total / howMany;

43 43 Improved Version float average,// average price total;// sum of prices entered int howMany;// number of prices entered … if ( howMany > 0 ) { average = total / howMany; }

44 44 The if-else control structure In the previous examples, a set of statements either executed, or didn’t, based on the truth value of an expression In many situations, two options make more sense – one set of statements executes if the condition is true, while the other executes if it is false This slightly more complicated version is called an if/else structure

45 45 If/else in Java Basic syntax is: if (relational expression) { statement(s); } else { statement(s) }

46 46 Example Read an int value from the keyboard If value is less than 0, print its square If value is greater than 0, print its square root

47 47 Program logic in Java String s; double value; s=JOptionPane.showInputDialog(null, “Enter a number”); value = Double.parseDouble(s); if (value < 0) JOptionPane.showMessageDialog(null, “Value squared is ” + Math.pow(value, 2.0)); else JOptionPane.showMessageDialog(null, “Square root of value is: ” + Math.sqrt(value));

48 48 Use of blocks recommended if ( Expression ) { } else { } “if clause” “else clause”

49 49 What output? and Why? boolean code; code = false; if ( ! code ) cout << “Yesterday”; else cout << “Tomorrow”;

50 50 int carDoors, driverAge ; double premium, monthlyPayment ;... if ( (carDoors == 4 ) && (driverAge > 24) ) { System.out.println(“LOW RISK”) ; premium = 650.00 ; } else { System.out.println(“HIGH RISK”) ; premium = 1200.00 ; } monthlyPayment = premium / 12.0 + 5.00 ;

51 51 What happens if you omit braces? if ( (carDoors == 4 ) && (driverAge > 24) ) System.out.println(“LOW RISK”) ; premium = 650.00 ; else System.out.println(“HIGH RISK”) ; premium = 1200.00 ; monthlyPayment = premium / 12.0 + 5.00 ; COMPILE ERROR OCCURS. The “if clause” is the single statement following the if.

52 52 Adding braces: if ( (carDoors == 4 ) && (driverAge > 24) ) { System.out.println(“LOW RISK”) ; premium = 650.00 ; } else System.out.println(“HIGH RISK”) ; premium = 1200.00 ; monthlyPayment = premium / 12.0 + 5.00 ; PROGRAM COMPILES. Is it correct?

53 53 Write If or If-Else for each If taxCode is 1, increase price by adding taxRate times price to it. If code has value 1, read values for income and taxRate from the keyboard, and calculate and display taxDue as their product. If A is strictly between 0 and 5, set B equal to 1/A, otherwise set B equal to A.

54 54 The ternary operator As an alternative to the simple if/else structure, Java offers a shortcut: the ternary operator “ternary” refers to the fact that the operator takes three operands The symbol for the ternary operator is ?:

55 55 The ternary operator The ternary operator takes the following form: expression1 ? expression2 : expression3 –if expression1 is true, expression2 is evaluated; if expression 1 is false, expression3 is evaluated –the result of the entire ?: expression is the value of whichever expression (2 or 3) was evaluated

56 56 Example code using ?: (value < 0) ? value = Math.pow(value, 2.0) : value = Math.sqrt(value); Note there is no semicolon after the first expression. That is because this is not the end of the instruction. Instead, the colon indicates the end of the “if” clause.

57 57 Conditions, logical expressions, and selection Introduction to control structures


Download ppt "1 Conditions, logical expressions, and selection Introduction to control structures."

Similar presentations


Ads by Google