2.1.1 if/else if Statements

Choose One Soccer Training Instruction

The Wildcats coach assigns one training instruction. In this simplified training rule, a player who has already taken three turns rests. Otherwise, a goalkeeper practices saves and any other player practices passing. Assume the turn count is nonnegative.

The examples are statements inside an existing method. The inputs are an integer named numberOfTurns and a Boolean named isGoalkeeper. A Boolean stores true or false; here it records whether the selected player is a goalkeeper. These statements select an instruction without changing the player.

Read an if/else if Chain
Select one instruction
string instruction;

if (numberOfTurns >= 3)
{
    instruction = "Rest this round";
}
else if (isGoalkeeper)
{
    instruction = "Practice saves";
}
else
{
    instruction = "Practice passing";
}
Follow the Checks in Order

With numberOfTurns equal to 3, the first condition is true. The program stores Rest this round and skips both later alternatives, even when isGoalkeeper is also true.

With 2 turns and isGoalkeeper equal to true, the first condition is false. The second condition is true, so the program stores Practice saves. With 2 turns and isGoalkeeper equal to false, both tests are false and the final branch stores Practice passing.

Check the Boundary and Priority
One instruction per player
Turns Goalkeeper Checks evaluated Selected instruction
2 true Turn limit, then goalkeeper Practice saves
2 false Turn limit, then goalkeeper Practice passing
3 true Turn limit only Rest this round
4 false Turn limit only Rest this round
Check Your Prediction