为什么在switch语句中的“default”之后执行错误的“case”

时间:2013-06-07 08:50:31

标签: java

输出怎么可能是1002,为什么最后一种情况会被执行,尽管不匹配?

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);
    }
}

5 个答案:

答案 0 :(得分:8)

下通

  

另一个兴趣点是break语句。每个休息声明   终止封闭的switch语句。控制流程继续   切换块后面的第一个语句。休息声明   是必要的,因为没有它们,开关块中的语句就会掉落   through:匹配的case标签之后的所有语句都在执行中   顺序,不管后续案例标签的表达,   直到遇到break语句。

您的代码应为:

  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

答案 1 :(得分:1)

您必须在案例块的末尾打破。否则所有后续案件也将被执行。

public class Main {
public static void main(String[] args) {
    System.out.println("Hello World!");
    int i=0,j=0;
    switch (i){
        case 2 : j++; break;
        case 4: j+=10; break;
        case 15 : j+=1000; break;
        default: j+=2;
    }
    System.out.println("j="+j);
}
}

答案 2 :(得分:0)

因为您缺少break;

如果我理解你的困惑,默认顺序无关紧要。在下面的情况下,

    int i=15,j=0;
    switch (i){
        case 2 : 
            j++;
            break;
        case 4: 
            j+=10;
            break;
        default: 
            j+=2;
            break;
        case 15 : 
            j+=1000;
            break;
    }

j即使1000之前default <{1}},其价值也会case 15

答案 3 :(得分:-1)

您没有在每个案例中指定'break'关键字。

应该是这样的:

switch (i){
    case 2 : 
    j++;
    break;
    case 4:
    j+=10;
    break;
    case 15 : 
    j+=1000;
    break;
    default: 
    j+=2;
    break;
}

答案 4 :(得分:-1)

在这种情况下,情况2和情况4不执行但默认情况和情况15是如此答案是1002.请为所需结果添加break语句。

希望这有帮助。

相关问题