Download presentation
Presentation is loading. Please wait.
Published byEmory Moody Modified over 9 years ago
1
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)
2
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
3
7-3 if-else Statement if ( ) { } else { } if ( ) { } else clause is optional
4
7-4 boolean Data Type George Boole (1815 - 1864) 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;
5
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.
6
7-6 Relational Operators, =, ==, != is equal to is NOT equal to
7
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!
8
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)
9
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") )...
10
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 )...
11
7-11 Logical Operators &&, ||, ! and or not
12
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
13
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
14
7-14 Ranks of Operators ! - (unary) ++ -- ( cast ) * / % + - >= == != && || if ( ( ( year % 4 ) == 0 ) && ( month == 2 ) )... if ( year % 4 == 0 && month == 2 )... Easier to read Highest Lowest
15
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
16
7-16 Nested if-else if ("forward".equals(cmd)) { if (slide >= numSlides) beep.play(); else slide++; } else { if (slide <= 1) beep.play(); else slide -- ; }
17
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; }
18
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:
19
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
20
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:... }
21
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 };
22
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:...
23
7-23 The Craps Project
24
7-24 The Craps Project (cont’d) Your job
25
7-25 The Craps Project (cont’d) Step 1: Test your CrapsGame class separately using the class CrapsTest1 provided to you. CrapsTest1 CrapsGame
26
7-26 The Craps Project (cont’d) Step 2: Use your Die and CrapsGame classes in the CrapsStats application. CrapsStats CrapsGameDie
27
7-27 The Craps Project (cont’d) Step 3: Finish the RollingDie class (the drawDots method). Integrate CrapsGame and RollingDie into the Craps program.
28
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?
29
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?
30
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?
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.