switch 语句

if-thenif-then-else语句不同,switch语句可以具有许多可能的执行路径。 switch适用于byteshortcharint基本数据类型。它也适用于枚举类型(在Enum Types中讨论),String类以及一些包装某些基本类型的特殊类:CharacterByteShortInteger(在数字和字符串中讨论)。

以下代码示例SwitchDemo声明了一个名为monthint,其值表示一个月。该代码使用switch语句基于month的值显示月份的名称。

public class SwitchDemo {
    public static void main(String[] args) {

        int month = 8;
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
    }
}

在这种情况下,August被打印到标准输出。

switch语句的主体称为切换块。 switch块中的语句可以用一个或多个casedefault标签标记。 switch语句计算其表达式,然后执行匹配的case标签之后的所有语句。

您还可以使用if-then-else语句显示月份名称:

int month = 8;
if (month == 1) {
    System.out.println("January");
} else if (month == 2) {
    System.out.println("February");
}
...  // and so on

根据可读性和该语句正在测试的表达式来决定使用if-then-else语句还是switch语句。 if-then-else语句可以基于值或条件的范围来测试表达式,而switch语句只能基于单个整数,枚举值或String对象来测试表达式。

另一个景点是break语句。每个break语句终止封闭的switch语句。控制流 continueswitch块之后的第一条语句。 break语句是必需的,因为如果没有它们,则switch块中的语句会贯穿:匹配case标签之后的所有语句将按 Sequences 执行,而与后续case标签的表达式无关,直到遇到break语句为止。程序SwitchDemoFallThroughswitch块中显示掉落的语句。程序显示对应于整数month的月份以及该年份之后的月份:

public class SwitchDemoFallThrough {

    public static void main(String[] args) {
        java.util.ArrayList<String> futureMonths =
            new java.util.ArrayList<String>();

        int month = 8;

        switch (month) {
            case 1:  futureMonths.add("January");
            case 2:  futureMonths.add("February");
            case 3:  futureMonths.add("March");
            case 4:  futureMonths.add("April");
            case 5:  futureMonths.add("May");
            case 6:  futureMonths.add("June");
            case 7:  futureMonths.add("July");
            case 8:  futureMonths.add("August");
            case 9:  futureMonths.add("September");
            case 10: futureMonths.add("October");
            case 11: futureMonths.add("November");
            case 12: futureMonths.add("December");
                     break;
            default: break;
        }

        if (futureMonths.isEmpty()) {
            System.out.println("Invalid month number");
        } else {
            for (String monthName : futureMonths) {
               System.out.println(monthName);
            }
        }
    }
}

这是代码的输出:

August
September
October
November
December

从技术上讲,不需要最后的break,因为流不在switch语句之内。建议使用break,以便更轻松地修改代码,并且不易出错。 default部分处理case部分之一未明确处理的所有值。

以下代码示例SwitchDemo2展示了一个语句如何具有多个case标签。该代码示例计算特定月份中的天数:

class SwitchDemo2 {
    public static void main(String[] args) {

        int month = 2;
        int year = 2000;
        int numDays = 0;

        switch (month) {
            case 1: case 3: case 5:
            case 7: case 8: case 10:
            case 12:
                numDays = 31;
                break;
            case 4: case 6:
            case 9: case 11:
                numDays = 30;
                break;
            case 2:
                if (((year % 4 == 0) && 
                     !(year % 100 == 0))
                     || (year % 400 == 0))
                    numDays = 29;
                else
                    numDays = 28;
                break;
            default:
                System.out.println("Invalid month.");
                break;
        }
        System.out.println("Number of Days = "
                           + numDays);
    }
}

这是代码的输出:

Number of Days = 29

在 switch 语句中使用字符串

在 Java SE 7 和更高版本中,可以在switch语句的表达式中使用String对象。下面的代码示例StringSwitchDemo根据名为monthString的值显示月份数:

public class StringSwitchDemo {

    public static int getMonthNumber(String month) {

        int monthNumber = 0;

        if (month == null) {
            return monthNumber;
        }

        switch (month.toLowerCase()) {
            case "january":
                monthNumber = 1;
                break;
            case "february":
                monthNumber = 2;
                break;
            case "march":
                monthNumber = 3;
                break;
            case "april":
                monthNumber = 4;
                break;
            case "may":
                monthNumber = 5;
                break;
            case "june":
                monthNumber = 6;
                break;
            case "july":
                monthNumber = 7;
                break;
            case "august":
                monthNumber = 8;
                break;
            case "september":
                monthNumber = 9;
                break;
            case "october":
                monthNumber = 10;
                break;
            case "november":
                monthNumber = 11;
                break;
            case "december":
                monthNumber = 12;
                break;
            default: 
                monthNumber = 0;
                break;
        }

        return monthNumber;
    }

    public static void main(String[] args) {

        String month = "August";

        int returnedMonthNumber =
            StringSwitchDemo.getMonthNumber(month);

        if (returnedMonthNumber == 0) {
            System.out.println("Invalid month");
        } else {
            System.out.println(returnedMonthNumber);
        }
    }
}

此代码的输出为8

switch表达式中的String与与每个case标签关联的表达式进行比较,就好像正在使用String.equals方法一样。为了使StringSwitchDemo示例接受任何月份而不考虑大小写,将month转换为小写字母(使用toLowerCase方法),并且与case标签关联的所有字符串 均为小写字母。

注意 :此示例检查switch语句中的表达式是否为null。确保任何switch语句中的表达式都不为空,以防止引发NullPointerException