Chapter 6 Conditions.

Slides:



Advertisements
Similar presentations
Chapter 5 Implementing a simple class. This chapter discusses n Implementing class definitions. n How to store data in an object and how to write method.
Advertisements

Chapter 6 Conditions. This chapter discusses n Conditions and conditional statements. n Preconditions, postconditions, and class invariants. n Boolean.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Chapter 5 Selection Statements. Topics Controlling program flow selection –if –switch Boolean expressions –boolean primitive type –comparison operators.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
JavaScript – Part II Data Types and Operations George Mason University June 3, 2010.
Decision Structures and Boolean Logic
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
ITP © Ron Poet Lecture 6 1 More on if. ITP © Ron Poet Lecture 6 2 Remembering Tests  We often want to remember the result of a test, so that we can use.
Chapter 7 Programming by contract: preconditions and postconditions.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Java-02 Basic Concepts Review concepts and examine how java handles them.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
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.
Principles of Programming - NI July Chapter 4: Basic C Operators In this chapter, you will learn about: Assignment operators Arithmetic operators.
Control Structures I Chapter 3
Chapter 3 Control Statements
Chapter 7: Expressions and Assignment Statements
Boolean expressions and if-else statements
Selection (also known as Branching) Jumail Bin Taliba by
Selections Java.
More important details More fun Part 3
Java Primer 1: Types, Classes and Operators
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 7: Expressions and Assignment Statements
Variables and Arithmetic Operators in JavaScript
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Topics The if Statement The if-else Statement Comparing Strings
JavaScript: Control Statements.
Control Structures – Selection
Chapter 4 : Conditionals
Topics The if Statement The if-else Statement Comparing Strings
Unit 2 Programming.
Chapter 8 JavaScript: Control Statements, Part 2
3 Control Statements:.
Java Programming Control Structures Part 1
Chapter 7 Conditional Statements
Chapter 6: Repetition Statements
Chapter 4: Control Structures I (Selection)
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
The System.exit() Method
Chapter 3 Operators and Expressions
Implementing a simple class
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 3: Selection Structures: Making Decisions
CprE 185: Intro to Problem Solving (using C)
Just Enough Java 17-May-19.
Using C++ Arithmetic Operators and Control Structures
Review of Previous Lesson
Boolean Expressions September 1, 2019 ICS102: The course.
Presentation transcript:

Chapter 6 Conditions

This chapter discusses Conditions and conditional statements Preconditions, postconditions, and class invariants Boolean expressions

Conditions postcondition: a condition the implementor (server) guarantees will hold when a method completes execution. invariant: a condition that always holds true. class invariant: an invariant regarding properties of class instances: that is, a condition that will always be true for all instances of a class.

Counter class Class invariant: component variable tally will always be greater than or equal to zero. This holds true with the methods currently defined. Postcondition: the method count must make sure that tally is greater or equal to zero when the method completes execution.

Counter class (cont.) Adding a method decrementCount threatens the class invariant constraint that tally be greater than or equal to zero. public void decrementCount () { tally = tally - 1; } We must guard the assignment statement with a condition statement.

Specifications Postconditions and class invariants are part of class specification but not the implementation. Therefore they should be included in comments but not in the implementation. /** * Current count; the number of items * counted. * ensure: * result >= 0 */ public int count () { … }

Specifications (cont.) private int tally; //current count //invariant: // tally >= 0 This commentary is, of course, meant for the implementor, not the user, of the class An appropriate comment should be included in the “preamble” documentation for the class

if statement Syntax: if (condition) statement A composite statement The condition is called the guard

Counter class (cont.) /** *Decrement positive count by 1 */ public void decrementCount () { if (tally > 0) tally = tally - 1; }

Explorer Class /** * Damage (hit points) required to defeat * this Explorer. * ensure: * result >= 0 */ public int stamina () { return staminaPoints; } … private int staminaPoints;//current stamina //invariant: //staminaPoints >= 0

Explorer Class (cont.) If stamina reaches 0, an explorer is defeated. One possible solution: public void takeHit (int hitStrength){ if (hitStrength <= staminaPoints) staminaPoints = staminaPoints - hitStrength; } But this never lets explorer “hitters” hit it with strength greater than the current explorer’s staminaPoints.

Explorer Class (cont.) A possible solution: public void takeHit (int hitStrength){ if (hitStrength <= staminaPoints) staminaPoints = staminaPoints - hitStrength; if (hitStrength > staminaPoints) staminaPoints = 0; } What is wrong with this approach?

Explorer Class (cont.) The first condition might be satisfied and then in the changed state, the second condition as well. Suppose, for example: hitStrength == 9 && staminaPoints == 10 After takeHit method is executed, we will have staminaPoints == 0 when it should be 1

if-else statement Syntax: if (condition) statement1 else statement2 Another composite statement

Explorer class (cont.) public void takeHit( int hitStrength ) { if (hitStrength <= staminaPoints) staminaPoints = staminaPoints - hitStrength; else staminaPoints = 0; }

Explorer constructor What should be done if the constructor is called with a negative value for the parameter stamina? public Explorer (String name, rooms.Room location, int hitStrength, int stamina) { … if (stamina >= 0) staminaPoints = stamina; else staminaPoints = 0; … }

Compound statements Syntax: In the statement: { statement1 statement2 … } In the statement: if (hitStrength <= staminaPoints) staminaPoints = staminaPoints - hitStrength; else staminaPoints = 0; strengthPoints = 0; the last statement is not part of the else “statement”

Compound statements (cont.)

Compound statements (cont.) Braces are used to create a block or compound statement, which is a single composite statement. if (condition) { if (condition) { statement1 statement1 … … statementn statementn } } else { statement1 … statementn }

Compound statements (cont.) if (hitStrength <= staminaPoints) staminaPoints = staminaPoints - hitStrength; else { staminaPoints = 0; strengthPoints = 0; }

Compound statements (cont.)

Relational Expressions Relational operators: < less than <= less than or equal > greater than >= greater than or equal == equal (a single ‘=‘ denotes assignment.) != not equal A relational expression consists of two expressions joined with a relational operator.

Relational Expressions (cont.) Let i1==10, i2==(-20), i3==30. i1 < 12  true i1 <= 10  true i3 == i1  false i1 != 2  true i1 < 10  false i2 > 0  false 2*i1 == i2+40  true i2*(-1) != i1+i1  false

Relational Expressions (cont.) An expression like a<b<c is illegal. If one operand is an int and the other is a double, the int is first converted to a double. 10 > 2.5  10.0 > 2.5 Since floating point values are approximations for real numbers, we should avoid using equality or inequality operators with them. (1.0/6.0+1.0/6.0+1.0/6.0+ 1.0/6.0+1.0/6.0+1.0/6.0) == 1.0  false

Boolean variables Boolean values can be stored as variables. private boolean tooBig; tooBig = true; tooBig = (i1 > 10);

Boolean Operators ! not (unary) && and || or ! booleanExpression booleanExpression && booleanExpression booleanExpression || booleanExpression A boolean expression evaluates to either true or false.

The “not” operator “not” reverses boolean values. i.e., !true  false !false  true If i1==10 !( i1 > 9)  !(true)  false “not” has high precedence. ! i1 > 9  (!i1) > 9  illegal If possible avoid the “not” operator.

“and” and “or” truth table b1&&b2 b1||b2 true false (i1>10)||(i1==10)  false||true  true (i1>10)||(i1<0)  false||false  false (i1>0)&&(i1<5)  true&&false  false (i1>0)&&(i1<20)  true&&true  true

“and” and “or” (cont.) The && and || have lower precedence than the relational operators, but parentheses are still useful because they enhance readability. The && and || are lazy operators, that is, the right operand is evaluated only when it is necessary.

“and” and “or” (cont.) Consider: (5 == 4) && ???? (5 != 4) || ???? Does it matter what the second operands are? This can protect against runtime errors such as an attempt to divide by zero. e.g., (x == 0) || (y/x < 10) (x != 0) && (y/x < 10)

DeMorgan’s Law Useful for simplifying expressions !(b1 && b2)  !b1 || !b2 !(b1 || b2)  !b1 && !b2 !(i1>5 && i1<8)  !(i1>5) || !(i1<8)  (i1<=5) || (i1>=8)

Operation precedence

Handling multiple cases Consider a method that determines if a year is a leap year. The Gregorian calendar stipulates that a year is a leap year if it is divisible by 4, unless it is also divisible by 100, in which case it is a leap year if and only if it is divisible by 400. For example, 1900 is not a leap year, but 2000 is. ( (year % 100 != 0) && (year % 4 == 0) ) || ( (year % 100 == 0) && (year % 400 == 0) )

Leap year method Another way of representing these rules uses cases and nested conditional statements. public boolean isLeapYear ( int year ) { boolean aLeapYear; if (year % 4 == 0) if (year % 100 == 0) aLeapYear = (year % 400 == 0); else aLeapYear = true; aLeapYear = false; return aLeapYear; }

Leap year method (cont.)

Traffic signal class Traffic signal class instances cycle through 4 states: LEFT (left turn arrow) GO (green light) CAUTION (yellow light) STOP (red light) The component variable currentState will hold one of these states.

Traffic signal class We want the method advance to move currentState to the next state. We assume that the component variable currentState has been declared as: private int currentState; public void advance () { if (currentState == LEFT) currentState = GO; else if (currentState == GO) currentState = CAUTION; if (currentState == CAUTION) currentState = STOP; else //currentState == STOP currentState = LEFT; }

Traffic signal class (cont.)

Dangling else Which if statement is the following else statement associated with? if (condition1) if (condition2) statement1 else statement2

Dangling else (cont.)

Dangling else (cont.) It is associated with the second if (b). To associate it with the first, add curly braces around everything contained between the first if and the else. if (condition1) { if (condition2) statement1 } else statement2

Another example: combination lock Responsibilities: Know: The combination whether unlocked or locked Do: lock unlock

Combination lock class Class: CombinationLock Queries: isOpen Commands: lock unlock

Class CombinationLock specifications public class CombinationLock Constructor: public CombinationLock( int combination ) Queries: public boolean isOpen() Commands: public void close() public void open( int combination )

Class CombinationLock implementation Component variables: private int combination; private boolean isOpen; CombinationLock combination int isOpen boolean

Class CombinationLock implementation (cont.) The methods with straightforward implementations: public boolean isOpen() { return isOpen; } public void close() { isOpen = false;

Class CombinationLock implementation (cont.) When the constructor is being executed, there are two distinct variables with the same name: Component variable and local variable combination). The keyword this refers to the “current object.” Therefore this.combination refers to the component variable. If the variable does not include the object reference this in front of it, it would be a reference to the local variable of the same name (if any). If there aren’t any local variables of the same name, then the unadorned variable refers to the component variable.

Class CombinationLock implementation (cont.)

Class CombinationLock implementation (cont.) public CombinationLock( int combination ) { this.combination = combination; isOpen = false; } We could write the second assignment as this.isOpen = false; But there is no ambiguity, so it is not necessary.

Class CombinationLock implementation (cont.) A final method: public void open( int combination ) { if ( this.combination == combination ) isOpen = true; }

Digit by digit lock: This lock has a 3 digit combination. To open the lock, the client provides the digits one at a time. If the client enters the three digits of the combination in order, the lock opens. It doesn’t matter how many digits the client provides, as long as the combination is given in the correct sequence at some point.

Digit by digit lock: Digit Entered 4 1 2 3 7 Lock Status closed open

CombinationLock responsibilities Know: the 3-digit combination. whether locked or unlocked. the last three digits entered. Do: lock. unlock, when given the proper combination. accept a digit.

Class CombinationLock public class CombinationLock Constructor: public CombinationLock (int combination) require: combination >= 0 && combination <=999 Queries: public boolean isOpen () Commands: public void close () public void enter (int digit) require: digit >=0 && digit <=9

Precondition A condition the client of a method must make sure holds when the method is invoked. The constructor and method enter have certain requirements that must be met for them to execute properly. These are the “require:”s found in the definition on the previous slide. Somewhat like the “unleaded gas only” sign near the gas cap on an automobile.

Getting digits from integers. Using the % and / operator, we can extract each digit. Suppose a combination 123. 123 % 10  3 123 / 10  12 12 % 10  2 12 / 10  1 % 10 gets the last digit and / 10 get the remaining digits.

CombinationLock implementation // entered1, entered2, entered3 are the last three // digits entered, with entered3 the most recent. // a value of -1 indicates the digit has not been // entered. private int entered1; private int entered2; private int entered3; // invariant: // entered1 >= -1 && entered1 <= 9 && // entered2 >= -1 && entered2 <= 9 && // entered3 >= -1 && entered3 <= 9

CombinationLock implementation

We covered Boolean expressions. Conditional statements. if (condition) statement statement1 else statement2 Compound statements {statement1 statement2 … statementn} Preconditions, postconditions, invariants.