26
Chapter 4 Conditional Statements

Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Embed Size (px)

Citation preview

Page 1: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Chapter 4

Conditional Statements

Page 2: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

A Programmer's Lament

I really hate this damned machine;I wish that they would sell itIt never does quite what I wantbut only what I tell it.

Dennie L Van Tassel,  The Compleat Computer

Page 3: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Conditional Statements

• Consider:if the mouse location is contained

in the rectangle, display message “success”

• Some programming constructs can choose between blocks of code to execute

Page 4: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

A Vote Counting Example

Complete source code

Page 5: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Code to Update Votes:

// Update votes and display vote countspublic void onMouseClick( Location point ) {

if ( point.getX() < MID_X ) { countA++;infoA.setText( "So far there are " + countA + " vote(s) for A." );

} else { countB++;infoB.setText( "So far there are " + countB + " vote(s) for B." );

}}

Page 6: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Syntax of the if Statement• The condition is evaluated. If true, the bracketed code following if is

executed; otherwise, the bracketed code after else is executed

if (condition) {//do something

} else {//do something else

}

• The else part can be omitted

if (condition) {//do something here

}

Page 7: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

ifif-else

Page 8: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

if Statement and 2D Objects

To check if the mouse is within a 2D object:public void onMouseClick ( Location point ) {

if ( anObject.contains ( point ) ) {

//do something here

}

}

Page 9: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Comparison Operators

Operator Description

> Greater than

< Less than

== Equal to

<= Less than or equal to

>= Greater than or equal to

!= Not equal to

Page 10: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

• ExamplesIf a=25, b=30

a<b evaluates to true

a<=b evaluates to true

a==b evaluates to false

a!=b evaluates to true

a>b evaluates to false

a>=b evaluates to false

4 < 3 false

2 == 2 true

Since these expressions are evaluated to either true or false, they are called boolean expressions

Page 11: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

The boolean Data Type

• A data type that has only two values: true or false

• Can be declared with the word boolean

Ex: boolean a=true; //holds the value true

boolean b=c>d; //holds the result of c > d

boolean k; //creates k, which can take on true or false

Page 12: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Dragging a Box//boolean variable to determine whether the box is grabbed

private boolean boxGrabbed;

// Save starting point and whether point was in box

public void onMousePress( Location point ) {

lastPoint = point;

boxGrabbed = box.contains( point );

}

// if mouse is in box, then drag the box

public void onMouseDrag( Location point ) {

if ( boxGrabbed ) {

box.move( point.getX() - lastPoint.getX(),

point.getY() - lastPoint.getY() );

lastPoint = point;

}

} Complete source code

Page 13: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

More Uses of The if else Statement• Picks one choice among manyEX: Converting a score into a letter grade

if ( score >= 90 ) { gradeDisplay.setText( "The grade is A" );

} else if ( score >= 80 ) { gradeDisplay.setText( "The grade is B" );

} else if ( score >= 70 ) { gradeDisplay.setText( "The grade is C" );

} else { gradeDisplay.setText( "No credit is given");

}

Page 14: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Combining Multiple Conditionals

• && (and) combines adjoining conditions in a way that the final result will be true only if all are true

Ex: a && b && cis true if a,b,c are true

• || (or) combines adjoining conditions in a way that if any of them is true, the final result will be true

Ex: a || b || c

is true if any of a, b, c, is true

• ! (not) negates the value of a boolean (true false)

Page 15: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Logical Operators

• && (and) – true only when both sides are true

• || (or) – true whenever one or both are true

• ! (not)– makes false -> true and true -> false

Page 16: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Examples using &&

• broom.overlaps(goal) && box.overlaps(goal)– The broom overlaps both goals at same time

• (3<4) && ( 4<5) true

• (3>4) && ( 4<5) false

• (3>4) && ( 4>5) false

Page 17: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Examples Using ||

• box.overlaps( goal1 ) || box.overlaps(goal2)– box overlaps either goal1 or goal2

• (3<4) || ( 4<5) true

• (3>4) || ( 4<5) true

• (3>4) || ( 4>5) false

Page 18: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Examples using !

• ! broom.overlaps(goal)– The broom does not overlap the goal

• !(3>4) !false = true

Page 19: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Order of Operations for Boolean Logic

1. Parentheses ( )

2. Relational ops <,>,<=,>=,!=,==

3. !

4. &&

5. ||

This order is applied in processing complex expressions

Parts at the same level are handled left to right

Page 20: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

ExampleEXAMPLE: suppose

x=3

y=10

z=20

Evaluate

!( x<y ) || (z > x)

! (3<10) || (20 > 3) first, plug in values for variables

! true || true second, evaluate parentheses

false || true third, apply ! to true to get false

true last, or the false with true to get true

Page 21: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Processing a Big Logic Expression

(3 < 10) && (4>10) || (3 == 3) || (3 > 6) && (4 == 2)

T && F || T || F && F

F || T || F

T || F

T

Page 22: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Random Number Generator

• private RandomIntGenerator rand;– rand is an object that spits out random values

• rand = new RandomIntGenerator(1,100);– Makes rand refer to a new RIG

– Will produce values from 1 to 100

• rand.nextValue();– Gets a new random number from rand

• score = rand.nextValue();– Stores the random value in an integer score

• box.moveTo(rand.nextValue(), rand.nextValue());

– Moves box to a new random location

Page 23: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

The Craps Example• A block of code that uses || (or) to determine whether the player wins a game of

Craps

if ( roll == 7 || roll == 11 ) { // 7 or 11 wins on first throwstatus.setText( "You win!" );

} else if ( roll == 2 || roll == 3 || roll == 12 ) { // 2, 3, or 12 losesstatus.setText( "You lose!" );

} else { // Set roll to be the point to be madestatus.setText( "Try for your point!" );point = roll;…

}

Complete source code

Page 24: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Nesting

• Suppose we want to decide among several choices based on several conditions, such as shown by the table:

• To do this, we use conditionals inside a conditional. This is called nesting.

Sunny Not sunny

Rich Outdoor Concert Indoor Concert

Not Rich Ultimate Frisbee Watch TV

Page 25: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Nesting Example

if ( ( sunny ) && (rich)) { activityDisplay.setText( "outdoor concert" );

} else if ((sunny) && (!rich) ){ // not richactivityDisplay.setText( "play ultimate" );

}else { // not sunny

if ( rich ) { activityDisplay.setText( "indoor concert" );

} else { // not richactivityDisplay.setText( "watch TV" );

}}

Page 26: Chapter 4 Conditional Statements. A Programmer's Lament I really hate this damned machine; I wish that they would sell it It never does quite what I want

Creating a Game of CrapsBy adding an outer conditional, we can effectively determine whether the player wins:

if ( newGame ) { //Starting a new gameif ( roll == 7 || roll == 11 ) { // 7 or 11 wins on first throw

status.setText( "You win!" );} else if ( roll == 2 || roll == 3 || roll == 12 ) { // 2, 3, or 12 loses

status.setText( "You lose!" );} else { // Set roll to be the point to be made

status.setText( "Try for your point!" );point = roll;newGame = false; // no longer a new game

}}

Complete source code