Java switch statement multiple cases

前端 未结 13 1160
后悔当初
后悔当初 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 15:10

    JEP 354: Switch Expressions (Preview) in JDK-13 and JEP 361: Switch Expressions (Standard) in JDK-14 will extend the switch statement so it can be used as an expression.

    Now you can:

    • directly assign variable from switch expression,
    • use new form of switch label (case L ->):

      The code to the right of a "case L ->" switch label is restricted to be an expression, a block, or (for convenience) a throw statement.

    • use multiple constants per case, separated by commas,
    • and also there are no more value breaks:

      To yield a value from a switch expression, the break with value statement is dropped in favor of a yield statement.

    Switch expression example:

    public class SwitchExpression {
    
      public static void main(String[] args) {
          int month = 9;
          int year = 2018;
          int numDays = switch (month) {
            case 1, 3, 5, 7, 8, 10, 12 -> 31;
            case 4, 6, 9, 11 -> 30;
            case 2 -> {
              if (java.time.Year.of(year).isLeap()) {
                System.out.println("Wow! It's leap year!");
                yield 29;
              } else {
                yield 28;
              }
            }
            default -> {
              System.out.println("Invalid month.");
              yield 0;
            }
          };
          System.out.println("Number of Days = " + numDays);
      }
    }
    
    

提交回复
热议问题