开关表达式:为什么 Java 认为我的 break - String 行不是语句?

Switch expressions: Why does Java consider my break - String lines not to be statements?

试图理解 switch 表达式并得出以下代码。事实上,对于所有“break - String”组合,我都会收到“not a statement”错误。我做错了什么?

String i = switch(value) {
            case 0:
                break "Value is 0";
            case 1:
                break "Value is 1";
            case 2:
                break "Value is 2";
            default:
                break "Unknown value";
        };

对于 JDK < 13

    String i;
    switch(value) {
        case 0:
            i = "Value is 0";
            break;
        case 1:
            i = "Value is 1";
            break;
        case 2:
            i = "Value is 2";
            break;
        default:
            i = "Unknown";
    };

对于 JDK > 13:

String i = switch(value) {
    case 0 -> "Value is 0";
    case 1 -> "Value is 1";
    case 2 -> "Value is 2";
    default -> "Unknown";
};

您的示例 - 是 sitch 语句和表达式的组合:)

正确使用的关键字是 yield 到 return 开关表达式中的值:它是作为 JDK 13 中的增强功能引入的。或者,由于您的表达式都很简单,您可以使用 shorthand 箭头符号:

String i = switch(value) {
    case 0 -> "Value is 0";
    case 1 -> "Value is 1";
    case 2 -> "Value is 2";
    default -> "Unknown value";
};