美文网首页
switch语句(2)

switch语句(2)

作者: 张轻舟 | 来源:发表于2018-04-22 15:36 被阅读18次

使用事例

1、int类型switch示例

int i = 1;
switch (i) {
case 1:
    System.out.println(1);
    break;
case 2:
    System.out.println(2);
    break;
case 3:
    System.out.println(3);
    break;
default:
    System.out.println(0);
}

2、Enum类型switch事例

public class SwitchEnum {
    static enum E {
        A, B, C, D
    }
    public static void main(String args[]) {
        E e = E.B;
        switch (e) {
        case A:
            System.out.println("A");
            break;
        case B:
            System.out.println("B");
            break;
        case C:
            System.out.println("C");
            break;
        case D:
            System.out.println("D");
            break;
        default:
            System.out.println(0);
        }
    }
}

3、String类型switch示例

public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
     String typeOfDay;
     switch (dayOfWeekArg) {
         case "Monday":
             typeOfDay = "Start of work week";
             break;
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
             typeOfDay = "Midweek";
             break;
         case "Friday":
             typeOfDay = "End of work week";
             break;
         case "Saturday":
         case "Sunday":
             typeOfDay = "Weekend";
             break;
         default:
             throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
     }
     return typeOfDay;
}

相关文章

网友评论

      本文标题:switch语句(2)

      本文链接:https://www.haomeiwen.com/subject/ollclftx.html