95
1 Decisions, decisions, decisions Chapter 4 Trey Kirk

1 Decisions, decisions, decisions Chapter 4 Trey Kirk

Embed Size (px)

Citation preview

Page 1: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

1

Decisions, decisions, decisions

Chapter 4Trey Kirk

Page 2: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

2

Background Our problem-solving solutions so far have the straight-line

property They execute the same statements for every run of the

program

public class DisplayForecast // main(): application entry point

public static void main(String[] args) { System.out.print("I think there is a world"); System.out.print(" market for maybe five "); System.out.println("computers. “); System.out.print(" Thomas Watson, IBM, “); System.out.println("1943.“);

}}

Page 3: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

3

Background For general problem solving we need more capabilities

The ability to control which statements are executed The ability to control how often a statement is executed

We will concentrate first on controlling which statements are executed

Java provides the if and switch conditional constructs to control whether a statement list is executed The if constructs use logical expressions to determine

their course of action

We will start with logical expressions

Page 4: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

44

Logical expressionsLogical expressions

Page 5: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

5

Logical expressions The branch of mathematics dealing with logical expressions

is Boolean algebra Developed by the British mathematician George Boole

Page 6: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

6

Logical expressions A logical expression has either the value logical true or

logical false

Some expressions whose values are logical true The year 2004 is a leap year A meter equals 100 centimeters

Some expressions whose values are logical false A triangle has four sides The area of square is always equal to twice its

perimeter

Page 7: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

7

Logical expressions There are three primary logical operators for manipulating

logical values Logical and Logical or Logical not

The operators work as most of us would expect

Page 8: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

8

Truth tables We use truth tables to give formal specifications of the

operators “It works as most of us would expect” allows for

ambiguity of interpretation Jim is smiling or Patty is smiling

Can both Jim and Patty both be smiling? Truth tables

Lists all combinations of operand values and the result of the operation for each combination

p q p and q

False False FalseFalse True FalseTrue False FalseTrue True True

Page 9: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

9

Or and not truth tables

p q p or q

False False FalseFalse True TrueTrue False TrueTrue True True p not p

False TrueTrue False

Page 10: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

10

Boolean algebra Can create complex logical expressions by combining simple

logical expressions

not (p and q)

p q p and q not (p and q)

False False False TrueFalse True False TrueTrue False False TrueTrue True True False

Page 11: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

11

DeMorgan’s laws not (p and q) equals (not p) or (not q)

(not p) or p q p and q not (p and q) ( not p) (not q) (not q)

False False False True True True TrueFalse True False True True False TrueTrue False False True False True TrueTrue True True False False False False

Page 12: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

12

DeMorgan’s laws not (p or q) equals (not p) and (not q)

(not p) and p q p or q not (p or q) ( not p) (not q) (not q)

False False False True True True TrueFalse True True False True False FalseTrue False True False False True FalseTrue True True False False False False

Page 13: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

13

DeMorgan’s laws If you remember nothing else about the Boolean operators,

remember that:

not (a and b) == (not a) or (not b) not (a or b) == (not a) and (not b)

Page 14: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

1414

Sidewalk chalk guySidewalk chalk guy

Source: http://www.gprime.net/images/sidewalkchalkguy/Source: http://www.gprime.net/images/sidewalkchalkguy/

Page 15: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

1515

Boolean expressionsBoolean expressions

Page 16: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

16

A boolean type Java has the logical type boolean

Type boolean has two literal constants true false

Operators The and operator is &&

Don’t use & The or operator is ||

Don’t use | The not operator is !

Page 17: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

17

Defining boolean variables Local boolean variables are uninitialized by default

boolean isWhitespace;boolean receivedAcknowledgement;boolean haveFoundMissingLink;

-isWhitespace

-receivedAcknowledgement

-haveFoundMissingLink

Page 18: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

18

Defining boolean variables Local boolean variables with initialization

boolean canProceed = true;boolean preferCyan = false;boolean completedSecretMission = true;

truecanProceed

falsepreferCyan

truecompletedSecretMission

Page 19: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

19

Assignment vs. comparison = is the assignment operator

It copies the value on the right to the location on the left Consider:

int x;x = 5;

The value 5 is copied to the spot x in memory

== is the comparison operator Returns a boolean (true or false) if the two sides are

equal Consider:

int x = 5;System.out.println (x == 5);System.out.println (x == 6);

Prints out true, false

Page 20: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

20

Other operators Equality operators == and !=

Operator == Returns true if the operands have the same value;

otherwise, returns false This is not the assignment operator!

Operator != Returns true if the operands have different values;

otherwise, returns false

The operators work with all types of values

Page 21: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

21

Evaluating boolean expressions Suppose

boolean p = true;boolean q = false;boolean r = true;boolean s = false;

What is the value ofp p && s !s p == q q q != r p && r r == s q || s q != s

Page 22: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

22

Evaluating boolean expressions Suppose

int i = 1;int j = 2;int k = 2;char c = '#';char d = '%';char e = '#';

What is the value ofj == k i != ki == j j != kc == e d != ec == d c != e

Page 23: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

2323

These images are not These images are not animated…animated…

Page 24: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

2525

Translating English to logical Translating English to logical expressionsexpressions

Page 25: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

26

Translating English to logical expressions English doesn’t always translate cleanly into logical expressions To see this, we need to examine the NOR operator

It doesn’t exist in Java, but we can fake it p NOR q == NOT (p OR q) NOR is represented by a downward arrow:

In Java, given variables p and q NOR is done by: !(p||q)

p q p or q not (p or q) p nor q

False False False True TrueFalse True True False FalseTrue False True False FalseTrue True True False False

Page 26: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

27

Translation Example “I have neither given nor received help on this exam”

Rephrased: “I have not given nor received …” Let p = “I have given help on this exam” Let q = “I have received help on this exam”

Translation is: pq Remember the precedence: NOT is done first!

p q p pq

T T F F

T F F T

F T T F

F F T F

Page 27: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

“I have neither given nor received help on this exam” Rephrased: “I have not (given nor received …)” Let p = “I have given help on this exam” Let q = “I have received help on this exam”

Another translation is: (pq) = p || q

28

Translation example, take 2

p q (pq) (pq) p || q

T T F T T

T F F T T

F T F T T

F F T F F

Page 28: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

29

Translation example, rephrased What is meant is “I have not given and I have not received help

on this exam” Or “I have not (given or received) help on this exam” This is a DeMorgaization of the one above it

The problem: has a higher precedence than in Boolean logic, but not always in English

Also, “neither” is vague

p q pq (p||q)

T T F F

T F F F

F T F F

F F T T

Page 29: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

3030

Floating point comparisonFloating point comparison

Page 30: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

31

Floating point precission What gets printed?

class FloatTest {public static void main (String args[]) {

double y = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 +

0.1 + 0.1 + 0.1 + 0.1 + 0.1;

System.out.println (y);}

} There are 10 0.1’s

Page 31: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

3232

Program demoProgram demo

FloatTest.javaFloatTest.java

Page 32: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

33

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 == b b != a

Two false expressions!a == b b != c

Problem lies with the finite precision of the floating-point types

Instead with the ordering operators for closeness

Page 33: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

34

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;

Page 34: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

3535

Sand CastlesSand Castles

Page 35: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

3636

More on evaluating expressionsMore on evaluating expressions

Page 36: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

37

Ordering operators Java provides ordering operators for the primitive types

Four ordering operators, <, >, <=, and >= They correspond to mathematical operators of <, >, ≤,

and ≥

Together the equality and ordering operators are known as the relational operators

False is less than true

Page 37: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

38

Evaluation boolean expressions Suppose

int i = 1;int j = 2;int k = 2;

What is the value ofi < jj < ki <= kj >= ki >= k

Page 38: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

39

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 Character ‘b’ has the encoding 98, and so on.

Page 39: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

40

Evaluation boolean expressions Suppose

char c = '2';char d = '3';char e = '2';int f = 4;

What is the value ofc < dc < ec <= ed >= ec >= ef > e

Page 40: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

41

Operator precedence revisited Highest to lowest

Parentheses Unary operators Multiplicative operators Additive operators Relational ordering Relational equality Logical and Logical or Assignment

Page 41: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

42

Expressions vs. statements A statement is a single command for Java to do, and always

ends in a semi-colon (for now, at least) System.out.println (“hello world”); int x = 4; ++x;

An expression returns a value, and does not have a semi-colon 5 circle.getRadius() x

Note the difference between the following: ++i is an expression ++i; is a statement

Page 42: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

4343

More demotivatiors!More demotivatiors!

Page 43: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

4444

if statementif statement

Page 44: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

45

Conditional constructs Provide

Ability to control whether a statement list is executed

Two constructs

If statementifif-elseif-else-if

Switch statement

Page 45: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

46

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

true false

Page 46: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

47

Example

if (value < 0) { value = -value;}

Is our numbernegative?

If Value is notless than zero

then our numberis fine as is

If Value is less thanzero then we needto update its value

to that of its additiveinverse

false

Value < 0

Value = -Value

true

Our number is nowdefinitely

nonnegative

Page 47: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

48

Sorting two valuesSystem.out.print("Enter an integer number: ");int value1 = stdin.nextInt();System.out.print("Enter another integer number: ");int value2 = stdin.nextInt();

// rearrange numbers if necessaryif (value2 < value1) {

// values are not in sorted orderint rememberValue1 = value1;value1 = value2;value2 = rememberValue1;

}

// display valuesSystem.out.println("The numbers in sorted order are "

+ value1 + " and then " + value2);

What happens if the user enters 11 and 28?

What happens if the user enters 11 and 4?

Page 48: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

If semanticsAre the numbers outof order

Rearrange value1 andvalue2 to put their

values in the properorder

value2 < value1

int rememberValue1 = value1 value1 = value2 value2 = rememberValue1

true false

The numbers were initially inorder

The numbers were rearranged intothe proper order

The numbers are in order

Page 49: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

50

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 (“!!!”);

}

Page 50: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

51

Why we always use braces What is the output?

int m = 5;int n = 10;

if (m > n) {++m;++n;

}

System.out.println(" m = " + m + " n = " + n);

Page 51: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

5252

if-else statementif-else statement

Page 52: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

53

The if-else statement Syntax

if (Expression) Action1

else Action2

If Expression is true then execute Action1 otherwise execute Action2

The actions are either a single statement or a list of statements within braces

Expression

Action1 Action2

true false

Page 53: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

54

Finding the maximum of two valuesSystem.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);

But is it initialized?

Page 54: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

55

Finding the maximum of two valuesSystem.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}

System.out.println("The maximum of " + value1 + " and " + value2 + " is " + maximum);

But is it initialized?

Page 55: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

56

Finding the maximum of two values

value1 < value2

maximum = value2 maximum = value1

true false

Is value2 larger than value1

Yes, it is . So value2 islarger than value1. Inthis case, maximum is

set to value2

No, its not. So value1is at least as large asvalue2. In this case,maximum is set to

value1

Either case, maximum is setcorrectly

Page 56: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

57

Why we use whitespace What does the following do?

System.out.print("Enter an integer number: ");int value1 = stdin.nextInt();System.out.print("Enter another integer number: ");int value2 = stdin.nextInt();if (value2 < value1) {int rememberValue1 = value1;value1 = value2;value2 = rememberValue1;}System.out.println("The numbers in sorted order are "+ value1 + " and then " + value2);

Page 57: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

59

How do you like your braces?

if (a == b){

//...} else {

//...}

if (a == b){

//...}else {

//...}

if (a == b){

//...} else {

//...}

if (a == b) {//...

} else {//...

}

if (a == b) {//...

} else {

//...}

Page 58: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

60

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?

Page 59: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

61

If-then-else precedence without whitespace

if (number != 0)if (number > 0)System.out.println("positive");elseSystem.out.println("negative");elseSystem.out.println("zero");

Page 60: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

6262

Program demoProgram demo

ElsePrecedence.javaElsePrecedence.java

Page 61: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

6363

if-else-if statementif-else-if statement

Page 62: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

64

if (number == 0) {System.out.println("zero");

}else

If-else-if Consider

System.out.println("positive");}else { System.out.println("negative");}}

{ These braces aren’t needed

if (number > 0) {

Same results as previous segment – but this segment better expresses the meaning of what is going on

We can change the whitespace

of the code

Page 63: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

65

Sorting three values For sorting values n1, n2, and n3 there are six possible

orderings n1 n2 n3 n1 n3 n2 n2 n1 n3 n2 n3 n1 n3 n1 n2 n3 n2 n1

Suppose s1, s2, s3 are to be a sorted version of n1, n2, and n3

Page 64: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

66

Sorting three valuesif ((n1 <= n2) && (n2 <= n3)) { // n1 <= n2 <= n3

s1 = n1; s2 = n2; s3 = n3;}else if ((n1 <= n3) && (n3 <= n2)) { // n1 <= n3 <= n2

s1 = n1; s2 = n3; s3 = n2;}else if ((n2 <= n1) && (n1 <= n3)) { // n2 <= n1 <= n3

s1 = n2; s2 = n1; s3 = n3;}else if ((n2 <= n3) && (n3 <= n1)) { // n2 <= n3 <= n1

s1 = n2; s2 = n3; s3 = n1;}else if ((n3 <= n1) && (n1 <= n2)) { // n3 <= n1 <= n2

s1 = n3; s2 = n1; s3 = n2;}else { // n3 <= n2 <= n1

s1 = n3; s2 = n2; s3 = n1;}

Page 65: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

6767

?: notation?: notation

Page 66: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

68

Finding the minimum value Consider:

// z is to hold the minimum of x and yif ( x < y )

z = x;else

z = y;

Another way to do this:

z = (x<y) ? x : y;

Notice no braces!

Page 67: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

69

The ?: notation Only works when both “cases” return a value!

Meaning when both “cases” are expressions Example: z = (x<y) ? x : y; Thus, you can’t put a print statement in there!

Can be difficult to read

System.out.println ((number != 0) ? ((number > 0) ? "positive“ : "negative") : "zero“);

if (number != 0)if (number > 0)

System.out.println("positive");else

System.out.println("negative");else

System.out.println("zero");

Page 68: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

7070

A bit of humor…A bit of humor…

Page 69: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

7171

switch statementswitch statement

Page 70: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

72

Switch statement Software engineers often confronted with programming tasks

where required action depends on the values of integer expressions The if-else-if construct can be used

Separately compare the desired expression to a particular value If the expression and value are equal, then perform

the appropriate action

Because such programming tasks occur frequently Java includes a switch statement

The task is often more readable with the switch then with the if-else-if

Page 71: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

73

A switch statement exampleif (a == ‘0’)

System.out.println (“zero”);else if (a == ‘1’)

System.out.println (“one”);else if (a == ‘2’)

System.out.println (“two”);else if (a == ‘3’)

System.out.println (“three”);else if (a == ‘4’)

System.out.println (“four”);else

System.out.println (“five+”);

switch (a) {case ‘0’:

System.out.println (“zero”);break;

case ‘1’:System.out.println (“one”);break;

case ‘2’:System.out.println (“two”);break;

case ‘3’:

System.out.println (“three”);break;

case ‘4’:

System.out.println (“four”);break;

default:System.out.println (“five+”);break;

}

Page 72: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

75

Switch statement

switch ( SwitchExpression ) {

case CaseExpression1 :Action1 ;

case CaseExpression2 :Action2 ;

...

case CaseExpressionn :Actionn;

default :Actionn+1 ;

}

Constantintegral

expressionJavastatements

Integral expression tobe matched with a case

expression

Page 73: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

76

Testing for vowel-nessswitch (ch) {

case 'a': case 'A':case 'e':case 'E':case 'i':case 'I':case 'o':case 'O':case 'u':case 'U':

System.out.println("vowel“);break;

default: System.out.println("not a vowel“);

}

Page 74: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

77

Testing for vowel-ness

switch (ch) {case 'a': case 'A':case 'e': case 'E':case 'i': case 'I':case 'o': case 'O':case 'u': case 'U':

System.out.println("vowel“);break;

default: System.out.println("not a vowel“);

}

The break causes an exiting of the switch

Handles all of the other cases

Page 75: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

78

A better way to format that switch statement

switch (ch) {case 'a':

// FALL THRUcase 'A':

// FALL THRUcase 'e':

// FALL THRUcase 'E':

// FALL THRUcase 'i':

// FALL THRUcase 'I':

// FALL THRU

...

Page 76: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

79

Processing a request

System.out.print("Enter a number: ");int n1 = stdin.nextInt();

System.out.print("Enter another number: ");int n2 = stdin.nextInt();

System.out.print("Enter desired operator: ");char operator = stdin.nextLine().charAt(0);

switch (operator) {case '+' : System.out.println((n1 + n2)); break;case '-' : System.out.println(n1 - n2); break;case '*' : System.out.println(n1 * n2); break;case '/' : System.out.println(n1 / n2); break;default: System.out.println(“Illegal request“);

}

Page 77: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

80

How well do you feel you understand the swtich statement?

1. Very well! This stuff is easy!

2. Fairly well – with a little review, I’ll be good

3. Okay. It’s not great, but it’s not horrible, either

4. Not well. I’m kinda confused

5. Not at all. I’m soooooo lost

Page 78: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

8181

Biggest software errorsBiggest software errors Ariane 5 rocket explosion (1996)Ariane 5 rocket explosion (1996)

– Due to loss of precision converting 64-bit double to 16-bit intDue to loss of precision converting 64-bit double to 16-bit int Pentium division error (1994)Pentium division error (1994)

– Due to incomplete look-up table (like an array)Due to incomplete look-up table (like an array) Patriot-Scud missile error (1991)Patriot-Scud missile error (1991)

– Rounding error on the timeRounding error on the time– The missile did not intercept an incoming Scud missile, leaving 28 dead and 98 The missile did not intercept an incoming Scud missile, leaving 28 dead and 98

woundedwounded Mars Climate Orbiter (1999)Mars Climate Orbiter (1999)

– Onboard used metric units; ground computer used English unitsOnboard used metric units; ground computer used English units AT&T long distance (1990)AT&T long distance (1990)

– Wrong break statement in C codeWrong break statement in C code Therac-25, X-ray (1975-1987)Therac-25, X-ray (1975-1987)

– Badly designed software led to radiation overdose in chemotherapy patientsBadly designed software led to radiation overdose in chemotherapy patients NE US power blackout (2003)NE US power blackout (2003)

– Flaw in GE software contributed to itFlaw in GE software contributed to it

References: References: http://www5.in.tum.de/~huckle/bugse.html, , http://en.wikipedia.org/wiki/Computer_bug, , http://www.cs.tau.ac.il/~nachumd/verify/horror.html

Page 79: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

8282

Object equalityObject equality

Page 80: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

83

Testing variables for equality Consider

System.out.print("Enter an integer number: ");int n1 = stdin.nextInt();System.out.print("Enter another integer number: ");int n2 = stdin.nextInt();

if (n1 == n2) {System.out.println("Same");

}else {

System.out.println(“Different");}

What is the output if the user enters 88 and 3?

What is the output if the user enters 88 both times?

Page 81: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

8484

Program DemoProgram Demo

IntEqualityIntEquality

Page 82: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

85

Testing objects for equality Consider

String s1 = “pastel”;String s2 = s1;

if (s1 == s2) {System.out.println("Same");

}else {

System.out.println("Different");}

Page 83: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

86

Testing objects for equality

Memory looks like

The comparison is between the references!

Thus, s1 and s2 are the same (they refer to the same object)

"pastel"s1

s2

Page 84: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

87

Testing objects for equality Consider

System.out.print("Enter a string: ");String s1 = stdin.nextLine();System.out.print("Enter another string: ");String s2 = stdin.nextLine();

if (s1 == s2) {System.out.println("Same");

}else {

System.out.println("Different");}

What is the output if the user enters "pastel" both times?

Page 85: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

8888

Program DemoProgram Demo

StringEqualityStringEquality

Page 86: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

89

Testing objects for equality When it is executed

System.out.print("Enter a string: ");String s1 = stdin.nextLine();System.out.print("Enter another string: ");String s2 = stdin.nextLine();

Memory looks like

As a result no matter what is entered s1 and s2 are not the same They refer to different objects

"pastel"s1

"pastel"s2

Page 87: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

90

Comparing strings for equality Consider:

String u = new String("hello");String v = new String("hello");System.out.println (u == v);

What gets printed? false

Consider:String s = "hello";String t = "hello";System.out.println (s == t);

What gets printed? true Huh?

These aren’t the exact same thing

Page 88: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

9191

Program DemoProgram Demo

StringEquality2StringEquality2

Page 89: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

92

Testing operators for equality Consider

System.out.print("Enter a string: ");String s1 = stdin.nextLine();System.out.print("Enter another string: ");String s2 = stdin.nextLine();

if (s1.equals(s2)) {System.out.println("Same");

}else {

System.out.println("Different");}

Tests whether s1 and s2 represent the same object

Most classes have a method equals(). It compares the objects themselves, not the references.

Page 90: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

9393

Today’s demotivatorsToday’s demotivators

Page 91: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

9494

Short-circuit evaluationShort-circuit evaluation

Page 92: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

95

Short-circuit evaluation The value of a logical expression can be known before all the

operands have been considered If left operand of && is false, then the value must be false If left operand of || is true, then the value must be true

Java uses these properties to make logical operations efficient Evaluates left operand before it evaluates right operand If the operator value is determined from the left operand,

then the right operand is not evaluated The operation is short-circuited

Page 93: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

96

Short-circuit evaluation Short-circuit evaluation is useful when some property must

be true for some other expression to be evaluated

Suppose you are interested in knowing whether scoreSum divided by nbrScores is greater than value The condition can be evaluated only if nbrScores is

nonzero

The following expression correctly represents the condition (nbrScores != 0) && ((scoreSum / nbrScores) > value)

Page 94: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

97

Short-circuit evaluation Assume we have a returnsFalse()

method from a ‘foo’ object It returns false And it prints “returnsFalse() called”

And a returnsTrue() method

Consider:if ( foo.returnsFalse() && foo.returnsTrue() ) {}if ( foo.returnsTrue() && foo.returnsFalse() ) {}if ( foo.returnsFalse() || foo.returnsTrue() ) {}if ( foo.returnsTrue() || foo.returnsFalse() ) {}

returnsFalse() called

returnsTrue() calledreturnsFalse() called

returnsFalse() calledreturnsTrue() called

returnsTrue() called

Output

Page 95: 1 Decisions, decisions, decisions Chapter 4 Trey Kirk

98

How well do you feel you understand decision statements (ifs, switches) in Java?

1. Very well! This stuff is easy!

2. Fairly well – with a little review, I’ll be good

3. Okay. It’s not great, but it’s not horrible, either

4. Not well. I’m kinda confused

5. Not at all. I’m soooooo lost