91
Programming and Problem Solving With Java Copyright 1999, James M. Slack Chapter 4 Selection Control Statements The if Statement More About Selection Errors Testing and Debugging Artificial Intelligence

Chapter 4 Selection Control Statements

Embed Size (px)

DESCRIPTION

Chapter 4 Selection Control Statements. The if Statement More About Selection Errors Testing and Debugging Artificial Intelligence. The if Statement. Making a decision. The if Statement. The if Statement. Relational Operators with if. Relational operator: compares two values - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 4 Selection Control Statements

Programming and Problem SolvingWith Java

Copyright 1999, James M. Slack

Chapter 4Selection Control StatementsThe if StatementMore About SelectionErrorsTesting and DebuggingArtificial Intelligence

Page 2: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 2

The if StatementMaking a decision

Page 3: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 3

The if StatementQuick Reference: if statement

Syntax:

if (condition){ if-body}

Example:

if (age < 16){ System.out.println("Too young to drive");}

Usage:

Use the if statement when you want the computer to execute another statementonly when a certain if-condition is true.

Action:

The computer evaluates the condition. If the condition is true, the computerexecutes the statements in the if-body, then continues with the statement afterthe if-body. If the condition is false, the computer skips the if-body andcontinues with the statement after if-body.

Page 4: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 4

The if Statement

System.out.println("Too young to drive");

if (age < 16){ System.out.println("Too young to drive");}

Is age lessthan 16?

Yes

Flow ofcontrol

Next statement inprogram

No

Page 5: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 5

Relational Operators with ifRelational operator: compares two valuesRelational operators in Java

Notice!! Test for equality is ==

Operator Description Example

== equal to if (myTurtle.atColumn() == 359) ...

!= not equal to if (myTurtle.direction() != 0) ...

> greater than if (myTurtle.atRow() > 700) ...

< less than if (total < 10.0) ...

>= greater than or equal to if (value >= 35) ...

<= less than or equal to if (age <= 20) ...

Page 6: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 6

Turtle Graphics Constants

Method Description Example

MAX_COLUMN The largest column number(1199).

System.out.print(Turtle.MAX_COLUMN);

MAX_ROW The largest row number (1199). System.out.print(Turtle.MAN_ROW);

MIN_COLUMN The smallest column number(0).

System.out.print(Turtle.MIN_COLUMN);

MIN_ROW The smallest row number (0). System.out.print(Turtle.MIN_ROW);

Makes if statements more readableif (Turtle.MAX_ROW - myTurtle.atRow() < 10){ myTurtle.turnRight(180);}

Page 7: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 7

Methods that Provide Turtle InfoMethod Description Example

atColumn() Absolute column of turtle if (myTurtle.atColumn() > 500){ myTurtle.move(200);}

atRow() Absolute row of turtle if (myTurtle.atRow() > 500){ myTurtle.move(200);}

direction() Absolute direction of turtle if (myTurtle.direction() < 180){ myTurtle.turnRight(90);}

isPenDown() True if turtle's pen isdown.

if (myTurtle.isPenDown()){ myTurtle.penUp();}

maxMove() Distance to the wall theturtle is facing

if (myTurtle.maxMove() < 200){ myTurtle.turnRight(180);}

Page 8: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 8

Relational Operands: PrimitivesCompare two primitive values

Value of type byte, int, short, long, float, …Relational operator tells how the values compare

Exampleif (3 < 5) …

3 and 5 are integers3 is less than 5, so condition is true

Page 9: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 9

Relational Operands: ObjectsCompare two objects

Object of class String, Turtle, …Relational operator compares objects, not their valuesExample

String message1 = "Hi there";String message2 = "Hi " + "there";

if (message1 == message2){ System.out.println("The messages are the same");}

if (message1 != message2){ System.out.println("The messages are different");}

message1 and message2 refer to different objects

false

true displays

message1

message2

Hi there

Hi there

Page 10: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 10

String Methods: compareTo()a.compareTo(b) returns

0 if a == b< 0 if a < b> 0 if a > b

ExampleString a = " Hi there";String b = " HI THERE";

if (a.compareTo(b) == 0){ System.out.println("Yes");}

No output: a and b have different values

Page 11: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 11

String Methods: endsWith()a.endsWith(b) returns

true if the last characters in a are b false otherwise

ExampleString a = " Hi there";if(a.endsWith("ere")){ System.out.println("Yes");}

Displays Yes: the last threecharacters of a are "ere"

Page 12: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 12

Strings: equals()a.equals(b) returns

true if the values of a and b are the same false otherwise

ExampleString a = " Hi there";String b = " HI THERE";

if(a.equals(b)){ System.out.println("Yes");}

Displays nothing: a and b have the different values (upper and lower case letters are different characters)

Page 13: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 13

Strings: equalsIgnoreCase()a.equalsIgnoreCase(b) returns

true if the values of a and b are the same, regardless of upper and lower case differences

false otherwiseExample

String a = " Hi there";String b = " HI THERE";

if(a.equalsIgnoreCase(b)){ System.out.println("Yes");}

Displays Yes: a and b have the same values (ignoring case)

Page 14: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 14

String Methods: startsWith()a.startsWith(b) returns

true if the first characters in a are b false otherwise

ExampleString a = " Hi there";if(a.startsWith(" Hi")){ System.out.println("Yes");}

Displays Yes: the first four characters of a are " Hi" (two spaces at beginning)

Page 15: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 15

The char TypeUsed for storing single charactersLiteral values surrounded by single quotes

'A' 'a' '?' '9' '!'

Displaying a characterSystem.out.println('B');

Upper and lower case characters are different 'a' != 'A'

Page 16: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 16

The if Statement: charchar choice;int firstNum, secondNum;

// Ask user for first numberfirstNum = Keyboard.readInt("Enter first integer: ");

// Ask user for second numbersecondNum = Keyboard.readInt("Enter second integer: ");

// Ask user which operation to usechoice = Keyboard.readChar("Enter A to add the numbers, " + "M to multiply them: ");

// Display the resultsif (choice == 'A'){ System.out.println("The sum is " + (firstNum + secondNum));}if (choice == 'M'){ System.out.println("The product is " + (firstNum * secondNum));}

Enter first integer: 23Enter second integer: 42Enter A to add the numbers, M to multiply them: AThe sum is 65

Page 17: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 17

The readChar() MethodThree ways to use readChar()

No prompt messagechoice = Keyboard.readChar();

Prompting messagechoice = Keyboard.readChar("Enter A to add the numbers, " + "M to multiply them: ");

Prompting message and restricted inputchoice = Keyboard.readChar("Enter A to add the numbers, " + "M to multiply them: ", "AM");

Enter A to add the numbers, M to multiply them: XPlease enter one of these characters: AMEnter A to add the numbers, M to multiply them: GPlease enter one of these characters: AMEnter A to add the numbers, M to multiply them: A

Page 18: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 18

Comparing CharactersComputer

compares Unicode values of characters

if ('A' < 'B') ...

Unicode value of'A' is 65

Unicode value of'B' is 66

'A' < 'B' becomes65 < 66

Code Char Code Char Code Char Code Char Code Char

32 (space) 51 3 70 F 89 Y 108 l

33 ! 52 4 71 G 90 Z 109 m

34 " 53 5 72 H 91 [ 110 n

35 # 54 6 73 I 92 \ 111 o

36 $ 55 7 74 J 93 ] 112 p

37 % 56 8 75 K 94 ^ 113 q

38 & 57 9 76 L 95 _ 114 r

39 ' 58 : 77 M 96 ` 115 s

40 ( 59 ; 78 N 97 a 116 t

41 ) 60 < 79 O 98 b 117 u

42 * 61 = 80 P 99 c 118 v

43 + 62 > 81 Q 100 d 119 w

44 , 63 ? 82 R 101 e 120 x

45 - 64 @ 83 S 102 f 121 y

46 . 65 A 84 T 103 g 122 z

47 / 66 B 85 U 104 h 123 {

48 0 67 C 86 V 105 i 124 |

49 1 68 D 87 W 106 j 125 }

50 2 69 E 88 X 107 k 126 ~

Page 19: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 19

Compound StatementsCompound statement: one or more

statements surrounded by braces{ x++; System.out.print("Hello");}

Compiler treats as a single statementif statement operates on a single statement

if (condition) if (myTurtle.direction() > 180) statement myTurtle.move(100);

No braces!

Page 20: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 20

if with Compound StatementsMust use compound statement if more than one

if (condition) if (myTurtle.direction() > 180){ { statement1 myTurtle.move(100); statement2 myTurtle.turnRight(90);} }

Good programming practice: always use compound statement with ifShows structure more clearlyCan easily add statements to if-bodyAvoid dangling-else problem (coming up

shortly)

Page 21: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 21

Order apple Order orange

Do I want anorange?

No Yes

Eat lunch and dessert

Flow ofcontrol

The else Clauseelse clause an optional

part of if statementComputer executes one

of 2 statementsif (condition){ statements}else{ statements}

If condition is true, execute if-body

Otherwise, else-body

Page 22: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 22

The else Clause

Next statement inprogram

Is y equal to 0?

Flow ofcontrol

if (y == 0){ x++;}else{ x--;}

Subtract 1 from x Add 1 to x

YesNo

Page 23: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 23

The else Clause: turn() Methodturn() method for turtle that turns 0 - 360o

Approach If the angle is 180 or less, do single turnRight().Otherwise, do turnRight(180), then turnRight the rest

// turn: Turn to the right, from 0 to 360 degreespublic void turn(int degrees)throws TurtleException{ if (degrees <= 180) { this.turnRight(degrees); } else { this.turnRight(180); this.turnRight(degrees - 180); }}

Page 24: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 24

Nested if Statements

Order apple Order orange

Do I want anorange?

No Yes

Eat lunch and dessert

Flow ofcontrol

Do I want dessert? YesNo

Go home

Nested decision: Onedecision depends on the result of another

Page 25: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 25

Nested if StatementsExample: Cost of first-class letter

40 cents for first ounce, 30 cents for each additionalMust be between 1 and 11 ounces

After reading weightif (weight > 0) // Outer-if statement{ if (weight <= FIRST_CLASS_LIMIT) // Inner-if statement { costInCents = FIRST_OUNCE_COST + ADDITIONAL_OUNCE_COST * (weight - 1); System.out.println("Cost: " + costInCents + " cents"); } else { System.out.println("Use parcel post or priority mail"); }}else{ System.out.println("ERROR: Weight must be positive");}

Page 26: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 26

Dangling-else ProblemArises only with nested if statements without bracesExample

// For a score less than 70, displays "You need to improve"// For a score greater than 95, displays "Excellent work"// For a score between 70 and 95, displays nothingif (testScore >= 70) // Outer-if statement if (testScore > 95) // Inner-if statement System.out.println("Excellent work!");else System.out.println("You need to improve");

ResultsScore Desired Message Actual Message

Less than 70 You need to improve (No message)

Between 70 and 95(including 70 and 95)

(No message) You need to improve

More than 95 Excellent work! Excellent work!

Page 27: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 27

Dangling-else ProblemWhen compiler finds else clause

"The else always matches the closest, unfinished if statement"

// For a score less than 70, displays "You need to improve"// For a score greater than 95, displays "Excellent work"// For a score between 70 and 95, displays nothingif (testScore >= 70) // Outer-if statement if (testScore > 95) // Inner-if statement System.out.println("Excellent work!");else System.out.println("You need to improve");

Page 28: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 28

Dangling-else Problem

if condition1 if condition2 statement1;else statement2;

The inner if isnested in the

if-body of theouter if

The "danglingelse"

The inner if doesnot have an else

The outer if hasan else

Structure of a dangling else clause

Page 29: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 29

Dangling-else ProblemHow braces

avoid thedangling-elseproblem

if (condition1){ if (condition2) { statement1; }}else{ statement2;}

The elsematches the

outer if

The inner ifis "finished"because thesurroundingbraces make ita completestatement

Page 30: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 30

Multiway Choices

What should Ihave for dessert?

Ice creampie

Pie a lamode

Bananasplit

Apple Orange Cookie

Eatdessert

Flow ofcontrol

Page 31: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 31

Multiway Choices: if-ladderchar grade;

if (score >= 90){ grade = 'A';}else{ if (score >= 80) { grade = 'B'; } else { if (score >= 70) { grade = 'C'; } else { if (score >= 60) { grade = 'D'; } else { grade = 'F'; } } }}

char grade;

if (score >= 90){ grade = 'A';}else if (score >= 80){ grade = 'B';}else if (score >= 70){ grade = 'C';}else if (score >= 60){ grade = 'D';}else{ grade = 'F';}

rewritenested if

as if-ladder

Nested ifif-ladder

Page 32: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 32

How the if-ladder Works

if (score >= 90){ grade = 'A';}else if (score >= 80){ grade = 'B';}else if (score >= 70){ grade = 'C';}else if (score >= 60){ grade = 'D';}else{ grade = 'F';}

score >= 90?

score >= 80?

score >= 70?

score >= 60?

grade = 'A';

grade = 'B';

grade = 'C';

grade = 'D';

grade = 'F';

Yes

Yes

Yes

Yes

No

No

No

No

Statementsfollowingif-ladder

Flow ofcontrol

Page 33: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 33

Multiway Choices: if-ladderDefault condition: last else in if-ladder

· OptionalGood idea to have one -- helps catch errors

if (score >= 90){ grade = 'A';}else if (score >= 80){ grade = 'B';}else if (score < 60){ grade = 'F';}else{ System.out.println("Error in assignGrade");}

Missing cases forgrades of C and D

Default conditioncatches the error

Page 34: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 34

General face() MethodTurtle graphics turnRight() -- turns relative degreesNo method to make turtle face absolute directionCan use nested if to write face()

myTurtle.face(122);

Direction of turtle can be anything face(122) makes turtle face 122 degrees

Page 35: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 35

General face() MethodThree cases to consider

0o

90 o

180 o

270 o

Direction turtle isfacing now

Direction we wantturtle to face

0o

90 o

180 o

270 o

Direction turtle isfacing now

Direction we wantturtle to face

(b) The turtlecrosses 0degrees

(a) The turtledoesn't cross 0

degrees

(c) The turtlemay already be

facing the desireddirection

Page 36: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 36

General face() MethodThree cases need nested if statementFirst version of face()

Handle case where turtle already facing desired direction// face: Faces the turtle an absolute direction,// from 1 to 360 degreespublic void face(int degrees)throws TurtleException{ // Make sure the turtle is not already facing the desired // direction if (this.direction() != degrees) { // Handle the other two cases here }}

Must distinguish between the remaining two cases

Page 37: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 37

General face() MethodDistinguish between two cases

0o

90 o

180 o

270 o

Direction turtle isfacing now

Direction we wantturtle to face

0o

90 o

180 o

270 o

Direction turtle isfacing now

Direction we wantturtle to face

(b) The turtlecrosses 0degrees

(a) The turtledoesn't cross 0

degrees

Current Direction < Desired Direction

Current Direction > Desired Direction

Page 38: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 38

General face() MethodDoesn't cross 0, current direction < desiredSecond version of face()

// face: Faces the turtle an absolute direction,// from 1 to 360 degreespublic void face(int degrees)throws TurtleException{ // Make sure the turtle is not already facing the desired // direction if (this.direction() != degrees) { if (this.direction() < degrees)

{ // The turtle doesn't cross 0 this.turn(degrees - this.direction()); }

else { // The turtle crosses 0 } }}

0o

90 o

180 o

270 o

Direction turtle isfacing now

Direction we wantturtle to face

Page 39: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 39

General face() MethodCrosses 0, current direction > desiredTurn in two steps

0o

90 o

180 o

270 o

Direction turtle isfacing now

Direction we wantturtle to face

Step 1:this.turn(360 - this.direction())

Step 2:this.turn(degrees)

Page 40: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 40

General face() MethodFinal version of face()

// face: Faces the turtle an absolute direction,// from 1 to 360 degreespublic void face(int degrees)throws TurtleException{ // Make sure the turtle is not already facing the desired // direction if (this.direction() != degrees) { if (this.direction() < degrees) { // The turtle doesn't cross 0 this.turn(degrees - this.direction()); } else { // The turtle crosses 0

this.turn(360 - this.direction() + degrees); } }}

Page 41: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 41

goPosition(): Example of ifTurtle graphics move() -- moves relative distanceNo method to make turtle move to absolute positionCan use nested if to write goPosition()

myTurtle.goPosition(10, 20); // row 10, column 20

Turtle can be anywhere on screenWill move to upper left corner

(facing same direction)

Page 42: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 42

goPosition(): Example of ifUse helper methods

moveToRow()moveToColumn();

First version of goPosition()// goPosition: Moves turtle to any absolute position on the// screen, without drawing a line. The// direction and pen status are unchanged.public void goPosition(int row, int column)throws TurtleException{ this.moveToRow(row); this.moveToColumn(column);}

Page 43: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 43

goPosition(): Example of ifWant pen status to be unchangedSecond version of goPosition()

// goPosition: Moves turtle to any absolute position on the// screen, without drawing a line. The// direction and pen status are unchanged.public void goPosition(int row, int column)throws TurtleException{ // Remember previous pen status

boolean penDownAtBeginning = this.isPenDown();

if (this.isPenDown()) { this.penUp(); }

this.moveToRow(row); this.moveToColumn(column);

// Put pen back down if it was down before if (penDownAtBeginning) { this.penDown(); }

}

Page 44: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 44

goPosition(): Example of ifAlso want direction to be unchangedFinal version of goPosition()

// goPosition: Moves turtle to any absolute position on the// screen, without drawing a line. The// direction and pen status are unchanged.public void goPosition(int row, int column)throws TurtleException{ // Remember previous pen status and direction boolean penDownAtBeginning = this.isPenDown();

int previousDirection = this.direction(); if (this.isPenDown())

{ this.penUp(); } this.moveToRow(row); this.moveToColumn(column);

// Put pen back down if it was down before if (penDownAtBeginning) { this.penDown(); }

// Restore previous direction this.face(previousDirection);

}

Page 45: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 45

goPosition(): Example of ifNeed to write moveToRow(), moveToColumn()Three cases in moveToRow()

Desiredrow

Case 1: Turtle isabove desired row

Case 2: Turtle isbelow desired row

Case 3: Turtle ison desired row

Page 46: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 46

goPosition(): Example of ifmoveToRow(): Do nothing if already on desired rowFirst version of moveToRow()

// moveToRow: Moves the turtle to an absolute row number.// Pen must be up beforehand, and is left// up afterward. The turtle's direction is// changed.// (This is a private method.)private void moveToRow(int row)throws TurtleException{ // Make sure not on desired row if (row != this.atRow()) { // Handle the other two cases }}

Page 47: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 47

goPosition(): Example of ifmoveToRow(): Use atRow() to tell direction to moveSecond version of moveToRow()

// moveToRow: Moves the turtle to an absolute row number.// Pen must be up beforehand, and is left// up afterward. The turtle's direction is// changed.// (This is a private method.)private void moveToRow(int row)throws TurtleException{ // Make sure not on desired row if (row != this.atRow()) { // Handle the other two cases

if (row < this.atRow()) { // Turtle below desired row } else { // Turtle above desired row }

}}

Page 48: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 48

goPosition(): Example of ifmovePosition(): turtle is below desired row

Use face() to turn turtle straight upMove from current row to desired row

this.face(0);this.move(this.atRow() - row);

movePosition(): turtle is above desired rowUse face() to turn turtle straight downMove from current row to desired row

this.face(180);this.move(row - this.atRow());

Desired row

Page 49: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 49

goPosition(): Example of ifFinal version of moveToRow()

// moveToRow: Moves the turtle to an absolute row number.// Pen must be up beforehand, and is left// up afterward. The turtle's direction is// changed.// (This is a private method.)private void moveToRow(int row)throws TurtleException{ // Make sure not on desired row if (row != this.atRow()) { // Handle the other two cases if (row < this.atRow()) { // Turtle below desired row

this.face(0); this.move(this.atRow() - row);

} else { // Turtle above desired row

this.face(180); this.move(row - this.atRow());

} }}

Page 50: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 50

Boolean Operators & ExpressionsDecisions often based on more than one factor

I will buy a new shirt if I like it AND it costs less than $25. I will study in my room tonight if it's quiet there OR the

library is closed.Compound conditions in English

condition1 AND condition2

condition1 OR condition2

NOT condition

Page 51: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 51

Boolean Operators & ExpressionsThe && (And) Operator

condition1 && condition2

True when both conditions are trueExample

if (total >= 100 && total <= 500){ System.out.println("Error");}

Displays error message if total between 100 and 500

Truth tableTells result of any combination

of true and false conditions

a b a && b

true true true

true false false

false true false

false false false

Page 52: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 52

Boolean Operators & ExpressionsThe || (Or) Operator

condition1 || condition2

True when either condition is true (or both)Example

if (prizeNumber == 1234 || prizeNumber == 4321){ System.out.println("You won!");}

Displays message if prizeNumber is 1234 or 4321

a b a || b

true true true

true false true

false true true

false false false

Page 53: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 53

Boolean Operators & ExpressionsThe ! (Not) Operator

!conditionTrue when condition is false; false when condition is true

Good use: reverse a boolean methodExample with turtle graphics

if (!myTurtle.isPenDown()){

myTurtle.penDown();}

Example with charactersif (!Character.isDigit(character)){ System.out.println("Not a digit");}

a !a

true false

false true

Page 54: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 54

Boolean Operators & ExpressionsShort-circuit Evaluation: Stop evaluating ASAP

Example with &&

if (3 > 4 && x + y * z - 5 / 2.3 * 4 == 3.625){ System.out.println("Yes");}

Example with ||

if (3 < 4 || x + y * z - 5 / 2.3 * 4 == 3.625){ System.out.println("Yes");}

Evaluate Ignore

Evaluate Ignore

Page 55: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 55

Boolean Operators & ExpressionsShortcuts that don't work

Shortcut Should beif (100 < total < 500){ System.out.println("Error");}

if (100 < total && total < 500){ System.out.println("Error");}

if (prizeNumber == 1234 || 4321){ System.out.println("You won!");}

if (prizeNumber == 1234 || prizeNumber == 4321){ System.out.println("You won!");}

if (total > 100 && < 500){ System.out.println("Error");}

if (total > 100 && total < 500){ System.out.println("Error");}

Page 56: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 56

Boolean Operators & ExpressionsPrecedence Rules

! very high&& and || after relational&& before ||

Examplesif (!50 <= 100)...if (x < y && y < z || z == 0)...if (myTurtle.atRow() > 10|| myTurtle.atRow() < 40 && myTurtle.atColumn() > 5)

Precedence Operation Associativity

Highest () N/A

! right

*, /, % left

+, - left

<, <=, >,>=

left

==, != left

&& left

|| left

Lowest = right

Page 57: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 57

Boolean Operators & ExpressionsStyle Guidelines

Avoid the ! operator, except when reversing a the result of a Boolean variable or method.

Try to use no more than two or three Boolean operators in any expression.

When you use more than one Booleanoperator in a single expression, use parentheses to make the expression clearer.

Page 58: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 58

Boolean Operators & ExpressionsDeMorgan's Laws

not (a and b) not a or not bnot (a or b) not a and not b

Use to distribute not over and or orExample

"It's not both warm and sunny today."

"It's not warm or not sunny today."

a b

Page 59: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 59!

Boolean Operators & ExpressionsTo avoid ! operator

Use DeMorgan's Lawsif (!(a > b && c <= d)) ...

rewrite as

if (!(a > b) || !(c <= d)) ...

Use opposite relational operatorsif (!(a > b) || !(c <= d)) ...

rewrite as

if (a <= b || c > d) ...

Operator Opposite

== !=

> <=

< >=

Page 60: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 60

The switch StatementAnother multiway selectionValue of expresssion determines which statements

executed switch (choice) { case 1: System.out.println(x + y); break; case 2: System.out.println(x * y); break; case 3: System.out.println(x - y); break; default: System.out.println("Invalid"); break;}

Page 61: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 61

The switch Statement

choice == 1?

choice == 2?

choice == 3?

System.out.println(x + y);

System.out.println(x * y);

System.out.println(x - y);

System.out.println("Invalid");

Yes

Yes

Yes

No

No

No

Statementsfollowingswitch

Flow ofcontrol

break;

switch (choice) { case 1: System.out.println(x + y); break; case 2: System.out.println(x * y); break; case 3: System.out.println(x - y); break; default: System.out.println("Invalid"); break; }

break;

break;

break;

Page 62: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 62

The switch StatementRestrictions on use

Expression (and all case values) must be integer or character

Each case is single literal or constantCases are distinct

More than one case value per statement groupswitch (choiceCharacter){ case 'A': // First style case 'a': System.out.println(x + y); break; case 'M': case 'm': // Second style System.out.println(x * y); break;}

Page 63: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 63

The switch StatementChoosing between if and switch

if: execute an optional group of statements

if-else: execute one of two groups of statements switch: execute one of several groups of statements,

based on integer-valued expressionnested-if: execute one of several groups of statements,

based on arbitrary conditionsNested-if is most general selection statement in

Javaswitch is easier to read than nested if

Page 64: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 64

ErrorsError: mistake in the program

Sometimes called a bugAlmost always the fault of the programmerDebugging: elimination of errors

Kinds of errorsCompile-timeRun-timeLogical

Page 65: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 65

Errors: Compile-timeCompiler finds compile-time errors

// Contains a compile-time error

public class Welcome{ System.out.println("Welcome to"); System.out.println("Java programming!");}

Error messageWelcome.java:5: Type expected. System.out.println("Welcome to"); ^1 error

Mistake in the use of the Java languageSimilar to spelling error in English

Page 66: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 66

Errors: Compile-timeCommon compile-time errors

Leaving out a keywordPutting a keyword where it doesn't belongLeaving out a semicolon, comma, parenthesis or bracketMisspelling a keyword or identifier

Easiest kind of error to fixTwo kinds of compile-time error

Syntax: error in form or structureif (amount == 3 || 6) ... // Invalid expression

Semantic: error in meaningint intVariable = 3;System.out.println(floatVariable); // Unknown variable

Page 67: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 67

Errors: Run-timeComputer finds when it runs the program

import Keyboard;public class DivisionInto100{ public static void main(String[] args) throws java.io.IOException { int dividend, quotient;

// Get the dividend from the user dividend = Keyboard.readInt("Enter the dividend: ");

// Divide the dividend into 100 quotient = 100 / dividend;

// Display the quotient System.out.println(quotient); }}

Run programEnter the dividend: 0java.lang.ArithmeticException: / by zero at DivisionInto100.main(DivisionInto100.java)

Page 68: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 68

Errors: Run-timeComputer can't follow a program instruction "Crash": when a program stops with a run-time

errorHarder to fix than compile-time

Computer doesn't give the statement, just the methodActual error may be much earlier in the program

Page 69: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 69

Errors: LogicalProgram compiles and runs, but output is wrong

// Display the area of a rectangle

import Keyboard;

public class LogicalError{ public static void main(String[] args) throws java.io.IOException { int length, height; length = Keyboard.readInt("Enter the length: "); height = Keyboard.readInt("Enter the height: ");

System.out.println("The area is " + (length + height)); }}

Run programEnter the length: 3Enter the height: 4The area is 7

Page 70: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 70

Errors: LogicalComputer doesn't find the error

Up to programmer or user to notice something is wrongNo help from the computer in finding the cause

Hardest error to fixAvoid logical errors!Some features of Java help

•All variables must be defined•All variables and parameters must have a type•All variables must be initialized before use•Objects and object-orientation

Best way to avoid: careful planning and design

Page 71: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 71

Testing and Debugging ProgramsTesting vs. debugging

Test: run with sample data to uncover errorsDebug: find the cause of a known error

Ideal testing strategy:Run program using all possible inputsCompare actual outputs to expected outputs

Problem: too many inputsProgram asks user for one integer: 4,294,967,296 inputsProgram asks user for two

integers:18,446,744,073,709,551,616 inputsMost programs require more input than this

Page 72: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 72

Testing and Debugging ProgramsBlack-box Testing

Treat program as "black box"Can only see inputs and outputsDon't look at the codeBase test data on specifications:

what the program is supposed to do

Program to double input

Test data = 2 Result = 4 ok

Page 73: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 73

Testing and Debugging ProgramsBlack-box Testing

Too many inputs to test allUse equivalence testing and boundary analysis

Group input values into equivalence classesEquivalence class: input values the

program should treat the sameBased on program's specificationsA few input values from each

equivalence class should find almost 100% of errorsCan design test cases before writing code

Common practice in industry

Page 74: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 74

Testing and Debugging ProgramsBlack-box Testing Example

The program reads a test score as a single integer, and produces a letter grade as output. If the score is between 90 and 100 (inclusive), the program should display the grade A. If the score is between 80 and 89 (inclusive), the program should display the grade B. If the score is between 70 and 79 (inclusive), the program should display the grade C. If the score is between 60 and 69 (inclusive), the program should display the grade D. If the score is between 0 and 59 (inclusive), the program should display the grade F. The program should display an error message for any other score.

Equivalence classes

0 10 20 30 40 50 60 70 80 90 100

60 to 69

70 to 79

80 to 89

90 to 100

over 100

0 to 59

less than 0

Page 75: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 75

Testing and Debugging ProgramsBoundary value

Values on and near boundary between equivalence classes

Choose typical value for each equivalence class, and three boundary values for each boundary

Equivalence Class

Scores greater than 100

Scores between 90 and 100

Scores between 80 and 89

Scores between 70 and 79

Scores between 60 and 69

Scores between 0 and 59

Scores less than 0

SampleValue

150

95

85

75

65

30

-50

BoundaryValue

100

90

80

70

60

0

Just AboveBoundary Value

101

91

81

71

61

1

Just BelowBoundary Value

99

89

79

69

59

-1

Page 76: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 76

Testing and Debugging ProgramsGlass-box Testing

Base test data on the codePath coverage

Test every possible pathMost programs have too

many paths to testOne if-else statement: 2 paths20 if-else statements: > 1 million pathsPath coverage is not practical

Statement coverageMake every statement execute at least onceMinimum amount of glass-box testing

Page 77: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 77

Testing and Debugging ProgramsExample

1 // Computes grades. (Wrong) 2 // This program reads a test score as a single integer, 3 // and produces a letter grade as output. If the score is 4 // between 90 and 100 (inclusive), the program should 5 // display the grade A. If the score is between 80 and 89 6 // (inclusive), the program should display the grade B. If 7 // the score is between 70 and 79 (inclusive), the program 8 // should display the grade C. If the score is between 60 9 // and 69 (inclusive), the program should display the grade10 // D. If the score is between 0 and 59 (inclusive), the11 // program should display the grade F. The program should12 // display an error message for any other score.13 14 import Keyboard;15 16 public class GradeAssignment17 {18 public static void main(String[] args)19 throws java.io.IOException20 {21 int score;22 char grade = ' ';2324 System.out.println("--- Grade Assignment ---");25 score = Keyboard.readInt("Enter score: ");26

Page 78: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 78

Testing and Debugging Programs27 if (score < 0 && score > 100)28 {29 System.out.println("Score must be between 0 and 100");30 }31 else if (score > 90 && score < 100)32 {33 grade = 'A';34 }35 else if (score > 80 && score < 90)36 {37 grade = 'B';38 }39 else if (score > 70 && score < 80)40 {41 grade = 'C';42 }43 else if (score > 60 && score < 70)44 {45 grade = 'D';46 }47 else48 {49 grade = 'F';50 }5152 System.out.println("Computed grade is " + grade);53 }54 }

Page 79: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 79

Testing and Debugging ProgramsValues that make every statement execute once

Enter score: -50Computed grade is F (should see error message)

Enter score: 150Computed grade is F (should see error message)

Enter score: 95Computed grade is A (OK)

Enter score: 85Computed grade is B (OK)

Enter score: 75Computed grade is C (OK)

Enter score: 65Computed grade is D (OK)

Enter score: 50Computed grade is F (OK)

Page 80: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 80

Testing and Debugging ProgramsTest boundary values

Enter score: 0Computed grade is F (OK)

Enter score: 60Computed grade is F (Should be D)

Enter score: 70Computed grade is F (Should be C)

Enter score: 80Computed grade is F (Should be B)

Enter score: 90Computed grade is F (Should be A)

Enter score: 100Computed grade is F (Should be A)

Page 81: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 81

Testing and Debugging ProgramsFixes

27 if (score < 0 || score > 100)28 {29 System.out.println("Score must be between 0 and 100");30 }31 else if (score >= 90 && score <= 100)32 {33 grade = 'A';34 }35 else if (score >= 80 && score < 90)36 {37 grade = 'B';38 }39 else if (score >= 70 && score < 80)40 {41 grade = 'C';42 }43 else if (score >= 60 && score < 70)44 {45 grade = 'D';46 }47 else48 {49 grade = 'F';50 }51

Page 82: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 82

Conditional OperatorQuick Reference: conditional operator

Syntax:

condition ? trueExpression : falseExpression

Example:

grade = (score > 75) ? 'P' : 'F';

Usage:

Use the conditional operator when you want to select between two values inside anexpression. (The parentheses around the condition aren't strictly necessary.However, they make the conditional operator much easier to read.)

Action:

The computer evaluates the condition. If the condition is true, the result of theoperator is trueExpression, otherwise the result is falseExpression.

Page 83: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 83

Artificial IntelligenceStudy of

Making a computer sense its surroundingsAnalyze what it findsReact to its findings

GoalGet computers to do

traditionally humantasks

Page 84: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 84

Artificial IntelligenceTuring Test (Alan Turing, 1950)

Communication onlyby terminal

Person and computertry to convinceinterviewer theyare human

If interviewercan't tell difference,computer hasintelligence

Terminal

Terminal

Computer

Interviewer

Page 85: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 85

Artificial IntelligenceExpert systems

Simulates the reasoning of a human expert with advanced knowledge in a particular area

Used in banking, finance, mining, medicine, geologyNatural language translation

Original goal for artificial intelligenceDifficult problem: incomplete

specifications for natural languagesExample: Time flies like an arrow

Today, computers can translate better, but not completely

Page 86: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 86

Artificial IntelligenceMany expert systems based on production systemsConsist of

collection of states (including start and goal)a collection of productions (rules)a control system

ProductionsTell how to move from one state to another

Control systemDecides which production to use next

Goal of a production systemMove from the start state to the goal state

Page 87: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 87

Artificial IntelligenceHeuristics

"Rules of thumb" - usually true, but not always Used when "best" hard to find, and "good

enough" will doExample: Traveling salesperson problem

Visit a set of cities, each exactly once What is the shortest route?

Only solution: examine all routes 2 x 1032 possible routes Examining 1 billion routes/sec, would take

8.4 x 1013 centuries to examine them allHeuristic to get "good enough" solution

Generate 2 billion random routes, take best of those

Page 88: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 88

Artificial IntelligenceHeuristic for maze

Always examine paths facing goal first

?

?

Start

Finish

Page 89: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 89

Artificial IntelligenceNeural network: Simulation of human brain

Based onneurons

Electricalsignals enterdendrites

Based on inputs,cell may sendsignal to otherneurons throughaxon

Page 90: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 90

Artificial IntelligenceNeural network

Simulated neuron is variable with weighted inputs and one output

If weighted sum of inputs > threshold, fire output value

sum inputs; if (sum > threshold) fire output;

Weight1

Weight2

Weight3

Input 1

Input 2

Input 3

Output

Page 91: Chapter 4 Selection Control Statements

Programming and Problem Solving With Java 91

Artificial IntelligenceSetting up a neural network

Connect neurons in some patternChoose threshold for each neuronChoose weights for each connection

Training the networkGive the network sample input data and expected outputNetwork should "learn" how to process the input to give

the expected outputCommon use: examination of satellite photographs

WeatherVegetationMinerals