© 2006 Pearson Education Making Decisions 1 of 26 MAKING DECISIONS Booleans Basic Choices (Should I stay or should I go?) Choosing From Many Alternatives.

Slides:



Advertisements
Similar presentations
Python Programming Language
Advertisements

Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
CSC 142 C 1 CSC 142 Object based programming in Java [Reading: chapter 4]
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Decision Structures and Boolean Logic
1 CSC 221: Computer Programming I Spring 2010 interaction & design  modular design: roulette game  constants, static fields  % operator, string equals.
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.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
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.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
CPS120: Introduction to Computer Science Decision Making in Programs.
1/54 Andries van Dam  /06/15 Piazza Stats 585 total posts 792 TA responses 5 min average response time!  Use Piazza! (But do follow the Piazza.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
Copyright 2003 Scott/Jones Publishing Making Decisions.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Introduction to Java Java Translation Program Structure
1 FUNCTIONS - I Chapter 5 Functions help us write more complex programs.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Selection Statements. Introduction Today we learn more about learn to make decisions in Turing ▫Nested if statements, ▫case statements.
Chapter Making Decisions 4. Relational Operators 4.1.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
CS 106 Introduction to Computer Science I 09 / 26 / 2007 Instructor: Michael Eckmann.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
The Math Class Methods Utilizing the Important Math Operations of Java!
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Conditionals Opening Discussion zWhat did we talk about last class? zDo you have any questions about the assignment? zPass by value limitations.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
BOOLEAN OPERATIONS AND CONDITIONALS CHAPTER 20 1.
1 CSC 221: Computer Programming I Fall 2005 simple conditionals and expressions  if statements, if-else  increment/decrement, arithmetic assignments.
CompSci 4 Chap 6 Sec 2 Sep 30, 2010 Prof. Susan Rodger “All your troubles are due to those ‘ifs’,” declared the Wizard. If you were not a Flutterbudget.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
1 Review for Midterm 2 Aaron Bloomfield CS 101-E.
Control Statements: Part1  if, if…else, switch 1.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
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++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
CONDITIONALS CITS1001. Scope of this lecture if statements switch statements Source ppts: Objects First with Java - A Practical Introduction using BlueJ,
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Chapter 4: Making Decisions.
EGR 2261 Unit 4 Control Structures I: Selection
Topics The if Statement The if-else Statement Comparing Strings
Chapter 4: Making Decisions.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Topics The if Statement The if-else Statement Comparing Strings
Comparing Data & the ‘switch’ Statement
Comparing Data & the ‘switch’ Statement
Presentation transcript:

© 2006 Pearson Education Making Decisions 1 of 26 MAKING DECISIONS Booleans Basic Choices (Should I stay or should I go?) Choosing From Many Alternatives –switch statements –M&M’s example –break statements Factory Pattern Is condition true? No Yes

© 2006 Pearson Education Making Decisions 2 of 26 Booleans Booleans, named in honor of British logician George Boole ( ), are another base type defined by Java. They can have one of two values: true or false boolean s are declared and assigned just like numbers –d–default value is false boolean foo = true; boolean bar = false; foo = bar; // foo is now false...

© 2006 Pearson Education Making Decisions 3 of 26 We can use a boolean in Cow class Cow can only fly when moon is full public class Cow extends FarmAnimal implements CowConstants { private boolean _canWeJump; public Cow(Moon myMoon) { // _moon is protected instance variable of // FarmAnimal, our superclass super(myMoon); // other setup code elided } /* when user clicks on cow, check if isFull() method of Moon returns true */ public void react() { _canWeJump = _moon.isFull(); // use this boolean to make decision later } } Terminology tidbit –a–a method that returns a boolean is called a predicate –i–it usually begins with ‘ is ’ as in ‘ isFull() ’

© 2006 Pearson Education Making Decisions 4 of 26 Relational Operators Numerical expressions (variables, constants, literal constants, etc…) can be compared using these operators. They return boolean value, either true or false Note that == is used to test for equality; don’t confuse it with = of assignment! boolean isEven = ((x % 2) == 0); Operator != > < <= >= == Meaning not equal to greater than less than less than or equal to greater than or equal to equal to Relational Operators

© 2006 Pearson Education Making Decisions 5 of 26 Comparing References We can check to see if two references are referring to the same instance of a class using == or if they are referring to different instances using != public class TestClass { public void compareReferences() { Cow cow1 = new Cow(); Cow cow2 = new Cow(); boolean isEqual = (cow1 == cow2); // false cow2 = cow1; isEqual = (cow1 == cow2); // true } } We can also check to see if a reference is not referring to anything boolean isNull = (cow1 == null);

© 2006 Pearson Education Making Decisions 6 of 26 Logical Operators: And, Or, and Not And ( && ) takes two boolean expressions and returns true only if both expressions are true Or ( || ) takes two boolean expressions and returns true if at least one expression is true Not ( ! ) takes one boolean expression and returns its negation Examples: boolean bool1 = (3 == 2) && (2 < 3); // false boolean bool2 = (!bool1) || (5.6 >= 8); // true boolean bool3 = !(bool1 && bool2); // true & and | have their own meanings in Java –bitwise AND and OR operator for integers –if you’re curious about what these do, take CS31 –has different meaning for boolean s which we will discuss in a few slides

© 2006 Pearson Education Making Decisions 7 of 26 if Statements But how do boolean s help us make decisions? Answer: if statements! Syntax: if ( ) { // code to be executed if expression is true } Boolean expression is evaluated –if true, Java executes code in body of if statement and then goes on with rest of method –if false, skips over body of if statement and continues with method

© 2006 Pearson Education Making Decisions 8 of 26 Checking booleans Note that you should never check if a boolean variable is true (or false) in the following way: if (myBoolean = = true) System.out.println(“true!”); What if you mistyped and instead wrote: if (myBoolean = true) System.out.println(“true!”); The value true would be assigned to myBoolean and the conditional statement would always evaluate to true –Assignments always evaluate to the result of the right side of the assignment –This is a HUGE source of bugs!! Remember to always use == when checking for equality! Instead, you should always say: if (myBoolean) System.out.println(“true!”);

© 2006 Pearson Education Making Decisions 9 of 26 if : The Flow Chart Is condition true? Execute rest of method Previous Statements Execute if clause No Yes

© 2006 Pearson Education Making Decisions 10 of 26 if-else What if we want to do something different when expression is false? We can add else clause to if ! Remember Moon’s isFull() predicate? if (_moon.isFull()) { // code to calculate weight and maybe fly } else { // code for cow to remain on ground } We don’t have to use braces if body of if or else is one statement: if (_moon.isFull()) this.jumpOverMoon(); else this.mooPiteously();

© 2006 Pearson Education Making Decisions 11 of 26 if-else : The Flow Chart Is condition true? Execute rest of method Previous Statements Execute else clause NoYes Execute if clause

© 2006 Pearson Education Making Decisions 12 of 26 Complex if statements We may want more than one condition in our if-statements We can add another if statement in else’s body. if ( ) { // body } else if ( ) { // body } We can also nest our if statements by putting one inside another. Our cow is now ready to fly!

© 2006 Pearson Education Making Decisions 13 of 26 Ready For Takeoff! public class Cow extends FarmAnimal implements CowConstants { private double _weight; // in pounds // some other boring stuff public Cow(Moon moon, /* some stuff FarmAnimal needs */ ) { super(moon); // some tedious setup code _weight = COW_START_WEIGHT; } public void react() { if ((_moon.isFull()) && (_weight < MAX_FLYING_WEIGHT)) this.jumpOverMoon(); else this.mooPiteously(); } public void mooPiteously() { // play a cow sound } }

© 2006 Pearson Education Making Decisions 14 of 26 Short-Circuiting What is the value of n after the following code has executed? int n = 1; if (false && (n++ == 2)) { System.out.println(“Went into the if clause”); } System.out.println(n); Answer: n is 1 –since the left side of the condition evaluated to false the right side is not evaluated The same holds for || and true –if the left side of the conditional evaluates to true, the right side is not evaluated This is called short-circuiting –part of the conditional is skipped –Java takes a shorter route to evaluate conditional Can avoid short-circuiting by using & and | operators (both sides always evaluated) –What if, in our above example, we always wanted to do the right side, which increments n? if (false & (n++ == 2)) –If we used this instead, n would be 2 but we would still not go in to the if clause.

© 2006 Pearson Education Making Decisions 15 of 26 “Side-effect”ing Note that the previous example updated a variable inside a conditional if (false && (n++ = = 2)) We only provide this as an example of C- style hacking which you might see when you look through someone else’s code. In this course, you should never write something like this –Increment your variables outside of conditionals –As you’ve seen, updating them inside conditionals makes the code confusing and hard to read.

© 2006 Pearson Education Making Decisions 16 of 26 If... If... If... What if we want lots of conditional statements? Could keep writing if-statements: if (condition1) { /* body1 */ } else if (condition2) { /* body2 */ } else if (condition3) { /* body3 */ } else if (condition4) { /* body4 */ }... else { /* bodyn */ } In English, this means –if condition1, execute body1 –otherwise, if condition2, execute body2 –otherwise, if condition3, execute body3 –otherwise, if condition4, execute body4... –otherwise, execute bodyn If all we want to do is something different for each value of a simple variable (e.g, age) can’t we do something simpler? Yes! We can use a switch statement!

© 2006 Pearson Education Making Decisions 17 of 26 switch Statement switch is used to choose among more than two mutually exclusive choices, based on values of a variable. Very special form of general if-else-if switch is like vending machine. When coins are deposited into machine they fall into ramp with holes for each different type of coin. Smallest slot is for dimes; largest, for quarters

© 2006 Pearson Education Making Decisions 18 of 26 switch Statement: Selector switch can pick out one action from among many using a simple key called a selector Selectors cannot be references, fractional numbers, or other complex data types. Of types we have encountered so far, can be int s, short s, byte s, or long s Value of selector determines action to be taken. Each possible value for selector should result in one action or set of actions (one block of code executed) Sometimes selector does not cover all cases. Use default value to specify what action(s) should be performed when selector does not fit any other values listed

© 2006 Pearson Education Making Decisions 19 of 26 switch : The Flow Chart Much like specialized if-else-if that tests mutually exclusive values of single variable Previous Statements Determine the value of the selector Execute statement 1 Execute statement n Execute statement n+1 Execute the rest of the program selector = value 1 selector = value n default … …

© 2006 Pearson Education Making Decisions 20 of 26 switch Example: M&M’s Let’s make a factory object that produces M&M’s using a switch statement! –Factory is a design pattern we’ll discuss later Want to make bunch of M&M’s –M&M’s come in different colors M&M colors are chosen by some weighted distribution –more reds, oranges, and browns –fewer greens, yellows, and blues Factory specification: Get a random value. Based on random value, create an M&M of one of the six possible colors. The M&M created should be based on a distribution. Return the M&M.

© 2006 Pearson Education Making Decisions 21 of 26 Designing M&M Factory Can use switch statement to weight probability of getting each color by having multiple values of the selector assigned to a single statement body that generates a more popular outcome –can “group” cases together - only write one statement body We’ll use the static method Math.random() for some randomness: –Returns a random double between 0.0 and 1.0; simply multiply by desired range – static means we can call this method without actually instantiating Math –Remember to cast the resulting number so you can get an int again (if you want one). _randomInt = (int)(Math.random()*15) Let’s see some code...

© 2006 Pearson Education Making Decisions 22 of 26 M&M’s “First Solution” Version If 2 is number that is randomly generated, what color is our M&M? – note: MnM is created with a java.awt.Color as a parameter public class MnMFactory { // constructor elided public MnM getMnM(){ // get a random number to serve as the selector int rand = (int)(Math.random()*10); MnM mnm = null; // not yet created switch(rand) { case 0: case 1: mnm = new MnM(java.awt.Color.orange); // red is the most popular color, hence a red // MnM will be created in three cases case 2: case 3: case 4: mnm = new MnM(java.awt.Color.red); // code for 6 and 7 elided // they are blue and green respectively default: // a brown color mnm = new MnM(new java.awt.Color(150,100,0)); } return mnm; } }

© 2006 Pearson Education Making Decisions 23 of 26 break But there’s a problem with that code... If nothing alters flow of control, switch statements “fall through” to next case –i.e., all case statements after one which matches selector are executed! In our example, nothing alters flow of control –so, if rand is 0 or 1, code under all cases will be executed likewise, if rand is 2, 3 or 4, code under cases 2, 3, 4, 5, 6, 7 as well as the default case will be executed Remember, we only want one M&M per match! Must have way to stop case from falling through: break out of switch statement

© 2006 Pearson Education Making Decisions 24 of 26 M&M Factory Method Now, what happens when 3 is selected? How about 4? 5? //... code elided to save space int rand = (int)(Math.random()*10); MnM mnm = null; // not created yet switch(rand) { case 0: case 1: mnm = new MnM(java.awt.Color.orange); break; case 2: case 3: case 4: mnm = new MnM(java.awt.Color.red); break; case 5: mnm = new MnM(java.awt.Color.yellow); break; // cases 6 and 7 elided. case 6 creates a blue // MnM and case 7 creates a green MnM default: // 3/11% chance of creating brown mnm = new MnM(new java.awt.Color (150, 100, 0)); // a brown color break; } return mnm; //... code elided to save space

© 2006 Pearson Education Making Decisions 25 of 26 Amendment to Previous Diagrams Previous Statements Determine the value of the selector Execute statement 1 break; Execute the rest of the program selector = value 1 selector = value n default Execute statement 1 break; Execute statement 1 break; … …

© 2006 Pearson Education Making Decisions 26 of 26