How to do a case with multiple conditions?

后端 未结 5 574
傲寒
傲寒 2020-12-29 21:57

In the 1 month experience I\'ve had with any programming language, I\'ve assumed that switch case conditions would accept anything in the parenthes

相关标签:
5条回答
  • 2020-12-29 22:28

    You can achieve an OR for cases like this:

    switch (someChsr) {
    case 'w':
    case 'W':
        // some code for 'w' or 'W'
        break;
    case 'x': // etc
    }
    

    Cases are like a "goto" and multiple gotos can share the same line to start execution.

    0 讨论(0)
  • 2020-12-29 22:28

    Every case is normally followed by a "break;" statement to indicate where execution should terminate. If you omit the "break;", then execution will continue. You can use this to support multiple cases which should be handled the same way:

    char someChar = 'w';
    {
    case 'W':
      // no break here
    case 'w': 
      System.out.println ("W or w");
      break;
    }
    
    0 讨论(0)
  • 2020-12-29 22:36

    You can do -

    switch(c) {
        case 'W':
        case 'w': //your code which will satisfy both cases
                  break;
    
        // ....
    }
    
    0 讨论(0)
  • 2020-12-29 22:39

    Switch cases are branches for alternative evaluations of a given expression. The expression is given in the switch parenthesis and can be byte, short, char, and int data types.

    The body of a switch statement is known as a switch block. A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label.

    http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

    0 讨论(0)
  • 2020-12-29 22:52

    For an alternate to switch statement(multiple if conditions), I think the best solution will be using an enum. For example: Consider the case below:-

        public enum EnumExample {
    
      OPTION1{
    
        public double execute() {
          Log.info(CLASS_NAME, "execute", "The is the first option.");
          return void;
        }
    
      },
      OPTION2{
    
        public double execute() {
          Log.info(CLASS_NAME, "execute", "The is the second option.");
          return void;
        }
    
      },
      OPTION3{
    
        public double execute() {
          Log.info(CLASS_NAME, "execute", "The is the third option.");
          return void;
    
      };
    
      public static final String CLASS_NAME = Indicator.class.getName();
    
      public abstract void execute();
    
    }
    

    The above enum can be used in the following fashion:

    EnumExample.OPTION1.execute();
    

    Hopefully this helps you guys.

    0 讨论(0)
提交回复
热议问题