输出怎么可能是1002,为什么最后一个case不匹配却被执行?
public class Main {
public static void main(String[] args) {
int i=0,j=0;
switch (i) {
case 2 : j++;
default: j+=2;
case 15 : j+=1000;
}
System.out.println("j="+j);
}
}
最佳答案
失败:
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.
您的代码应该是:
case 2 : j++; break;
case 4: j+=10; break;
default: j+=2; break;
case 15: j+=1000;
}
public class Example{
public static void main(String[] args) {
java.util.ArrayList<String> futureMonths =
new java.util.ArrayList<String>();
int month = 8;
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December");
default: break;
}
if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}
}
}
This is the output from the code:
August
September
October
November
December
关于java - 为什么 switch 语句中的 "case"之后执行了错误的 "default",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16979940/