Branch structures in Cava

更新时间:
复制 MD 格式

Cava supports three forms of the if branch structure: if, if...else, and if...else if...else. Switch branch structures are not supported — use if...else if...else to handle multiple conditions instead.

if statement

Use an if statement to run a block of code when a single condition is true. If the condition is false, the block is skipped.

Syntax:

if (condition) { // condition is a Boolean expression.
    // Code to run if condition is true
}

Sample code:

class Example {
    static int main() {
        int a = 1;
        int b = 2;
        if (a < b) {
            a = b;
        }
        return a;
    }
}

if...else statement

Use an if...else statement to run different code depending on whether a condition is true or false.

Syntax:

if (condition) { // condition is a Boolean expression.
    // Code to run if condition is true
} else {
    // Code to run if condition is false
}

Sample code:

class Example {
    static int main() {
        int a = 1;
        int b = 2;
        if (a < b) {
            a = b * 10;
        } else {
            a = b * 20;
        }
        return a;
    }
}

if...else if...else statement

Use an if...else if...else statement to check multiple conditions in sequence. Cava evaluates each condition from top to bottom and executes only the first branch whose condition is true. All remaining branches are skipped.

Note the following rules:

  • At most one else branch is allowed, and it must appear after all else if branches.

  • Multiple else if branches are allowed, and they must all appear before the else branch.

Syntax:

if (condition1) { // condition1 is a Boolean expression.
    // Code to run if condition1 is true
} else if (condition2) {
    // Code to run if condition2 is true
} else {
    // Code to run if both condition1 and condition2 are false
}

Sample code:

class Example {
    static int main() {
        int a = 2;
        if (a == b) {
            a = 10;
        } else if (a == 2) {
            a = 20;
        } else if (a == 3) {
            a = 30;
        } else {
            a = 40;
        }
        return a;
    }
}