输出如何变成2?不明白
how does the output became 2? don't understand
public class Ex33 {
public static void main(String[] args) {
int x = 3, result = 4;
switch (x + 3) {
case 6: result = 0;
case 7: result = 1;
default: result += 1;
}
System.out.println(result);
}
}
不明白答案怎么变成2?
case
语句 "fall through" 没有 break
case 7: result = 1; // <-- no break, so
default: result += 1; // <-- happens after case 7
这是documented行为
Another point of interest is the break
statement. 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
由于在每种情况下都缺少 break;
,您的 case 语句会落空并且无法跳出循环。您所有的案例都被应用,因此导致 result = 2
.
格式正确的代码如下所示:
int x =3, result=4;
switch (x+4){
case 6:
result = 0;
break;
case 7:
result = 1;
break;
default:
result+=1;
}
System.out.println(result);
如果要停止执行其他 case 语句,则必须在每个 case
之后放置 break
语句。因此,将结果值设为 1 的等效代码是:
int x =3, result=4;
switch (x+4){
case 6: result = 0;
break;
case 7: result = 1;
break;
default: result+=1;
}
System.out.println(result);
阅读 switch 语句的一些重要规则 部分来自 here
匹配的case标签之后的所有语句都依次执行,不管后面的case标签的表达式如何,直到遇到break语句。
进行有效的中断操作!
public class Ex33 {
public static void main(String[] args) {
int x = 3, result = 4;
switch (x + 3) {
case 6: result = 0;
case 7: result = 1;
default: result += 1;
}
System.out.println(result);
}
}
不明白答案怎么变成2?
case
语句 "fall through" 没有 break
case 7: result = 1; // <-- no break, so
default: result += 1; // <-- happens after case 7
这是documented行为
Another point of interest is the
break
statement. Eachbreak
statement terminates the enclosingswitch
statement. Control flow continues with the first statement following theswitch
block. Thebreak
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
由于在每种情况下都缺少 break;
,您的 case 语句会落空并且无法跳出循环。您所有的案例都被应用,因此导致 result = 2
.
格式正确的代码如下所示:
int x =3, result=4;
switch (x+4){
case 6:
result = 0;
break;
case 7:
result = 1;
break;
default:
result+=1;
}
System.out.println(result);
如果要停止执行其他 case 语句,则必须在每个 case
之后放置 break
语句。因此,将结果值设为 1 的等效代码是:
int x =3, result=4;
switch (x+4){
case 6: result = 0;
break;
case 7: result = 1;
break;
default: result+=1;
}
System.out.println(result);
阅读 switch 语句的一些重要规则 部分来自 here
匹配的case标签之后的所有语句都依次执行,不管后面的case标签的表达式如何,直到遇到break语句。 进行有效的中断操作!