java - 为什么 switch 语句中的 "case"之后执行了错误的 "default"

标签 java

输出怎么可能是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;
}

FROM DOCS

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/

相关文章:

java - 返回一个范围以与 BigDecimal 进行比较

java - 单元测试和 UI 测试的模拟 final类

java - 删除某些项目后 ListView 刷新

java - Jasper 报告找不到包 net.sf.jasperreports.engine

java - 函数 Completable Future 上的 gradle 不兼容错误

java - 如何在 windows 下将 Ffmpeg 扩展嵌入到 Exoplayer 中?

java - MVC 井字游戏

java - 无法从 JTable 中的列获取正确的值

java - Hive - 运行 Java 代码时的依赖关系

java - servlet 和 JAX-RS 依赖项来自哪里?