Java Switch Expression

来自WHY42
Riguz留言 | 贡献2023年9月25日 (一) 05:22的版本 (Created page with "<syntaxhighlight lang="java"> public class Test { public static void main(String[] args) { System.out.println(countryName("CN")); System.out.println(countryName("EN")); System.out.println(countryName("US")); System.out.println(countryName("XX")); } private static String countryName(String shortName) { return switch(shortName) { case "CN" -> "China"; case "EN" -> "English"; case "US"...")
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
public class Test {
    public static void main(String[] args) {
        System.out.println(countryName("CN"));
        System.out.println(countryName("EN"));
        System.out.println(countryName("US"));
        System.out.println(countryName("XX"));
    }

    private static String countryName(String shortName) {
        return switch(shortName) {
            case "CN" -> "China";
            case "EN" -> "English";
            case "US" -> {
                yield "United States";
            }
            default -> "Unknown";
        };
    }
}

Output:

China
English
United States
Unknown