Control Structures: if Statements & For Loops
if Statements: One-Way and Two-Way Selection
An if statement runs its body only when a boolean condition is true:
if (joystick.getRawButton(1))
{
intake.spin(0.5);
}
Add an else for a second branch that runs when the condition is false:
if (joystick.getRawButton(1))
{
intake.spin(0.5);
}
else
{
intake.stop();
}
Always use curly braces, even for a single statement — Java doesn't require them, but skipping them is exactly how the classic "which statement is actually inside the if" bug happens.
The Classic = vs. == Mistake
One = assigns a value; two == test whether a value equals something. Writing if (isCold = true) inside a condition compiles (it's a legal assignment expression) but silently does the wrong thing — it assigns true to isCold and the condition is always true, regardless of what isCold was before.
For Loops: Three Parts, One Line
A for loop bundles the three steps of a loop — initialize, test, update — into one header:
for (int i = 0; i < sensors.length; i++)
{
if (sensors[i].isFaulty())
{
report(sensors[i]);
}
}
The three parts are always separated by semicolons, in this order: initialize the loop variable, test it, update it. Starting at 0 pairs naturally with <; starting at 1 pairs naturally with <= — pick whichever matches how many times you actually want to run.
Common Pitfalls
- Missing curly braces. Without them, only the very next line is actually part of the
if/loop body — everything after it runs unconditionally, every time. =instead of==in a condition. A real, silent bug — the code compiles and the condition is always true.- Off-by-one in a for loop's bound.
i < sensors.lengthvisits every valid index;i <= sensors.lengthruns one iteration too many and reads past the end.
Key Takeaways
- An
ifruns its body only when its condition is true; anelsegives it a second branch for when it's false. - Always use curly braces around a conditional or loop body.
==tests equality;=assigns. Confusing them compiles but silently breaks the logic.- A
forloop's header has three parts — initialize, test, update — always in that order, separated by semicolons.
Deck context: mechacoder-test/src/lessons/java-1.js, slide 5 ("CONTROL STRUCTURES")