Goals
- To review boolean expressions
- To use if statements
- To use switch statements
Resources
http://processing.org/learning/basics/ under Control
A real decision is measured by the fact that you've taken a new action. If there's no action, you haven't truly decided. ~ Tony Robbins
Boolean expressions
Boolean expressions are statements that can one of two values: true or false.
Example:
100 > 50 evaluates to true
Boolean Operators
- ! negation
- && and (conjunction)
- || or (disjunction)
- > greater than
- >= greater than or equals
- <= less than or equals
- < less than
- == equal NOTE the difference between "=", which is the assignment operator
- != not equal
Boolean expressions evaluate to true or false.
if statement
if statements are used to allow your code to follow different paths depending on a condition.
The concept: if the statement is true, do the following bit of code.
Example:
if ( xPos < 100 && xPos > 0)
{
fill(255, 0, 0);
}
The basic pattern:
if( boolean expression ) {
// statements
}
We can add an else. If the thing we wanted to be isn't true, a different set of instructions should be used.
A concrete example:
We have a few more forms:
This shows an else - if, which is basically an else with an if tacked on the end. It requires a second condition to be checked before moving on. In fact, you can chain else - ifs together to check a series of different condition making it work similar to switch.
if - else statements use a boolean expression to determine which path to take through the code.
Nested if statement
Now just to give you more control, you can put an if any place where you can put statements.
One more example:
if statements can be nested to deal with sub conditions.
You can put an if statement anywhere you can put a set of statements: method, loop, if, where ever it is needed.
Switch
switch is a shortcut to using a long series of if-else statements
You can only switch on ints, bytes, shorts, chars. You cannot currently use strings.
To use switch you define a number of cases, and a default case. Once the case has been completed you break out of the block.
The basic form:
A real world example:
You must always have a default case.
You cannot switch on strings.