默认块位于顶部的 switch 语句的行为

naz*_*art 3 java switch-statement

我发现了一种在 Java 中使用switch语句的有趣方法,但我无法捕获所有逻辑。

有人可以帮助深入了解所有细节吗?

这是代码:

private static int counter = 0;

public static Shape randomFactory() {

    int xVal = rand.nextInt(100);
    int yVal = rand.nextInt(100);
    int dim = rand.nextInt(100);

    switch (counter++ % 3) {
    default:
    case 0:
        return new Circle(xVal, yVal, dim);
    case 1:
        return new Square(xVal, yVal, dim);
    case 2:
        return new Line(xVal, yVal, dim);
    }
}
Run Code Online (Sandbox Code Playgroud)

一般来说我理解这个逻辑,

这里的确切含义是default

switch (counter++ % 3) {
        default:
Run Code Online (Sandbox Code Playgroud)

以及如何switch (counter++ % 3)查找等于大小写?这里没有任何brake介绍。

有什么建议么?

NPE*_*NPE 5

defaultswitch标记当表达式不匹配任何标签时将执行的块case。在您的示例中,default不包含break,因此它将失败并执行与 相同的代码case 0

case请注意,由于表达式的每个可能值都有一个标签switch,因此default实际上是一个无操作。