Java 中的 Switch 语句在删除 "break;" 后显示奇怪的输出
Switch statement in Java displays weird output after removing "break;"
我已经创建了这段代码,但它的输出很奇怪。可能是因为我是 Java 的新手。我期望从此代码中输出 2 1 0
但是当我在所有 case
语句之后删除 break
语句时,这个奇怪的输出显示:2 1 2 0 1 2
谁能解释一下为什么会这样?这是我的代码:
public class Sem2 {
final static short x = 2;
public static void main(String [] args) {
for (int z=0; z < 3; z++)
{
switch (z)
{
case x: System.out.print("0 ");
case x-1: System.out.print("1 ");
case x-2: System.out.print("2 ");
}
}
}
}
没有break语句它也会继续执行其他语句。通过使用 break 它在匹配大小写后退出 switch case。
需要关键字 break
来跳出 switch 语句的每个 case。
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
...Each break statement terminates the enclosing switch statement.
Control flow continues with the first statement following the switch
block. The break statements are necessary because without them,
statements in switch blocks fall through: All statements after the
matching case label are executed in sequence, regardless of the
expression of subsequent case labels, until a break statement is
encountered
我已经创建了这段代码,但它的输出很奇怪。可能是因为我是 Java 的新手。我期望从此代码中输出 2 1 0
但是当我在所有 case
语句之后删除 break
语句时,这个奇怪的输出显示:2 1 2 0 1 2
谁能解释一下为什么会这样?这是我的代码:
public class Sem2 {
final static short x = 2;
public static void main(String [] args) {
for (int z=0; z < 3; z++)
{
switch (z)
{
case x: System.out.print("0 ");
case x-1: System.out.print("1 ");
case x-2: System.out.print("2 ");
}
}
}
}
没有break语句它也会继续执行其他语句。通过使用 break 它在匹配大小写后退出 switch case。
需要关键字 break
来跳出 switch 语句的每个 case。
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
...Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered