1 / 27

MAKING DECISIONS

MAKING DECISIONS. Booleans Basic Choices “Two roads diverge in a yellow wood” - Frost “When you come to a fork in the road, take it” - Berra “I drove by the fork in the road and went straight” – JAY-Z Choosing From Many Alternatives switch statements M&M’s example break statements

mikko
Télécharger la présentation

MAKING DECISIONS

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. MAKING DECISIONS Booleans Basic Choices “Two roads diverge in a yellow wood” - Frost “When you come to a fork in the road, take it” - Berra “I drove by the fork in the road and went straight” – JAY-Z Choosing From Many Alternatives switch statements M&M’s example break statements Factory Pattern

  2. Booleans Booleans, named in honor of British logician George Boole (1815-1864), are another base, or primitive, type defined by Java. They can have one of two values: true or false. booleans are declared and assigned just like numbers default value is false assign an initial value anyway (good habit) booleanfoo = true; boolean bar = false; foo = bar; // foo is now false...

  3. We can use a boolean in Cow class Cow can only fly when moon is full public class Cow extends FarmAnimal { private boolean _canWeJump; public Cow(Moon myMoon) { super(myMoon); // other setup code elided } /** * When user clicks on cow, check if * isFull() method of Moon returns true */ public void react() { // _moon is protected instance variable // of FarmAnimal, our superclass _canWeJump = _moon.isFull(); // later use _canWeJump “flag” to make // decision } } Terminology tidbits a method that returns a boolean is called a predicate a predicate usually begins with ‘is’ or ‘has’, like ‘isFull()’ a boolean that stores the value returned by a predicate is called a flag

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

  5. 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(…); booleanisEqual = (cow1 == cow2); // false booleanisNotEqual = (cow1 != cow2);//true cow2 = cow1; isEqual = (cow1 == cow2); // true isNotEqual = (cow1!= cow2);// false } } We can also check to see if a reference is not referring to anything boolean isCow1Null = (cow1 == null);

  6. Logical Operators: And, Or, Not And (&&) takes two boolean expressions and returns true if and only if both expressions are true Or (||) takes two boolean expressions and returns true if and only if at least one 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 & OR operator for integers if you’re curious about what these do, take CS33 has different meaning for booleans which we will discuss in a few slides

  7. if Statements But how do booleans help us make decisions? Answer: if statements! Syntax: if (<boolean expression>) { // code to be executed if expression is true } Boolean expression is evaluated if true, Java executes code in body of ifstatement if false, skips over body of if statement as if it weren’t there. whether or not the body of the if statement was executed, Java then continues on with the rest of the method

  8. if: The Flow Chart Previous Statements Is condition true? Yes No Execute if clause Execute rest of method

  9. Checking booleans Note:System.out.println(…) is a special java output method useful for debugging temporary results and messages Parameter can be a variable (of type java.lang.String), a literal (e.g., “Hello World”), or an expression (e.g., 23) You should never, evercheck if a boolean variable is true (or false) in the following way: if (myBoolean == true) { System.out.println(“it’s true!”); } What if you mistyped and instead wrote: if (myBoolean = true) { System.out.println(“it’s 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! The Java compiler would catch this error, but in other languages, the above assignment would be legal and you will have a hard time tracking down the bug Instead, you should always say: if (myBoolean){ System.out.println(“it’s true!”); }

  10. if-else What if we want to do something different when the expression is false? We can add an else clause to if! Remember Moon’s isFull() predicate? if (_moon.isFull()) { // code to jump over the moon } else { // code to stay on the ground } Java doesn’t require use of braces if the body of if or else is one statement, but we want you to always use braces to allow for expansion to multiple statements in the future: This will also save you hours of painful debugging! if (_moon.isFull()){ this.jumpOverMoon(); } else{ this.mooPiteously(); } // We can nest boolean method calls!

  11. if-else: The Flow Chart Previous Statements Is condition true? Yes No Execute if clause Execute else clause Execute rest of method

  12. Complex if statements We may want more than one condition in our if statements We can use an ‘else if’ statement if (<boolean expression>) { // body for if } else if (<boolean expression>) { // body for else if } else { // body for else } We can also nestour if statements by putting one inside another

  13. Nested if statements example Note: methods and variables are made up //first if statement if (cs15Student.hasProject()) { //nested if-else statement if (cs15Student.hasInitiative()) { cs15Student.codeTASafeHouseEarly(); } else { cs15Student.playMarioKart(); } } // end of first if // statement

  14. Cow has been cleared for Takeoff by NASA! public class Cow extends FarmAnimal { private double _weight; // in pounds // some other boring stuff public Cow(Moon moon, /* …*/) { /* other parameters elided*/ super(moon); _weight = CowConstants.COW_START_WEIGHT; //constant defined in CowConstants } public void react() { if ((_moon.isFull()) && (_weight <= CowConstants.MAX_FLYING_WEIGHT)) { this.jumpOverMoon(); } else { this.mooPiteously(); } } } Important: Makesure your closing brackets line up with the correct identifiers! Not required by Java, but good practice.

  15. 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 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 into the ifclause.

  16. “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 CS15, you should never increment your variables inside conditionals as you’ve seen, updating variables inside conditionals makes the code confusing and hard to read

  17. If... If... If... What if we want lots of mutually exclusive conditional statements? For maximum generality, Java recognizes the if-else if-else if... construction, with an arbitrary number of else ifs: if (condition_1) { /* body_1 */ } else if (condition_2) { /* body_2 */ } else if (condition_3) { /* body_3 */ } else if (condition_4) { /* body_4 */ } ... else { /* body_n */ } In English, this means if condition_1, execute body_1 otherwise, if condition_2, execute body_2 otherwise, if condition_3, execute body_3 otherwise, if condition_4, execute body_4 . . . otherwise, execute body_n 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!

  18. 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 a ramp with holes for each different type of coin. Smallest slot is for dimes; largest for quarters. 25 5 10

  19. 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 the types we have encountered so far, selectors can be ints, shorts, bytes, or longs. The value of a selector determines the action to be taken. Each possible value for a selector should result in one action or set of actions (one block of code executed). Sometimes a selector does not cover all cases. Use default value to specify what action(s) should be performed when a selector does not fit any other values listed.

  20. 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 selector = value 1 selector = value n default Execute statement 1 Execute statement n Execute statement n+1 Execute the rest of the program … …

  21. switch Example: M&M’s Let’s make a factory object that produces M&M’s using a switch statement! Factory is a generalization of a simple constructor and is an example of a “design pattern” that we’ll discuss later (and you’ll need it for Tetris) We want to make a 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 the random value, create an M&M of one of the six possible colors. The color of the M&M created should be based on a weighted distribution. Return the M&M.

  22. Designing M&M Factory We can use a switch statement to weight the 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: This method returns a random double between 0.0 (inclusive) and 1.0 (exclusive); simply multiply by desired range static means we can call this method without actually instantiating Math Remember to castthe resulting number so you can get an int again (if you want one) _randomInt = (int)(Math.random()*10); Let’s see some code...

  23. M&M’s “First (Incorrect) Solution” Version If 2 is our randomly generated number, what color is our M&M? Note: an instance of class MnM is constructed with a java.awt.Coloras a parameter public class MnMFactory { // constructor elided public MnMgetMnM() { // get a random number to serve as the selector int rand = (int)(Math.random()*10); MnMmnm = null; // not yet created switch (rand) { case 0: case 1: mnm = new MnM(java.awt.Color.PURPLE); // 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 cases 5, 6, and 7 elided // they are green, blue, yellow respectively default:// a brown color mnm = new MnM(new java.awt.Color(150,100,0)); } return mnm; } } // end of class

  24. Oh, give me a break But there’s a problem with that code . . . If nothing alters the flow of control, switch statements will “fall through” to the next case i.e., all case statements after any case that matches the selector will be 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 for cases 2, 3, 4, 5, 6, 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

  25. 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); MnMmnm = null; // not created yet switch (rand) { case 0: case 1: mnm = new MnM(java.awt.Color.PURPLE); break; case 2: case 3: case 4: mnm = new MnM(java.awt.Color.RED); break; case 5: mnm = new MnM(java.awt.Color.GREEN); break; // cases 6 and 7 elided. case 6 creates a blue // MnM and case 7 creates a yellow MnM. default: // 20% chance of creating brown mnm = new MnM(new java.awt.Color(150, 100, 0)); break; } return mnm; // ... code elided to save space

  26. Amendment to Previous Diagrams Previous Statements Determine the value of the selector selector = value 1 selector = value n default Execute statement 1 break; Execute statement n break; Execute statement default break; Execute the rest of the program … …

  27. Announcements • Lab 3 (Interfaces and Polymorphism) is this week! • TASafeHouse is due Friday at 10pm! • Early deadline: Wednesday at 11:59pm • Late deadline: Sunday at 11:59pm • GFX goes out on Thursday.

More Related