Can we call a “case” inside another case in the same switch statement in Java?

后端 未结 5 1556
傲寒
傲寒 2021-01-04 10:28

My intention is to call two cases inside another case in the same switch statement,

switch (orderType) {
        case 1: 
            statement 1;
                   


        
5条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-04 10:48

    You can't just call a another case block like this. What you could do, though, is wrap each of these blocks in a method, and reuse them:

    private void doSomething() {
        // implementation
    }
    
    private void doSomethingElse() {
        // implementation
    }
    
    private void runSwitch(int order) {
    
        switch (orderType) {
               case 1: 
                    doSomething();
                    break;
               case 2:
                    doSomethingElse();
                    break;
               case 3:
                    doSomething();
                    doSomethingElse();
                    break;
               default:
                    break;
        }
    }
    

提交回复
热议问题