Presentation is loading. Please wait.

Presentation is loading. Please wait.

Boolean Expressions And if…else Statements.

Similar presentations


Presentation on theme: "Boolean Expressions And if…else Statements."— Presentation transcript:

1 Boolean Expressions And if…else Statements

2 Objectives: Learn about the boolean data type
Learn the syntax for if-else statements Learn about relational and logical operators, and short-circuit evaluation Learn when to use nested if-else statements and if-else-if sequences Another objective is to discuss team development and illustrate software reusability in the context of a simple but realistic case study, the Craps applet.

3 boolean Data Type George Boole (1815 - 1864)
boolean variables may have only two values, true or false. You define boolean fields or boolean local variables the same way as other variables. boolean true false There is no point, really, in using boolean symbolic constants because you can just use true and false in the code. George Boole was a British mathematician who studied properties of formal logic. private boolean hasMiddleName; boolean isRolling = false; Reserved words

4 Relational Operators <, >, <=, >=, ==, !=
<, >, <=, >=, ==, != is equal to is NOT equal to = is for assignment, == is for comparison. Apply only to primitive data types.

5 Boolean Expressions (cont’d)
Do not use == or != with doubles because they may have rounding errors double x = 7.0; double y = 3.5; if (x / y == 2.0) ... <= and >= are OK with doubles, because in this type of comparison the program usually doesn’t care about the situation when the numbers are exactly equal. May be false!

6 Logical Operators &&, ||, ! and or not
&&, ||, ! and or Logical operators parallel those in formal logic. not

7 Logical Operators (cont’d)
( condition1 && condition2 ) is true if and only if both condition1 and condition2 are true ( condition1 || condition2 ) is true if and only if condition1 or condition2 (or both) are true !condition1 is true if and only if condition1 is false Note that || is inclusive or: either one or the other or both.

8 Boolean Expressions a < 5 b == 6 c != 6
A Boolean expression evaluates to either true or false. Boolean expressions are written using boolean variables and relational and logical operators. You can assign the result of an arithmetic expression to an int or double variable. Similarly, you can assign the result of a Boolean expression to a boolean variable. For example, rather than writing boolean exceedsLimit; if (x > limit) exceedsLimit = true; else exceedsLimit = false; you can write simply: boolean exceedsLimit = x > limit; a < 5 b == 6 c != 6 ch >= ‘a’ && ch <= ‘z’ x < 0 || y < 0

9 Short-Circuit Evaluation
if (condition1 && condition2) ... If condition1 is false, condition2 is not evaluated (the result is false anyway) if (condition1 || condition2) ... If condition1 is true, condition2 is not evaluated (the result is true anyway) Java has another set of operators, & (and), | (or), ~ (not), and ^ (xor). These are bitwise logical operators that work on bit patterns. Unfortunately, these can be also used with boolean variables. When applied to booleans, & and | do NOT follow the short-circuit evaluation rule. So be very careful to make sure you have && and ||. if ( x >= 0 && Math.sqrt (x) < 15.0) ... Always OK: won’t get to sqrt if x < 0

10 if Statement if ( <condition> ) { < statements > }
<condition> is a boolean expression! if ( <condition> ) { < statements > } When the if or else clause contains only one statement, the braces are optional, but it is safer to always keep them. With braces it is also easier to add a statement to an if or else clause.

11 if Statement (cont’d) if (inventory < 10) { <statements> }
In the if-else-if sequence, the second if-else is actually nested within the preceding else clause, but this layout is conventional and more readable. The sequence remains readable even if it is quite long.

12 if-else Statement if ( <condition> ) { < statements > }
< other statements > When the if or else clause contains only one statement, the braces are optional, but it is safer to always keep them. With braces it is also easier to add a statement to an if or else clause.

13 if-else Statement (cont’d)
if (inventory < 10) { < statements > } else < other statements > In the if-else-if sequence, the second if-else is actually nested within the preceding else clause, but this layout is conventional and more readable. The sequence remains readable even if it is quite long.

14 if-else-if Statement if ( <condition> ) { < statements > }
else if ( <condition> ) < other statements > else When the if or else clause contains only one statement, the braces are optional, but it is safer to always keep them. With braces it is also easier to add a statement to an if or else clause.

15 if-else-if Statement if (drinkSize == 32) { price = 1.39; }
else if (drinkSize == 16) price = 1.19; else // if 8 oz drink size price = 0.99; In the if-else-if sequence, the second if-else is actually nested within the preceding else clause, but this layout is conventional and more readable. The sequence remains readable even if it is quite long.

16 Nested if-else if ( <condition> ) { <statements> else }
If you nest if-else to more than two levels, it may be hard to read. Reconsider your design: perhaps you need helper methods that handle different cases.

17 Relational Operators (cont’d)
Be careful using == and != with objects (e.g., Strings): they compare references (addresses) rather than values (the contents) String cmd = console.readLine(); if ( cmd == "Help" ) ... In Java you have to always be aware when two variables refer to the same object and when to two different objects, perhaps with equal values. Wrong! (always false)

18 Relational Operators (cont’d)
Use the equals method to compare Strings: or String cmd = console.readLine(); if ( cmd.equals ("Help") ) ... The “value” may be defined differently for different types of objects. For strings, the value is the characters in the string; for “employees,” equals may mean the same social security number. A programmer defines the meaning of “equals” for the objects of his or her class. if ( "Help".equals (cmd) ) ...

19 Relational Operators (cont’d)
Use the == or != operator with strings and other objects when you want to know whether or not this is exactly the same object. Also use == or != to compare to null: Comparison to null works for all types of objects. String text = file.readLine(); if ( text != null ) ...

20 Ranks of Operators ! -(unary) ++ -- (cast) * / % + -
* / % < <= > >= == != && || Thus you can string several && with no parentheses: a && b && c. The rank of || is lower than &&, so a && b || c && d is the same as (a && b) || (c && d), but the expression is more readable with parentheses. Easier to read if ( ( ( year % 4 ) == 0 ) && ( month == 2 ) ) ... if ( year % 4 == 0 && month == 2 ) ...

21 Common if-else Errors if (...) ; { statements; ... } Extra semicolon
It is safer to always use braces in if-else if (...) statement1; statement2; ... if (...) statement1; else statement2; ... With the extra semicolon, the code will executed as follows: if (...) do nothing perform statements in braces (unconditionally) The second example of missing braces is known as a “dangling” else: the else clause actually pairs with the inner if, not the outer if as the programmer intended and as the indentation implied. Missing braces

22 How Does An if Statement Work?

23 How Does An if Statement Work?
country(25); public void country(int n) { if (n < 0) System.out.println(“France”); else if (n > 100) System.out.println(“England”); else System.out.println(“Germany”); }

24 How Does An if Statement Work?
public void country(int n) { if (n < 0) System.out.println(“France”); else if (n > 100) System.out.println(“England”); else System.out.println(“Germany”); }

25 How Does An if Statement Work?
public void country(int n) { if (n < 0) System.out.println(“France”); else if (n > 100) System.out.println(“England”); else System.out.println(“Germany”); } if (25 < 0)

26 How Does An if Statement Work?
public void country(int n) { if (n < 0) System.out.println(“France”); else if (n > 100) System.out.println(“England”); else System.out.println(“Germany”); }

27 How Does An if Statement Work?
public void country(int n) { if (n < 0) System.out.println(“France”); else if (n > 100) System.out.println(“England”); else System.out.println(“Germany”); } if (25 > 100)

28 How Does An if Statement Work?
public void country(int n) { if (n < 0) System.out.println(“France”); else if (n > 100) System.out.println(“England”); else System.out.println(“Germany”); }

29 How Does An if Statement Work?
public void country(int n) { if (n < 0) System.out.println(“France”); else if (n > 100) System.out.println(“England”); else System.out.println(“Germany”); }

30 How Does An if Statement Work?
public void country(int n) { if (n < 0) System.out.println(“France”); else if (n > 100) System.out.println(“England”); else System.out.println(“Germany”); }

31 How Does An if Statement Work?
country(125); public void country(int n) { if (n < 0) System.out.println(“France”); else if (n > 100) System.out.println(“England”); else System.out.println(“Germany”); }

32 How Does An if Statement Work?
public void country(int n) { if (n < 0) System.out.println(“France”); else if (n > 100) System.out.println(“England”); else System.out.println(“Germany”); }

33 How Does An if Statement Work?
public void country(int n) { if (n < 0) System.out.println(“France”); else if (n > 100) System.out.println(“England”); else System.out.println(“Germany”); } if (125 < 0)

34 How Does An if Statement Work?
public void country(int n) { if (n < 0) System.out.println(“France”); else if (n > 100) System.out.println(“England”); else System.out.println(“Germany”); }

35 How Does An if Statement Work?
public void country(int n) { if (n < 0) System.out.println(“France”); else if (n > 100) System.out.println(“England”); else System.out.println(“Germany”); } if (125 > 100)

36 How Does An if Statement Work?
public void country(int n) { if (n < 0) System.out.println(“France”); else if (n > 100) System.out.println(“England”); else System.out.println(“Germany”); }

37 How Does An if Statement Work?
public void country(int n) { if (n < 0) System.out.println(“France”); else if (n > 100) System.out.println(“England”); else System.out.println(“Germany”); }

38 Top-Down Design

39 Top-Down Design (cont’d)
Start JCreator. Open the file “Lab06.java”. Lab07.java is in your Lab06 folder.

40 Top-Down Design (cont’d)
Write a program that calculate the cost of a soft drink and a box of popcorn at the movies. The prices for each item are as follows: Item Small (8 oz) Medium (16 oz) Large (32 oz) Drinks Popcorn Read the size of the soft drink and popcorn from the keyboard and output the total cost.

41 Top-Down Design (cont’d)
The “big problem” is defined in the main method.

42 Top-Down Design (cont’d)
import java.text.DecimalFormat; import java.util.Scanner; public class Lab06 { public static void main(String[] args) Lab06 lab = new Lab06( ); lab.input(); // Enter data from the kybd lab.process(); // Calculate the cost lab.output( ); // Display output }

43 Top-Down Design (cont’d)
What fields are required to solve the problem? NOTE: Fields should be the values we will read from the keyboard and the values for which we are solving. String sizeOfPopcorn; int sizeOfDrink; double totalCost;

44 Top-Down Design (cont’d)
import java.text.DecimalFormat; import java.util.Scanner; public class Lab06 { private String sizeOfPopcorn; private int sizeOfDrink; private double totalCost; public static void main(String[] args) Lab06 lab = new Lab06( ); lab.input(); // Enter data from the kybd lab.process(); // Calculate the total cost lab.output( ); // Display output }

45 Top-Down Design (cont’d)
input(), process() and output( ) are the smaller parts of the problem.

46 Top-Down Design (cont’d)
input( )

47 Top-Down Design (cont’d) Input
Read the size of the popcorn and the size of the soft drink from the keyboard. Precede each value entered with a prompt. Enter the size of the popcorn <Small, Medium, Large>: medium

48 Top-Down Design (cont’d) Input
Read the size of the popcorn and the size of the soft drink from the keyboard. Precede each value entered with a prompt. Enter the size of the popcorn <Small, Medium, Large>: medium Enter the size of the soft drink <8, 16, 32>: 32

49 Top-Down Design (cont’d)
public void input() { Scanner reader = new Scanner(System.in); System.out.print("Enter the size of the popcorn <Small, Medium, Large>: "); sizeOfPopcorn = reader.next(); System.out.print("Enter the size of the soft drink <8, 16, 32>: "); sizeOfDrink = reader.nextInt(); }

50 Top-Down Design (cont’d)
output( )

51 Top-Down Design (cont’d) Output
Write a statement that displays the cost of the popcorn and softdrink. A <sizeOfPopcorn> box of popcorn and a <sizeOfDrink> oz soft drink costs <totalCost>.

52 Top-Down Design (cont’d)
public void output() { DecimalFormat df = new DecimalFormat("$#.00"); System.out.println("A " + sizeOfPopcorn + " box of popcorn and a " + sizeOfDrink + " oz soft drink costs " + df.format(totalCost)); }

53 Top-Down Design (cont’d)
process( )

54 Top-Down Design (cont’d) Process
Calculate the total cost of the popcorn and soft drink.

55 Top-Down Design (cont’d)
public void process() { }

56 Top-Down Design (cont’d)
public void process() { if (sizeOfPopcorn.equalsIgnoreCase("SMALL")) totalCost = 3.0; }

57 Top-Down Design (cont’d)
public void process() { if (sizeOfPopcorn.equalsIgnoreCase("SMALL")) totalCost = 3.0; else if (sizeOfPopcorn.equalsIgnoreCase("MEDIUM")) totalCost = 3.50; }

58 Top-Down Design (cont’d)
public void process() { if (sizeOfPopcorn.equalsIgnoreCase("SMALL")) totalCost = 3.0; else if (sizeOfPopcorn.equalsIgnoreCase("MEDIUM")) totalCost = 3.50; else totalCost = 4.25; }

59 Top-Down Design (cont’d)
public void process() { if (sizeOfPopcorn.equalsIgnoreCase("SMALL")) totalCost = 3.0; else if (sizeOfPopcorn.equalsIgnoreCase("MEDIUM")) totalCost = 3.50; else totalCost = 4.25; if (sizeOfDrink == 8) totalCost += 2.75; }

60 Top-Down Design (cont’d)
public void process() { if (sizeOfPopcorn.equalsIgnoreCase("SMALL")) totalCost = 3.0; else if (sizeOfPopcorn.equalsIgnoreCase("MEDIUM")) totalCost = 3.50; else totalCost = 4.25; if (sizeOfDrink == 8) totalCost += 2.75; else if (sizeOfDrink == 16) totalCost += 3.25; }

61 Top-Down Design (cont’d)
public void process() { if (sizeOfPopcorn.equalsIgnoreCase("SMALL")) totalCost = 3.0; else if (sizeOfPopcorn.equalsIgnoreCase("MEDIUM")) totalCost = 3.50; else totalCost = 4.25; if (sizeOfDrink == 8) totalCost += 2.75; else if (sizeOfDrink == 16) totalCost += 3.25; totalCost += 4.0; }

62 Top-Down Design (cont’d)
Run The Program: (1st Run) Enter the size of the popcorn <Small, Medium, Large>: small Enter the size of the soft drink <8, 16, 32>: 16 A small box of popcorn and a 16 oz soft drink costs $6.25

63 Top-Down Design (cont’d)
Run The Program: (2st Run) Enter the size of the popcorn <Small, Medium, Large>: Large Enter the size of the soft drink <8, 16, 32>: 32 A small box of popcorn and a 16 oz soft drink costs $8.25

64 Questions?

65 Begin Lab 06


Download ppt "Boolean Expressions And if…else Statements."

Similar presentations


Ads by Google