Boolean Expressions and if-else Statements Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006.

Slides:



Advertisements
Similar presentations
CS-1010 Dr. Mark L. Hornick 1 Selection Statements and conditional expressions.
Advertisements

Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
If Statements & Relational Operators Programming.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Flow of Control (1) : Logic Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
(c) 2003 E.S.Boese1 Conditionals Chapter 10 - Student.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Boolean Expressions Conditional Statements & Expressions CSC 1401: Introduction to Programming with Java Lecture 4 – Part 2 Wanda M. Kunkle.
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 Lecture 7:Control Structures I (Selection) Introduction to Computer Science Spring 2006.
Function tax and buy_one double tax (double price, double tr) { return price*tr; } double buy_one() { double p; cout > p;
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
Logical Operators and Conditional statements
C++ for Engineers and Scientists Third Edition
Visual C++ Programming: Concepts and Projects
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.
COMP 110 Introduction to Programming Mr. Joshua Stough September 19, 2007.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.1 Chapter 3 Selections.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Chapter 8 Conditionals. Learning Java through Alice © Daly and Wrigley Objectives List relational operators. List logical operators. Use the hierarchy.
CSCI 1100/1202 January 28, The switch Statement The switch statement provides another means to decide which statement to execute next The switch.
Decisions CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 5, Horstmann*
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Chapter 3 More Flow Of Control.
Flow of Control Part 1: Selection
Compound Statements If you want to do more than one statement if an IF- else case, you can form a block of statements, or compound statement, by enclosing.
ㅎㅎ logical operator if if else switch while do while for Third step for Learning C++ Programming Repetition Control Structures.
1 st Semester Module3 Condition Statement อภิรักษ์ จันทร์สร้าง Aphirak Jansang Computer Engineering.
Compound Statements If you want to do more than one statement if an if- else case, you can form a block of statements, or compound statement, by enclosing.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
Iterative Statements: while, for, do-while Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
1 CS1001 Lecture Overview Java Programming Java Programming Arrays Arrays.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
Decisions. Three Forms of Decision Making in Java if statements (test a boolean expression) switch statements (test an integer expression) conditional.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
If Statements Programming. COMP104 Lecture 7 / Slide 2 Review: Rules for Division l C++ treats integers different than doubles. 100 is an int. l 100.0,
Control statements Mostafa Abdallah
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
BOOLEAN OPERATIONS AND CONDITIONALS CHAPTER 20 1.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
STRUCTURED PROGRAMMING Selection Statements. Content 2  Control structures  Types of selection statements  if single-selection statement  if..else.
Chapter 6 Conditionals. Learning Java through Alice © Daly and Wrigley Objectives List relational operators. List logical operators. Use the hierarchy.
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.
Session 2 Operators, Decisions and Loops. Objectives Operators Casting data Decision marking structures Loops break, continue, return.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
LECTURE # 7 : STRUCTURED PROGRAMMING Selection Statements Tr.Hadeel.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Boolean Expressions and if-else Statements
Boolean Expressions And if…else Statements.
Chapter 4: Control Structures I (Selection)
Control Structure Chapter 3.
Unit 7 - Short-Circuit Evaluation - De Morgan’s Laws - The switch statement - Type-casting in Java - Using Math.random()
CprE 185: Intro to Problem Solving (using C)
Control Structure.
Presentation transcript:

Boolean Expressions and if-else Statements Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. if (chapter == 7)

7-2 Objectives: Learn about the boolean data type Learn the syntax for if-else statements Learn about relational and logical operators, De Morgan’s laws, short-circuit evaluation Learn when to use nested if-else statements, if-else-if sequences, the switch statement Learn about enum data types

7-3 if-else Statement if ( ) { } else { } if ( ) { } else clause is optional

7-4 boolean Data Type George Boole ( ) 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 Reserved words private boolean hasMiddleName; boolean isRolling = false;

7-5 Boolean Expressions In if ( ) is a Boolean expression. A Boolean expression evaluates to either true or false. Boolean expressions are written using boolean variables and relational and logical operators.

7-6 Relational Operators, =, ==, != is equal to is NOT equal to

7-7 Relational Operators (cont’d) Apply to numbers or chars: if ( count1 <= count2 )... if ( sum != 0 )... if ( letter == 'Y' )... 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)... May be false!

7-8 Relational Operators (cont’d) Be careful using == and != with objects (for example, Strings): they compare references (addresses) rather than values (the contents) String cmd = console.readLine(); if ( cmd == "Help" )... Wrong! (always false)

7-9 Relational Operators (cont’d) Use the equals or equalsIgnoreCase methods to compare Strings: or if ( "Help".equals (cmd) )... String cmd = console.readLine(); if ( cmd.equals ("Help") )...

7-10 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. String text = file.readLine( ); if ( text != null )...

7-11 Logical Operators &&, ||, ! and or not

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

7-13 Logical Operators (cont’d) &&, ||, and ! obey the laws of formal logic called De Morgan’s Laws: Example: if ( ! ( x => - 10 && x <= 10 ) )... if ( x 10 )... ! (p && q) == ( !p || !q ) ! (p || q) ==( !p && !q ) Easier to read

7-14 Ranks of Operators ! - (unary) ( cast ) * / % + - >= == != && || if ( ( ( year % 4 ) == 0 ) && ( month == 2 ) )... if ( year % 4 == 0 && month == 2 )... Easier to read Highest Lowest

7-15 Short-Circuit Evaluation if (condition1 && condition2)... If condition1 is false, then condition2 is not evaluated (the result is false anyway) if (condition1 || condition2)... If condition1 is true, then condition2 is not evaluated (the result is true anyway) if ( x >= 0 && Math.sqrt (x) < 15.0)... Always OK: won’t get to sqrt if x < 0

7-16 Nested if-else if ("forward".equals(cmd)) { if (slide >= numSlides) beep.play(); else slide++; } else { if (slide <= 1) beep.play(); else slide -- ; }

7-17 if-else-if if (drinkSize.equals(”Large")) { price += 1.39; } else if (drinkSize.equals("Medium")) { price += 1.19; } else // if "Small" drink size { price += 0.99; }

7-18 Common if-else Errors if (...) statement1; else statement2;... It is safer to always use braces in if-else if (...) statement1; statement2;... if (...) ; { statements;... } Extra semicolon:Missing braces:

7-19 The switch Statement switch (expression) { case value1:... break; case value2:... break;... default:... break; } Don’t forget breaks! switch case default break Reserved words

7-20 The switch Statement (cont’d) The same case can have two or more labels. For example: switch (num) { case 1: case 2: System.out.println ("Buckle your shoe"); break; case 3:... }

7-21 enum Data Types Used when an object’s attribute or state can have only one of a small set of values, for example: enum variables do not represent numbers, characters, or strings. private enum Speed { LOW, MEDIUM, HIGH }; private enum InkColor { BLACK, RED }; private enum DayOfWeek { sunday, monday, tuesday, wednesday, thursday, friday, saturday };

7-22 enum Data Types (cont’d) Use == or != to compare enum values Can be used in a switch: private enum Speed { LOW, MEDIUM, HIGH };... Speed currentSpeed = Speed.LOW;... if (currentSpeed == Speed.LOW)... switch (currentSpeed) { case LOW:... break; case MEDIUM:...

7-23 The Craps Project

7-24 The Craps Project (cont’d) Your job

7-25 The Craps Project (cont’d) Step 1: Test your CrapsGame class separately using the class CrapsTest1 provided to you. CrapsTest1 CrapsGame

7-26 The Craps Project (cont’d) Step 2: Use your Die and CrapsGame classes in the CrapsStats application. CrapsStats CrapsGameDie

7-27 The Craps Project (cont’d) Step 3: Finish the RollingDie class (the drawDots method). Integrate CrapsGame and RollingDie into the Craps program.

7-28 Review: What are the possible values of a boolean variable? What operators are used to compare values of numbers and chars? How can you test whether two Strings have the same values? Which binary operators have higher rank (are executed first), relational or logical?

7-29 Review (cont’d): Can you have an if statement without an else? What are De Morgan’s Laws? Explain short-circuit evaluation. How long can an if-else-if sequence be?

7-30 Review (cont’d): What are breaks used for in a switch? What happens if you forget one? Can the same case in a switch have two breaks? What types of expressions can be used in a switch? chars? ints? doubles? enums? Can any operators have enum operands?