break and switch appears to execute all case statements

前端 未结 4 1839
南笙
南笙 2020-12-21 02:45

In the latest stable release of Java and Eclipse (Kempler), entering the following code and executing it, assuming the package and class names exist:

package         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-21 03:12

    If a condition in a case block is true and there is no return or break, all the other case blocks will be executed regardless if the are true or not.

    For a rule of thumb always put a break or return at the end of a case block and you will be 90% right.

    switch (p) {
        case (1):
            x--;
            break;
        case (2):
            x = 2;
            break;
        case (3):
            x = 3;
            break;
        default:
            x++;
            break;
    }
    

提交回复
热议问题