简体   繁体   中英

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

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

switch (orderType) {
        case 1: 
            statement 1;
            break;
       case 2:
            statement 2;
            break;
       case 3:
             **call case 1;**
             **Call case 2;**
             break;
       default:
            break;`
}

Can we do that in Java?

No, you can't jump to the code snippet in another switch case. You can however extract the code into an own method that can be called from another case:

switch (orderType) {
    case 1: 
        someMethod1();
        break;
    case 2:
        someMethod2();
        break;
    case 3:
        someMethod1();
        someMethod2();
        break;
    default:
        break;
}

void someMethod1() { ... }
void someMethod2() { ... }

Although you cannot influence the switch cases directly, you can call switch's parent method from one case and pass different arguments. For example,

void foo(int param1, String param2, ...) {
    switch (param1) {
        case 0:
            foo(1, "some string");
            break;

        case 1:
            //do something
            break;

        default:
            break;
    }
}

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

As others have pointed out, you can implement your switch cases inside a method which takes a parameter, which corresponds to the desired switch case. These switch cases can recursively call the same method, with the desired switch cases. Here is a fully-working example which allows you to check if a year is a leap year, or not:

public class LeapYear {

    static int year = 2016;

    public static void main(String[] args) {

        leapSwitch(1);

    }

    public static void leapSwitch(int switchcase) {

        switch (switchcase) {

        case 1: {
            if (year % 4 == 0) {
                leapSwitch(2);
            } else {
                leapSwitch(5);
            }
        }
            break;

        case 2: {
            if (year % 100 == 0) {
                leapSwitch(3);

            } else {
                leapSwitch(4);
            }
        }
            break;

        case 3: {
            if (year % 400 == 0) {
                leapSwitch(4);

            } else {
                leapSwitch(5);
            }
        }
            break;

        case 4: {
            System.out.println(year+ " is a leap year!");
        }
            break;

        case 5: {
            System.out.println("Not a leap year...");
        }
            break;

        }
    }
}

Using methods is the best way to do it as mentioned in the accepted answer but for some reasons if you are unable to create method, Here is one more way to do this without using methods

boolean isBreakTheLoop = false, isCase2Required = false;
while(!isBreakTheLoop){
    switch (orderType) {
       case 1: 
            statement 1;
            if(isCase2Required){
               orderType = 2;
               break;
            }
            isBreakTheLoop = true;
            break;
       case 2:
            statement 2;
            isBreakTheLoop = true;
            break;
       case 3:
            orderType = 1;
            isCase2Required = true;
            break;
       default:
            isBreakTheLoop = true;
            break;
    }
}

Just a reminder: while the most suggested case is the best solution, note that if you don't close with a brake; your case: , it will continue executing in the next case.

Then, while it's still best pratice to break your cases, you could still adopt a solution similar to the following:

switch (orderType) {
    case 3:
        someMethod1();
    case 2:
        someMethod2();
        break;
    case 1: 
        someMethod1();
        break;
    default:
        break;
}

Note that "avoiding breaks" solution can't completely cover OP necessities, because writing:

    case 3:
    case 1:
        someMethod1();
    case 2:
        someMethod2();
    default:
        break;

or:

    case 3:
    case 1:
        someMethod1();
        break;
    case 2:
        someMethod2();
        break;
    default:
        break;

would make case: 3 be the same than case: 1 , making them execute both methods in first code, or a single method in the second code.

If this situation is a case of needing to execute all cases up to the parameter (say you have 5 cases, but case 2 needs 1 and 2 to execute, case 3 needs 1 and 2 and 3 to execute, etc.), I have a potential solution. I created a switch statement nested within a for loop like so:

for (int i = 1; i <= orderType; i++) {
    switch (i) {
    case 1:
        statement1;
        break;
    case 2:
        statement2;
        break;
    case 3:
        statement3;
        break;
    default:
        break;
    }
}

This will cause each statement leading up to the valid case to execute. Not exactly the best for efficiency, but could help with a small number of cases or simple executions.

You can use this trick in some case :

switch (orderType) {
   case 3: 
        statement 3;
   case 2:
        statement 2;
   case 1:
        statement 1;
        break;
   default:
        break;`

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM