Week 9 - Decision Statements



Decision Statements

Control Statements

selection or branching (if, switch)

repetition (while, for)

A Boolean expression is an expression that evaluates as true or false.

if..else statement

if (age < 12)

{

ticket_price = 4.50;

output.setText(“”+ticket_price);

}

else

{

ticket_price = 8.50;

output.setText(“”+ticket_price);

}

if statement

ticket_price=8.50;

if (age < 12)

{

ticket_price = 4.50;

}

output.setText(“”+ticket_price);

Execution equivalent

A statement that has the same result.

Compound Statement

A series of statements between braces. Rule: Anywhere a simple statement may be used, a compound

statement may be used. The if statement does not require braces when there is only one simple statement.

Relational and Logical Operators

|OPERATOR |MEANING |

|Relational | |

|< |less than |

| |greater than |

|>= |greater than or equal |

|Logical | |

|! |not |

|&& |and |

||| |or |

Truth table for logical operators

|A |B |A&&B |A||B |!A |

|false |false |false |false |true |

|false |true |false |true |true |

|true |false |false |true |false |

|true |true |true |true |false |

Short-circuit evaluation - if the first expression in a logical and evaluates as false, the second expression is not evaluated. If the first expression in a logical or evaluates as true, the second expression is not evaluated.

Boolean variable

boolean done = false;

Nested if

if (gpa > 2.7)

{

if (SAT > 1000)

{

output.setText("Accepted");

}

else // matches 2nd if statement

{

output.setText("SAT too low");

}

} //end 1st if

else

{

output.setText("No requirements met");

} //end else

Dangling else

an else without a matching if.

Random Numbers

final MAX =

int r = (int) (Math.random() * MAX) + 1; // MAX = largest integer to be generated

The range of random numbers generated is: 1 ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download