Boolean Expressions And if…else Statements.

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University.
C++ for Engineers and Scientists Third Edition
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Decision Structures and Boolean Logic
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Chapter 2: Using Data.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Boolean Expressions and if-else Statements Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006.
1 CS1001 Lecture Overview Java Programming Java Programming Arrays Arrays.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC INTRO TO COMPUTING - PROGRAMMING If Statement.
A Sample Program public class Hello { public static void main(String[] args) { System.out.println( " Hello, world! " ); }
7-1 boolean Data Type George Boole ( ) boolean variables may have only two values, true or false You define boolean fields or boolean local variables.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Lab 04-2 Objectives:  Understand what a file is.  Learn how to use the File class  Learn how to use the Scanner class to read from files  Learn about.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Copyright © Curt Hill The C++ IF Statement More important details More fun Part 3.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
CompSci 230 S Programming Techniques
Control Structures I Chapter 3
INTERMEDIATE PROGRAMMING USING JAVA
User-Written Functions
Chapter 3 Control Statements
Basics programming concepts-2
REPETITION CONTROL STRUCTURE
Elementary Programming
Chapter 4: Control Structures I
Selections Java.
More important details More fun Part 3
Chapter 4: Making Decisions.
Chapter 3 Selections ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH Introduction to Java Programming, Liang (Pearson 2014)
EGR 2261 Unit 4 Control Structures I: Selection
Boolean Expressions and if-else Statements
The Selection Structure
Switch Statement.
Java Review Most of these slides are based on
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Topics The if Statement The if-else Statement Comparing Strings
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Chapter 4 – Control Structures Part 1
Char data type and the String class.
SELECTION STATEMENTS (1)
While Statement.
Chapter 4: Control Structures I
Topics The if Statement The if-else Statement Comparing Strings
Bools and simple if statements
MSIS 655 Advanced Business Applications Programming
elementary programming
Control Structure Chapter 3.
SELECTIONS STATEMENTS
Lecture Notes - Week 2 Lecture-1. Lecture Notes - Week 2 Lecture-1.
Boolean Expressions to Make Comparisons
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Primitive Types and Expressions
CSC 1051 – Data Structures and Algorithms I
Review of Previous Lesson
Control Structure.
The IF Revisited A few more things Copyright © Curt Hill.
Presentation transcript:

Boolean Expressions And if…else Statements

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.

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

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

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!

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

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.

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

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

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.

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.

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.

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.

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.

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.

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.

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)

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

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

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

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

How Does An if Statement Work?

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

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

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)

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

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)

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

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

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

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

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

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)

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

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)

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

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

Top-Down Design

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

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 2.75 3.25 4.00 Popcorn 3.00 3.50 4.25 Read the size of the soft drink and popcorn from the keyboard and output the total cost.

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

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 }

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;

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 }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Questions?

Begin Lab 06