Download presentation
Presentation is loading. Please wait.
Published byMelvin Morton Modified over 8 years ago
1
Decision Structures Michele Co CS 101-E
2
2 UVa CS101E Spring 2007 Today if statements Logical expressions –Truth tables –Boolean algebra –DeMorgan’s laws Boolean expressions Relational Operators –Equality –Ordering Expressions vs. Statements
3
3 UVa CS101E Spring 2007 Background So far, sequential code We need more control… –Java constructs to control execution of statements if if-else if-else-if Relies on logical expressions
4
Conditional Statements
5
5 UVa CS101E Spring 2007 Conditional Constructs if statements –if –if-else –if-else-if switch statements
6
6 UVa CS101E Spring 2007 Basic if statement Syntax if (Expression) Action If the Expression is true then execute Action Action is either a single statement or a group of statements within braces For us, it will always be a group of statements within braces Expression Action truefalse
7
7 UVa CS101E Spring 2007 If semantics Are the numbers out of order Rearrange value1 and value2 to put their values in the proper order value2 < value1 intrememberValue1 = value1 value1 = value2 value2 = rememberValue1 true false The numberswereinitially in order The numbers were rearranged into the proper order The numbers are in order
8
8 UVa CS101E Spring 2007 What an if statement executes An if statement executes the next block of code A block is either: –A single statement without curly brackets: if (a == b) System.out.println (“a==b!!!”); –A number of statements enclosed by curly brackets: if (a == b) { System.out.print (“a”); System.out.print (“==”); System.out.print (“b”); System.out.println (“!!!”); }
9
9 UVa CS101E Spring 2007 What is the Output? int m = 5; int n = 10; if (m < n) ++m; ++n; System.out.println(" m = " + m + " n = “ + n);
10
10 UVa CS101E Spring 2007 Code Demo: AverageScore.java
11
11 UVa CS101E Spring 2007 The if-else statement Syntax if (Expression) Action 1 else Action 2 If Expression is true then execute Action 1 otherwise execute Action 2 The actions are either a single statement or a list of statements within braces Expression Action 1 Action 2 true false
12
12 UVa CS101E Spring 2007 Finding the maximum of two values System.out.print("Enter an integer number: "); int value1 = stdin.nextInt(); System.out.print("Enter another integer number: "); int value2 = stdin.nextInt(); int maximum; if (value1 < value2) { // is value2 larger? maximum = value2; // yes: value2 is larger } else { // (value1 >= value2) maximum = value1; // no: value2 is not larger } System.out.println("The maximum of " + value1 + " and " + value2 + " is " + maximum);
13
13 UVa CS101E Spring 2007 Finding the maximum of two values value1 < value2 maximum = value2 maximum = value1 true false Is value2 larger than value1 Yes, it is. So value2 is larger than value1. In this case, maximum is set to value2 No, its not. So value1 is at least as large as value2. In this case, maximum is set to value1 Either case, maximum is set correctly
14
14 UVa CS101E Spring 2007 Code Demo: Division.java
15
15 UVa CS101E Spring 2007 If-then-else precedence if (number != 0) if (number > 0) System.out.println("positive"); else System.out.println("negative"); Which if does this else refer to?
16
16 UVa CS101E Spring 2007 Code Demo: TestResults.java
17
Logical Expressions
18
18 UVa CS101E Spring 2007 Logical Expressions The branch of mathematics dealing with logical expressions is Boolean algebra –Developed by the British mathematician George Boole Logical expression values –logical true –logical false
19
19 UVa CS101E Spring 2007 Logical Operators Logical and –&& Logical or –|| Logical not –!
20
20 UVa CS101E Spring 2007 Truth Tables Formal specification for an operator Lists all combinations of operand values and results for each combination
21
21 UVa CS101E Spring 2007 Logical AND (&&) pq p and q False FalseFalse False TrueFalse True FalseFalse True TrueTrue Short circuit evaluation for logical AND: if left hand side is false, then whole expression evaluates to false
22
22 UVa CS101E Spring 2007 Logical OR (||) pq p or q False FalseFalse False TrueTrue True FalseTrue True TrueTrue Short circuit evaluation for logical OR: if left hand side is true, then whole expression evaluates to true
23
23 UVa CS101E Spring 2007 Logical NOT (!) pnot p False True True False
24
24 UVa CS101E Spring 2007 Boolean Algebra Complex logical expressions can be formed by combining simpler logical expressions pq p and q not (p and q) False FalseFalseTrue False TrueFalseTrue True FalseFalseTrue True TrueTrueFalse
25
25 UVa CS101E Spring 2007 DeMorgan’s Laws (1) not (p and q) equals (not p) or (not q) (not p) or pq p and q not (p and q) ( not p) (not q) (not q) False False False True True True True False True False True True False True True False False True False True True True True True False False False False
26
26 UVa CS101E Spring 2007 DeMorgan’s Laws (2) not (p or q) equals (not p) and (not q) (not p) and pq p or q not (p or q) ( not p) (not q) (not q) False False False True True True True False True True False True False False True False True False False True False True True True False False False False
27
27 UVa CS101E Spring 2007 DeMorgan’s Laws ! (a && b) == (! a) || (! b) ! (a || b) == (! a) && (! b)
28
28 UVa CS101E Spring 2007 Sidewalk chalk guy Source: http://www.gprime.net/images/sidewalkchalkg uy/
29
Boolean Expressions
30
30 UVa CS101E Spring 2007 Java’s boolean type Has 2 literal constants –true –false Operators –&& –|| –!
31
31 UVa CS101E Spring 2007 Defining boolean variables Local boolean variables are uninitialized by default boolean isWhitespace; boolean receivedAcknowledgement = true; boolean haveFoundMissingLink = false;
32
32 UVa CS101E Spring 2007 Assignment vs. comparison = is the assignment operator –Consider: int x; x = 5; == is the comparison operator –Consider: int x = 5; System.out.println (x == 5); System.out.println (x == 6); –Prints out true, false
33
33 UVa CS101E Spring 2007 Equality Operators == –returns true if operands have the same value != –returns true if operands have different values Works with all sorts of values
34
34 UVa CS101E Spring 2007 Evaluating boolean expressions Suppose boolean p = true; boolean q = false; boolean r = true; boolean s = false; What is the value of p p && s !s p == q q q != r p && r r == s q || s q != s
35
35 UVa CS101E Spring 2007 Evaluating boolean expressions Suppose int i = 1; int j = 2; int k = 2; char c = '#'; char d = '%'; char e = '#'; What is the value of j == k i != k i == j j != k c == e d != e c == d c != e
36
36 UVa CS101E Spring 2007 A bit of humor…
37
37 UVa CS101E Spring 2007 Ordering operators Java provides ordering operators for the primitive types –, = –They correspond to mathematical operators of, ≤, and ≥ Together the equality and ordering operators are known as the relational operators
38
38 UVa CS101E Spring 2007 Relational Operators Summary Relational OperatorMeaning > is greater than < is less than >= is greater than or equal to <= is less than or equal to == is equal to != is not equal to
39
Evaluating Boolean Expressions
40
40 UVa CS101E Spring 2007 Evaluation boolean expressions Suppose int i = 1; int j = 2; int k = 2; What is the value of i < j j < k i <= k j >= k i >= k
41
41 UVa CS101E Spring 2007 Unicode values Character comparisons are based on their Unicode values Characters ‘0’, ‘1’, … ‘9’ have expected order –Character ‘0’ has the encoding 48 –Character ‘1’ has the encoding 49, and so on. Upper case Latin letters ‘A’, ‘B’, … ‘Z’ have expected order –Character ‘A’ has the encoding 65, character ‘B’ has the encoding 66, and so on. Lower case Latin letters ‘a’, ‘b’, … ‘z’ have expected order –Character ‘a’ has the encoding 97, `b’ 98, etc.
42
42 UVa CS101E Spring 2007 Evaluation boolean expressions Suppose char c = '2'; char d = '3'; char e = '2'; What is the value of c < d c < e c <= e d >= e c >= e
43
43 UVa CS101E Spring 2007 Operator precedence revisited Highest to lowest –Parentheses () –Unary operators - –Multiplicative operators * / % –Additive operators + - –Relational ordering, = –Relational equality ==, != –Logical and && –Logical or || –Assignment =
44
44 UVa CS101E Spring 2007 Expressions vs. Statements Statement –Single command for Java to execute –Examples System.out.println (“hello world”); int x = 4; ++x; Expression –Returns a value (does not have semi-colon) Note the difference between the following: –++iis an expression –++i;is a statement
45
45 UVa CS101E Spring 2007 Sand Castles
46
Evaluating Boolean Expressions Precedence In-Class Exercise
47
47 UVa CS101E Spring 2007 More Complex Boolean Expressions w/Precedence 1.7 < 4 < 1 2.3 - -4 != 6 % 11 3.4 < 9 == false 4.7 > 2 != false 5.2 == 2 == 1 6.2 – 6 < 6 – 2 7.6 % 5 <= 5 + 7
48
48 UVa CS101E Spring 2007 What Order of Evaluation? What Result? 1.3 < 7 && 7 < 14 2.2 > 6 && 6 == 14 3.false || false && true 4.4 == 6 || 6 != 4 5.true || false && true && false 6.! ( 4 != 8 != true) 7.! false || ! true 8.8 / 3 >= 1 == ! true 9.false || true && true || false
49
49 UVa CS101E Spring 2007 End of Class 7 Feb 2007
50
Expressions and Floating Point Precision FloatTest.java
51
51 UVa CS101E Spring 2007 Take care with floating- point values Consider double a = 1; double b = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 double c =.9999999999999999; Two true expressions! c == bb != a Two false expressions! a == bb != c Problem lies with the finite precision of the floating-point types Instead with the ordering operators for closeness
52
52 UVa CS101E Spring 2007 How to solve this Don’t compare floating-point values if you can help it! –Both doubles and floats Need to test if the two doubles are “close” in value final double EPSILON = 0.000001; boolean foo = Math.abs (a-b) < EPSILON;
53
53 UVa CS101E Spring 2007
54
Debugging
55
55 UVa CS101E Spring 2007 Debugging Webster’s English Dictionary 1.to remove insects from 2.to eliminate errors in or malfunctions of 3.to remove concealed microphone or wiretapping device
56
56 UVa CS101E Spring 2007 Basic Debugging Process 1.Recognize that a bug exists 2.Isolate the source of the bug 3.Identify the cause of the bug 4.Determine a fix for the bug 5.Apply the fix and test it –if a problem still exists, re-evaluate assumptions, go back to start
57
57 UVa CS101E Spring 2007 Step 1: Recognizing the Bug Check –the format and content of data are correct –if unanticipated data values are given –if values are corrupted or handled incorrectly The more minor the error, the MORE difficult to locate!!! Questions –What conditions cause the problem? –Are there workarounds?
58
58 UVa CS101E Spring 2007 Step 2: Isolate the Sources of the Bug 1.Is the input correct? 2.Is it read in properly? 3.Is it processed correctly? 1.Step through the program sequentially 2.Hypothesize where the problem might be 3.... may have to iterate until sources are found
59
59 UVa CS101E Spring 2007 Step 3: Determine the Cause of the Bug Is the data wrong? If so, why? Was the data handled incorrectly? –Why? Misunderstanding of/lack of familiarity with the system? Logic error? Unexpected values? (Values outside of unstated assumptions) Does this error occur in other sections of the code?
60
60 UVa CS101E Spring 2007 Step 4: Determine a Fix Need knowledge of the system May expose other hidden bugs –Possible large design flaws
61
61 UVa CS101E Spring 2007 Step 5: Fix and Test (Repeat, as necessary) Apply the fix Check to see that the fix addresses the problem –Has the original problem been fixed? –Are there any new problems? (Unusual side effects?) Large systems use regression tests (test suite)
62
62 UVa CS101E Spring 2007 Making Debugging More Efficient 1.Recognize that you might not fully understand the assumptions or system (and that this is ok...) 2.Start debugging early As you write your code, insert checks Brainstorm possible ways for bugs to occur 3.Suspect user input Add code to carefully check inputs 4.Develop a set of tests to exercise the code 5.Change only ONE thing at a time! 6.Back out changes that have no effect Problem isn’t where originally thought That area of code isn’t being reached, so isn’t part of the bug at hand May introduce new bugs after current bug is fixed
63
In-Class Debugging Exercises Debugging Decisions ifError1.java, ifError2.java, ifError3.java, switchError.java
64
64 UVa CS101E Spring 2007 Switch and if-else-if if-else-if structures that handle integral data can be converted to switch statements ifToSwitchConversion.java
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.