😀

if / switch(文・式)を理解するbreak忘れ・default忘れ・yield忘れまで全部やる

に公開

1.実行用ディレクトリ構成
control-samples/
├── Main.java
├── IfSample.java
├── IfElseSample.java
├── IfElseIfSample.java
├── SwitchStmtSample.java
├── SwitchMissingBreakSample.java
├── SwitchMissingDefaultSample.java
├── SwitchExprSample.java
├── SwitchExprMissingDefaultSample.java
└── SwitchExprMissingYieldSample.java

2.実行環境

public class Main {
    public static void main(String[] args) {
        //if文の分岐
        IfSample.run();
        IfElseSample.run();
        IfElseIfSample.run();

        //switch文
        SwitchStmtSample.run();
        SwitchMissingBreakSample.run();
        SwitchMissingDefaultSample.run();

        //
        SwitchExprSample.run();
        // これはコンパイルエラー例なので、試したい時だけ有効化
        SwitchExprMissingDefaultSample.run();

        // これはコンパイルエラー例なので、試したい時だけ有効化
        SwitchExprMissingYieldSample.run();
    }
}

3.if文:基本3パターン
3.1 if(trueのときだけ実行)

public class IfSample {
    public static void run() {
        System.out.println("=== IfSample ===");
        int x = 10;
        if (x > 5) {
            System.out.println("5よりも大きいです。");
        }
    }
}

3.2 if-else(どちらか必ず実行)

public class IfElseIfSample {
    public static void run() {
        System.out.println("=== IfElseIfSample ===");
        int score = 85;

        if (score >= 90) System.out.println("A");
        else if (score >= 80) System.out.println("B");
        else System.out.println("C");
    }
}

3.3 if-else if-else(上から順に判定)

public class IfElseIfSample {
    public static void run() {
        System.out.println("=== IfElseIfSample ===");
        int score = 85;

        if (score >= 90) System.out.println("A");
        else if (score >= 80) System.out.println("B");
        else System.out.println("C");
    }
}

ポイント:
•上から順に評価される
•一度trueになったら 下は見ない

4.switch文(statement):処理を分岐する
4.1 switch文(基本)

public class SwitchStmtSample {
    public static void run() {
        System.out.println("=== SwitchStmtSample ===");
        int n = 2;

        switch (n) {
            case 1:
                System.out.println("one");
                break;
            case 2:
                System.out.println("two");
                break;
            default:
                System.out.println("other");
        }
    }
}
ABC

ポイント:
• reakがないと 下に落ちて全部実行される(fall-through)

4.3 default無し(一致しなければ何も起きない)

public class SwitchMissingDefaultSample {

    public static void run(){
        System.out.println("=== SwitchMissingDefaultSample ===");
        int n = 3;
        switch (n) {
            case 1:
                System.out.println("one");
                break;
        }
            System.out.println("(no output from switch)");
        }
    }

ポイント
• switch文は defaultがなくてもコンパイルOK
• case に一致しないなら 何もしないで抜ける

5.switch式(expression):値を返す
switch式は「値を返す」ので、String result = ... のように代入できます。

5.1 switch式(正常系)

public class SwitchExprSample {
    public static void run() {
        System.out.println("=== SwitchExprSample ===");
        int n = 2;

        String result = switch (n) {
            case 1 -> "one";
            case 2 -> {
                System.out.println("two selected");
                yield "two";
            }
            default -> "other";
        };

        System.out.println("result=" + result);
    }
}

ポイント:
• switch式は 値を返す
• {} ブロックにしたら yield が必要

public class SwitchExprMissingDefaultSample {
    public static void run() {
        int n = 3;

        String result = switch (n) {
            case 2 -> "two";
        };

        System.out.println(result);
    }
}

ポイント:
• switch式は すべてのパターンで値を返す必要がある
• default無しはコンパイルエラーになりがち

5.2 yield忘れ(ブロックは必ず値を返す必要がある)

public class SwitchExprMissingYieldSample {
    public static void run() {
        System.out.println("=== SwitchExprMissingYieldSample ===");
        int n = 2;

        String result = switch (n) {
            case 1 -> "one";
            case 2 -> {
                System.out.println("two selected");
                // yield がない!
            }
            default -> "other";
        };

        System.out.println(result);
    }
}

エラー例:
• switch expression must yield a value...

ポイント:
• {} ブロックのcaseは yieldかthrowが必須
• printlnを書いても 値を返していないのでアウト

項目 switch文 switch式
目的 処理を分岐 値を作る
値を返す ×
break 必要(忘れるとfall-through) 不要
default 任意 原則必須
yield 不要 ブロックで必須

Discussion