Why can't I use switch statement on a String?

前端 未结 16 2065
面向向阳花
面向向阳花 2020-11-21 07:57

Is this functionality going to be put into a later Java version?

Can someone explain why I can\'t do this, as in, the technical way Java\'s switch state

16条回答
  •  Happy的楠姐
    2020-11-21 08:20

    The following is a complete example based on JeeBee's post, using java enum's instead of using a custom method.

    Note that in Java SE 7 and later you can use a String object in the switch statement's expression instead.

    public class Main {
    
        /**
        * @param args the command line arguments
        */
        public static void main(String[] args) {
    
          String current = args[0];
          Days currentDay = Days.valueOf(current.toUpperCase());
    
          switch (currentDay) {
              case MONDAY:
              case TUESDAY:
              case WEDNESDAY:
                  System.out.println("boring");
                  break;
              case THURSDAY:
                  System.out.println("getting better");
              case FRIDAY:
              case SATURDAY:
              case SUNDAY:
                  System.out.println("much better");
                  break;
    
          }
      }
    
      public enum Days {
    
        MONDAY,
        TUESDAY,
        WEDNESDAY,
        THURSDAY,
        FRIDAY,
        SATURDAY,
        SUNDAY
      }
    }
    

提交回复
热议问题