Unit 7 - Short-Circuit Evaluation - De Morgan’s Laws - The switch statement - Type-casting in Java - Using Math.random()
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)
De Morgan’s Laws ! (p && q) evaluates to ( !p || !q ) One could think of it as the “Distributive Property” for Logic ! (p && q) evaluates to ( !p || !q ) ! (p || q) evaluates to ( !p && !q )
The switch Statement switch (expression) { case value1: ... break; default: } The switch Statement switch case default break Don’t forget breaks! Reserved words Only works with: int char enum
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 my shoe"); break; case 3: case 4: System.out.println(“Shut the door"); …
The Cast Operator Java allows a programmer to “cast” a piece of data to a different type when needed. Can be useful if working with int values and a decimal result is needed. For example, one might want the decimal equivalent of a fraction even though the numerator and denominator are integers. Example: decAnswer = (double)myDenominator / (double)myNumerator;
Math.Random() returns a double value 0 ≤ x < 1 Can then be scaled to fit the needs of your application. For example, if you needed a random number from 1 to 12, you would do something like this: randNum = (int) (12 * Math.Random() ) + 1;
The Craps Project The purpose of this case study is both to practice with if-else and boolean expressions and to discuss design topics: OO design, team development, and software reusability.
The Craps Project (cont’d) Your job Your assignment is placed into the context of a larger team effort. All you need to know is the public interfaces for your classes Die and CrapsGame, that is, their constructors and public methods.
The Craps Project (cont’d) Step 1: Test your CrapsGame class separately using the class CrapsTest1 provided to you. CrapsTest1 It would take a long time to test your class in the real Craps program, with random numbers of points coming up on the dice. You want a more controlled test, in which you can specify the outcome of a “dice roll,” and you need to run through all relevant sequences of “roll” outcomes. CrapsGame
The Craps Project (cont’d) Step 2: Use your Die and CrapsGame classes in the CrapsStats application. CrapsStats Note how the CrapsGame class is used in the Craps program, and also in the CrapsStats program. This is a simple example of reusability. CrapsGame Die
The Craps Project (cont’d) Step 3: Finish the RollingDie class (the drawDots method). Integrate CrapsGame and RollingDie into the Craps program. Step 3 is here to let you code a switch.