Switch语句没有显示正确的答案

时间:2014-12-03 03:29:49

标签: java switch-statement

出于某种原因,

int x = 5;
switch (x) {
    case 3 : x += 1;
    System.out.println(x);
    case 4 : x += 2;
    System.out.println(x);
    case 5 : x += 3;
    System.out.println(x);
    case 6 : x++;
    System.out.println(x);
    case 7 : x += 2;
    System.out.println(x);
    case 8 : x--;
    System.out.println(x);
    case 9 : x++;
    System.out.println(x);
}

(忽略SOP' s),这个开关语句的结果一直给我11,当我在纸上计算时,我一直得到10.我觉得它与增量有关,但是不能弄清楚它为什么显示11.我错过了什么吗?

2 个答案:

答案 0 :(得分:2)

我认为这很直接:

int x = 5;
    switch (x) {
    case 3 : x += 1;
    System.out.println(x);
    case 4 : x += 2;
    System.out.println(x);
    case 5 : x += 3;     /* found a match, so start here.  now x=8  */
    System.out.println(x);
    case 6 : x++;  /* no break statement, so now x=9  */
    System.out.println(x);
    case 7 : x += 2;  /* no break statement, so now x=11  */
    System.out.println(x);
    case 8 : x--;  /* no break statement, so now x=10  */
    System.out.println(x);
    case 9 : x++;  /* no break statement, so now x=11  */
    System.out.println(x);

    }

答案 1 :(得分:1)

由于您的交换机中没有break指令,因此会执行案例5-9X计算:

x = 5 + 3 + 1 + 2 -1 + 1 == 11