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 Penny guessing game I weighed a pound of pennies and found there was exactly 160. 160 is an integer. int exact = 160; But nothing stops me from changing it. It is also a constant that I never want to change. final int exact = 160; So let’s write a guessing game.

3 Penny guessing game import java.util.Scanner;
public class GuessingGame { public static void main ( String s[] ) { final int exact = 160; Scanner in = new Scanner( System.in ); //prompt for a guess System.out.print( “Guess the # of pennies in a pound. “ ); int guess = in.nextInt(); //check the answer if (guess==exact) System.out.println( “You are correct!” ); else System.out.println( “Nope.” ); in.close(); }

4 Penny guessing game … //check the answer if (guess==exact)
System.out.println( “You are correct!” ); else System.out.println( “Nope.” ); == is a boolean (true or false) operator It tests for equality. A==B is a boolean expression The result of this expression is either true or false.

5 Branching with an if-else Statement
An if-else statement chooses between two alternative statements based on the value of a Boolean expression if (Boolean_Expression) Yes_Statement else No_Statement The Boolean_Expression must be enclosed in parentheses If the Boolean_Expression is true, then the Yes_Statement is executed If the Boolean_Expression is false, then the No_Statement is executed

6 Pay attention to the indentation!!
if (guess==exact) System.out.println( “You are correct!” ); else System.out.println( “Nope.” );

7 Penny guessing game Let’s accept a guess that’s 160 ± 10%.

8 Penny guessing game Let’s accept a guess that’s 160 ± 10%.
So let’s define two more constants – the minimum and the maximum that we’ll accept.

9 Penny guessing game Let’s accept a guess that’s 160 ± 10%.
So let’s define two more constants – the minimum and the maximum that we’ll accept. final int exact = 160; final int max = exact + exact/10; final int min = exact - exact/10;

10 Penny guessing game Now we must change the check to include the acceptable range. //check the answer if (guess==exact) System.out.println( “You are correct!” ); else System.out.println( “Nope.” );

11 Penny guessing game Now we must change the check to include the acceptable range. //check the answer if (guess==exact) System.out.println( “You are correct!” ); else if (guess<min) System.out.println( “Nope.” ); else if (guess>max) else System.out.println( “Close enough.” );

12 Multiway if-else Statement
if (Boolean_Expression) Statement_1 else if (Boolean_Expression) Statement_2 else if (Boolean_Expression_n) Statement_n else Statement_For_All_Other_Possibilities . . .

13 Comparison operators Equality x==y Inequality x != y
Less than x < y Greater than x > y Less than or equal x <= y Greater than or equal x >= y

14 Penny guessing game … //check the answer if (guess==exact)
System.out.println( “You are correct!” ); else if (guess<min) System.out.println( “Nope.” ); else if (guess>max) else System.out.println( “Close enough.” ); Note that we write “Nope.” if the first boolean expression or the second boolean expression is true. Wouldn’t it be nice if we had a boolean operator for or?

15 Penny guessing game … //check the answer if (guess==exact)
System.out.println( “You are correct!” ); else if (guess<min || guess>max) System.out.println( “Nope.” ); else System.out.println( “Close enough.” ); boolean operator for OR

16 Logical operators (AND, OR, NOT)
Logical “not”: ! if (!phone.equals(“ ”) System.out.println(“Sorry, wrong number!”); Logical “and”: && if (temp >= 97 && temp <=99) System.out.println(“Patient is healthy”); Logical “or”: || if (months >= 3 || miles >= 3000) System.out.println(“Change your oil”);

17 Penny guessing game … //check the answer if (guess==exact)
System.out.println( “You are correct!” ); else if (guess>=min && guess<=max) System.out.println( “Close enough.” ); else System.out.println( “Nope.” ); boolean operator for AND

18 Building Boolean Expressions
When two Boolean expressions are combined using the "and" (&&) operator, the entire expression is true provided both expressions are true Otherwise the expression is false When two Boolean expressions are combined using the "or" (||) operator, the entire expression is true as long as one of the expressions is true The expression is false only if both expressions are false Any Boolean expression can be negated using the ! operator Place the expression in parentheses and place the ! operator in front of it Unlike mathematical notation, strings of inequalities must be joined by && Use (min < result) && (result < max) rather than min < result < max

19 Truth Tables

20 Comparing strings == doesn’t work (as you expect) so please don’t use it. Example: String city1 = “Philadelphia”; String city2 = “Phoenix”; I want to say: if (city1==city2) but I can’t!

21 Comparing strings Use .equals() instead:
if (city1.equals(city2)) … .equals() is case sensitive (i.e., NYC is not the same as NyC) .equalsIgnoreCase() is not case sensitive if (city1.equalsIgnoreCase(city2)) …

22 Omitting the else Part The else part may be omitted to obtain what is often called an if statement if (Boolean_Expression) Yes_Statement If the Boolean_Expression is true, then the Yes_Statement is executed Otherwise, nothing happens, and the program goes on to the next statement if (weight > ideal) calorieIntake = calorieIntake – 500; System.out.println(“This is the next statement”);

23 If-else and blocks Sometimes we wish to execute more than one statement for an if statement. if (x==y) singleStatement; if (x==y) { statement1; statement2; statementn; } { s1; s2; sn; } This is called a block.

24 Compound Statements Each Yes_Statement and No_Statement branch of an if-else can be a made up of a single statement or many statements Compound Statement: A branch statement that is made up of a list of statements A compound statement must always be enclosed in a pair of braces ({ }) A compound statement can be used anywhere that a single statement can be used

25 Compound Statements if (myScore > your Score) {
System.out.println("I win!"); wager = wager + 100; } else System.out.println ("I wish these were golf scores."); wager = 0;

26 if-else form in general
if (conds1) one-statement; or { block-of-statements } else if (conds2) else if (condsn) else

27 Evaluating Boolean Expressions
Even though Boolean expressions are used to control branch and loop statements, Boolean expressions can exist independently as well A Boolean variable can be given the value of a Boolean expression by using an assignment statement A Boolean expression can be evaluated in the same way that an arithmetic expression is evaluated The only difference is that arithmetic expressions produce a number as a result, while Boolean expressions produce either true or false as their result boolean madeIt = (time < limit) && (limit < max);

28 Boolean type and variables
boolean b; b = true; b = false; int x = 10; int y = 9; b = (x==y); // b = false b = (x>y); // b = true

29 Boolean type and variables
boolean b; b = true; b = !b; // b = false int count = 8; b = !( ( count < 3) || (count > 7) ) //true or false?

30 Boolean I/O boolean answer = in.nextBoolean();
You must type in either true or false and hit return (enter). System.out.writeln( answer ); //works as too

31 Problem Write a program that inputs dates in the form month/day/year (ex. 6/13/1988) and outputs the date in the form: 13-jun-1988. Note: Days are in the range Months are in the range

32 Short-Circuit and Complete Evaluation
Java can take a shortcut when the evaluation of the first part of a Boolean expression produces a result that evaluation of the second part cannot change This is called short-circuit evaluation or lazy evaluation For example, when evaluating two Boolean subexpressions joined by &&, if the first subexpression evaluates to false, then the entire expression will evaluate to false, no matter the value of the second subexpression In like manner, when evaluating two Boolean subexpressions joined by ||, if the first subexpression evaluates to true, then the entire expression will evaluate to true

33 Short-Circuit and Complete Evaluation
There are times when using short-circuit evaluation can prevent a runtime error In the following example, if the number of kids is equal to zero, then the second subexpression will not be evaluated, thus preventing a divide by zero error Note that reversing the order of the subexpressions will not prevent this if ((kids !=0) && ((toys/kids) >=2)) . . . Sometimes it is preferable to always evaluate both expressions, i.e., request complete evaluation In this case, use the & and | operators instead of && and ||

34 Precedence and Associativity Rules
Boolean and arithmetic expressions need not be fully parenthesized If some or all of the parentheses are omitted, Java will follow precedence and associativity rules (summarized in the following table) to determine the order of operations If one operator occurs higher in the table than another, it has higher precedence, and is grouped with its operands before the operator of lower precedence If two operators have the same precedence, then associativity rules determine which is grouped first

35 Precedence and Associativity Rules

36 Evaluating Expressions
In general, parentheses in an expression help to document the programmer's intent Instead of relying on precedence and associativity rules, it is best to include most parentheses, except where the intended meaning is obvious


Download ppt "Boolean expressions and if-else statements"

Similar presentations


Ads by Google