Chapter 4 & 5 Helper Sheet
Making conditions
boolean is a type that holds true and
false
You can make conditions for if statements and loops
- To have more than one condition: && is AND and || is OR. (Remember
to think out one value that is too small, one that is too big and one that
will be chosen.)
- When your condition tests a string, remember not to use ==. Instead use
the equals method.
- When your condition tests a number, remember to use ==, not =, as = will
actually reset the variable.
- == does not work for Classes (including strings). Instead use x.equals(string
to compare)
If / if else / else
if (condition that evaluates to true or
false)
{
// do something
}
else if (condition that evaluates to true or false) // remember
that everything that met first criteria doesn't get here
{
// do something else
}
.
. // repeat else if as needed
.
else // remember to put no condition
{
// do something
}
If facts:
- else is not needed
- when the condition is met, it executes inside the parentheses and
then goes to the end of the if and continues on down
- You can have ifs inside the brackets for another if
For loop - repeats when you know the number of times to repeat
for (statement to start the loop;
condition that evaluates to true or false; statement to run when the
loop repeats)
{
// do something
}
For facts:
- Don't put a semi-colon at the end of the for condition
- Remember to create the variable used to count the loop with an
int statement somewhere in your program. (either in the for statement
or before it)
- You can add to the counter between the brackets as well.
- After the first time through, the for loop does the "statement to
run when the loop repeats" first, and then checks whether the condition
fails.
- When the condition fails, it goes to the bottom bracket of the
loop and continues on
- You can have loops inside loops
- Stopping when equal to a single number is dangerous - go with
< or > instead when you can.
While loop - repeats until some condition is met
while (condition that evaluates to true or false)
{
// do something
}
- Don't put a semi-colon at the end of the while condition
- Remember to have something inside your loop that will make the
condition fail sometime, or it will NEVER END
- When the condition fails, it goes to the bottom bracket of the
loop and continues on
- The condition is only checked when it gets to the bottom bracket.
Reaching the bottom bracket causes it to go back up to the top and check
- You can have loops inside loops