Boolean expressions and if-else statements

Slides:



Advertisements
Similar presentations
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
Advertisements

Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control if-else and switch statements.
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 4 Making Decisions
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control if-else and switch statements.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
True or False Unit 3 Lesson 7 Building Blocks of Decision Making With Additions & Modifications by Mr. Dave Clausen True or False.
Chapter 3 Flow of Control Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Flow of Control Java Programming Mrs. C. Furman January 5, 2009.
Boolean expressions Conditional statements and expressions.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Edited by JJ Shepherd
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control.
Flow of Control Module 3. Objectives Use Java branching statements Compare values of primitive types Compare objects such as strings Use the primitive.
Chapter 3 Flow of Control Slides prepared by Rose Williams, Binghamton University Kenrick Mock University of Alaska Anchorage Copyright © 2008 Pearson.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
1 Chapter 3 Selections. 2 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Copyright 2003 Scott/Jones Publishing Making Decisions.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Chapter Making Decisions 4. Relational Operators 4.1.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Chapter 3 Boolean Expressions Section 3.2 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control.
Flow of Control Joe McCarthy CSS 161: Fundamentals of Computing1.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
ICS102 Lecture 8 : Boolean Expressions King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science.
(Java Looping and Conditional Statements). Flow of control Sequential Executes instructions in order Method Calls Transfer control to the methods, then.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Switch statement.
CompSci 230 S Programming Techniques
Chapter 3 Flow of Control
Chapter 3 Flow of Control
Control Structures I Chapter 3
Lecture 3 Java Operators.
Selection (also known as Branching) Jumail Bin Taliba by
Selections Java.
More important details More fun Part 3
Chapter 4: Making Decisions.
CMPT 201 if-else statement
CHAPTER 4 Selection CSEG1003 Introduction to Computing
Debugging and Random Numbers
Flow of Control.
Chapter 3 Branching Statements
Lecture 4: Program Control Flow
The Selection Structure
Boolean Expressions and If
Chapter 4: Making Decisions.
Boolean expressions Conditional statements and expressions
CMSC 202 Java Primer 2.
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
Chapter 3 Flow of Control
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
CSC 1051 – Data Structures and Algorithms I
Outline Software Development Activities
Using C++ Arithmetic Operators and Control Structures
Conditionals and Loops
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
CSS161: Fundamentals of Computing
Boolean Expressions September 1, 2019 ICS102: The course.
CSS 161: Fundamentals of Computing
Presentation transcript:

Boolean expressions and if-else statements

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.

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(); }

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.

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

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

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

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.

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;

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.” );

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.” );

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 . . .

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

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?

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

Logical operators (AND, OR, NOT) Logical “not”: ! if (!phone.equals(“610-660-1566”) 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”);

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

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

Truth Tables

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!

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)) …

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”);

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.

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

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;

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

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);

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

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

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

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 1..31. Months are in the range 1..12.

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

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 ||

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

Precedence and Associativity Rules

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