Java switch statement multiple cases

前端 未结 13 1123
后悔当初
后悔当初 2020-11-27 14:43

Just trying to figure out how to use many multiple cases for a Java switch statement. Here\'s an example of what I\'m trying to do:

switch (variable)
{
    c         


        
13条回答
  •  一向
    一向 (楼主)
    2020-11-27 14:48

    // Noncompliant Code Example

    switch (i) {
      case 1:
        doFirstThing();
        doSomething();
        break;
      case 2:
        doSomethingDifferent();
        break;
      case 3:  // Noncompliant; duplicates case 1's implementation
        doFirstThing();
        doSomething();
        break;
      default:
        doTheRest();
    }
    
    if (a >= 0 && a < 10) {
      doFirstThing();
    
      doTheThing();
    }
    else if (a >= 10 && a < 20) {
      doTheOtherThing();
    }
    else if (a >= 20 && a < 50) {
      doFirstThing();
      doTheThing();  // Noncompliant; duplicates first condition
    }
    else {
      doTheRest();
    }
    

    //Compliant Solution

    switch (i) {
      case 1:
      case 3:
        doFirstThing();
        doSomething();
        break;
      case 2:
        doSomethingDifferent();
        break;
      default:
        doTheRest();
    }
    
    if ((a >= 0 && a < 10) || (a >= 20 && a < 50)) {
      doFirstThing();
      doTheThing();
    }
    else if (a >= 10 && a < 20) {
      doTheOtherThing();
    }
    else {
      doTheRest();
    }
    

提交回复
热议问题