switch

switch语句根据switch (表达式)计算的结果,跳转到匹配的case结果,然后继续执行后续语句,直到遇到break结束执行

如果option的值没有匹配到任何case,例如option = 99,那么,switch语句不会执行任何语句。这时,可以给switch语句加一个default,当没有匹配到任何case时,执行default

public class Main {
    public static void main(String[] args) {
        int option = 99;
        switch (option) {
        case 1:
            System.out.println("Selected 1");
            break;
        case 2:
            System.out.println("Selected 2");
            break;
        case 3:
            System.out.println("Selected 3");
            break;
        default:
            System.out.println("Not selected");
            break;
        }
    }
}

注意case语句并没有花括号{}

如果有几个case语句执行的是同一组语句块,可以

public class Main {
    public static void main(String[] args) {
        int option = 2;
        switch (option) {
        case 1:
            System.out.println("Selected 1");
            break;
        case 2:
        case 3:
            System.out.println("Selected 2, 3");
            break;
        default:
            System.out.println("Not selected");
            break;
        }
    }
}

使用switch语句时,只要保证有breakcase的顺序不影响程序逻辑

switch (option) {
case 3:
    ...
    break;
case 2:
    ...
    break;
case 1:
    ...
    break;
}

switch语句还可以匹配字符串。字符串匹配时,是比较“内容相等”

public class Main {
    public static void main(String[] args) {
        String fruit = "apple";
        switch (fruit) {
        case "apple":
            System.out.println("Selected apple");
            break;
        case "pear":
            System.out.println("Selected pear");
            break;
        case "mango":
            System.out.println("Selected mango");
            break;
        default:
            System.out.println("No fruit selected");
            break;
        }
    }
}

switch语句还可以使用枚举类型

编译检查

使用IDE时,可以自动检查是否漏写了break语句和default语句,方法是打开IDE的编译检查

在Eclipse中,选择Preferences - Java - Compiler - Errors/Warnings - Potential programming problems,将以下检查标记为Warning

  • 'switch' is missing 'default' case
  • 'switch' case fall-through

在Idea中,选择Preferences - Editor - Inspections - Java - Control flow issues,将以下检查标记为Warning

  • Fallthrough in 'switch' statement
  • 'switch' statement without 'default' branch

switch语句存在问题时,即可在IDE中获得警告提示

switch表达式

使用switch时,如果遗漏了break,就会造成严重的逻辑错误,而且不易在源代码中发现错误。从Java 12开始,switch语句升级为更简洁的表达式语法,使用类似模式匹配(Pattern Matching)的方法,保证只有一种路径会被执行,并且不需要break语句:

public class Main {
    public static void main(String[] args) {
        String fruit = "apple";
        switch (fruit) {
        case "apple" -> System.out.println("Selected apple");
        case "pear" -> System.out.println("Selected pear");
        case "mango" -> {
            System.out.println("Selected mango");
            System.out.println("Good choice!");
        }
        default -> System.out.println("No fruit selected");
        }
    }
}

注意新语法使用->,如果有多条语句,需要用{}括起来。不要写break语句,因为新语法只会执行匹配的语句,没有穿透效应。

还可能用switch语句给某个变量赋值。例如:

int opt;
switch (fruit) {
case "apple":
    opt = 1;
    break;
case "pear":
case "mango":
    opt = 2;
    break;
default:
    opt = 0;
    break;
}

使用新的switch语法,不但不需要break,还可以直接返回值。把上面的代码改写如下:

public class Main {
    public static void main(String[] args) {
        String fruit = "apple";
        int opt = switch (fruit) {
            case "apple" -> 1;
            case "pear", "mango" -> 2;
            default -> 0;
        }; // 注意赋值语句要以;结束
        System.out.println("opt = " + opt);
    }
}

yield

大多数时候,在switch表达式内部,会返回简单的值

但是,如果需要复杂的语句,也可以写很多语句,放到{...}里,然后,用yield返回一个值作为switch语句的返回值:

public class Main {
    public static void main(String[] args) {
        String fruit = "orange";
        int opt = switch (fruit) {
            case "apple" -> 1;
            case "pear", "mango" -> 2;
            default -> {
                int code = fruit.hashCode();
                yield code; // switch语句返回值
            }
        };
        System.out.println("opt = " + opt);
    }
}

由于switch表达式是作为Java 13的预览特性(Preview Language Features)实现的,编译的时候,还需要给编译器加上参数

javac --source 13 --enable-preview Main.java

例:使用switch实现一个简单的石头、剪子、布游戏

import java.util.Scanner;

/**
 * switch实现石头/剪子/布并判断胜负
 */
public class Main {

    public static void main(String[] args) {
        int choice;
        int random;
        Scanner in = new Scanner(System.in);
        while (1 == 1) {
            System.out.println("please choice:");
            System.out.println(" 1: Rock");
            System.out.println(" 2: Scissors");
            System.out.println(" 3: Paper");
            choice = in.nextInt();
            random = (int) (1 + Math.random() * 3);
            System.out.println("You:" + choice + "    System:" + random);
            switch (choice) {
            case 1:
                if (random == 1)
                    System.out.println("Draw");
                if (random == 2)
                    System.out.println("Won");
                if (random == 3)
                    System.out.println("Failed");
                break;
            case 2:
                if (random == 2)
                    System.out.println("Draw");
                if (random == 3)
                    System.out.println("Won");
                if (random == 1)
                    System.out.println("Failed");
                break;
            case 3:
                if (random == 3)
                    System.out.println("Draw");
                if (random == 1)
                    System.out.println("Won");
                if (random == 2)
                    System.out.println("Failed");
                break;
            default:
                System.out.println("Wrong input");
                break;
            }
        }
    }

}
THE END
最后修改:2020 年 03 月 04 日 22 : 16
本文链接:https://www.j000e.com/%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6/switchmultipleselection.html
版权声明:本文『[switch多重选择][编译检查][新语法][yield]』为『Joe』原创。著作权归作者所有。
转载说明:[switch多重选择][编译检查][新语法][yield] || Joe's Blog』转载许可类型见文末右下角标识。允许规范转载时,转载文章需注明原文出处及地址。
Last modification:March 4, 2020
If you think my article is useful to you, please feel free to appreciate