这个开关盒是否正确?

时间:2015-05-24 12:42:56

标签: java

public class SwitchTest {
    public static void main(String[] args) {
        System.out.println(“value = “ + switchIt(4));
    }
    public static int switchIt(int x) {
        int j = 1;
        switch (x) {
            case 1: j++;
            case 2: j++;
            case 3: j++;
            case 4: j++;
            case 5: j++;
            default: j++;
        }
        return j + x;
    }
}

为什么上面的代码打印8而不是6?

1 个答案:

答案 0 :(得分:4)

当你没有使用break时,它继续其他情况,首先j是1:

case 4: j++; // j became 2
case 5: j++; // j became 3
default: j++; // j became 4

如果您希望代码输出为6,则可以更改代码:

switch (x) {
    case 1: j++;
        break;
    case 2: j++;
        break;
    case 3: j++;
        break;
    case 4: j++;
        break;
    case 5: j++;
        break;
    default: j++;
}