JAVA · ОСНОВЫ · LESSON 08

Three ways

else if · about 16 minutes

Learning with progressRead the summary for free. To save the work, log in to the account.
STEP 1

More than two options.

When two choices are not enough, add else if between if and else. The program checks conditions from top to bottom.

int stars = 3;
if (stars >= 5) {
    System.out.println("Супер");
} else if (stars >= 3) {
    System.out.println("Хорошо");
} else {
    System.out.println("Ещё раз");
}

✦ For three stars, «Хорошо» will appear.

STEP 2

Order matters.

First ask about the high score, then the average. Java will select the first suitable branch.

int stars = 5;
if (stars >= 5) {
    System.out.println("Супер");
} else if (stars >= 3) {
    System.out.println("Хорошо");
} else {
    System.out.println("Ещё раз");
}

✦ After selecting one branch, the others are not executed.

IN-CLASS PRACTICE

Type the code yourself

Type an example manually. Check the signs and brackets.

public class Main {
    public static void main(String[] args) {
        int stars = 4;
        if (stars >= 5) {
            System.out.println("Супер");
        } else if (stars >= 3) {
            System.out.println("Хорошо");
        } else {
            System.out.println("Ещё раз");
        }
    }
}
Open the editor for class work
HOMEWORK

Solve it yourself

Create int score = 2. If score is at least 5, output «Отлично»; otherwise, if not less than 3, output «Хорошо»; otherwise, output «Тренируйся». Use if, else if and else.

The answer is hidden. Use similar examples from the lesson notes.

Opening up your homework