Control Structures

Making Decisions with if/else

Control structures help your program make decisions and repeat actions based on conditions.

If/Else Statements:

int batteryLevel = 75;

if (batteryLevel > 80) {
    System.out.println("Battery level is good");
} else if (batteryLevel > 50) {
    System.out.println("Battery level is okay");
} else if (batteryLevel > 20) {
    System.out.println("Battery level is low");
} else {
    System.out.println("Battery critically low!");
}

Comparison Operators:

Common Operators:

  • == - Equal to
  • != - Not equal to
  • > - Greater than
  • < - Less than
  • >= - Greater than or equal
  • <= - Less than or equal

Loops - For Loop:

// For loop - when you know how many times to repeat
for (int i = 1; i <= 5; i++) {
    System.out.println("Count: " + i);
}

// For loop with arrays
int[] motorPowers = {50, 75, 100, 25};
for (int i = 0; i < motorPowers.length; i++) {
    System.out.println("Motor " + i + " power: " + motorPowers[i]);
}

Loops - While Loop:

// While loop - repeat based on a condition
int attempts = 0;
boolean sensorDetected = false;

while (!sensorDetected && attempts < 10) {
    sensorDetected = checkSensor();
    attempts++;
    System.out.println("Attempt " + attempts);
}

Logical Operators:

Combining Conditions:

  • && - AND (both conditions must be true)
  • || - OR (at least one condition must be true)
  • ! - NOT (reverses the condition)

Examples:

// AND example
if (batteryLevel > 20 && motorTemperature < 80) {
    robot.startDriving();
}

// OR example  
if (gamepad1.a || gamepad1.b) {
    robot.activateClaw();
}

Try It Yourself:

Exercise 1: Control Flow

  • An if/else chain that sets motor speed based on distance to target
  • A for loop that checks multiple sensors
  • A while loop that runs until a button is pressed
  • Combine conditions using logical operators
Write control structures for robot behavior:

Open full interactive app