切换声明
switch 语句是 Java 的多路分支语句。它被用来代替长 if-else if-else 链,使它们更具可读性。但是,与 if 陈述不同,人们可能不会使用不等式; 必须具体定义每个值。
switch 语句有三个关键组件:
case:这是与switch语句的参数等价求值的值。default:如果case语句都没有评估为true,那么这是一个可选的,全能的表达式。- 突然完成
case声明; 通常break:这是为了防止对进一步的发言进行不期望的评估。
除了 continue 之外,可以使用任何会导致语句突然完成的语句 。这包括:
breakreturnthrow
在下面的示例中,典型的 switch 语句包含四种可能的情况,包括 default。
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
switch (i) {
case 0:
System.out.println("i is zero");
break;
case 1:
System.out.println("i is one");
break;
case 2:
System.out.println("i is two");
break;
default:
System.out.println("i is less than zero or greater than two");
}
通过省略 break 或任何突然完成的陈述,我们可以利用所谓的跌倒案例,该案例针对多个值进行评估。这可用于创建值成功的范围,但仍然不如不等式灵活。
Scanner scan = new Scanner(System.in);
int foo = scan.nextInt();
switch(foo) {
case 1:
System.out.println("I'm equal or greater than one");
case 2:
case 3:
System.out.println("I'm one, two, or three");
break;
default:
System.out.println("I'm not either one, two, or three");
}
在 foo == 1 的情况下,输出将是:
I'm equal or greater than one
I'm one, two, or three
在 foo == 3 的情况下,输出将是:
I'm one, two, or three
Version >= Java SE 5
switch 语句也可以与 enums 一起使用。
enum Option {
BLUE_PILL,
RED_PILL
}
public void takeOne(Option option) {
switch(option) {
case BLUE_PILL:
System.out.println("Story ends, wake up, believe whatever you want.");
break;
case RED_PILL:
System.out.println("I show you how deep the rabbit hole goes.");
break;
}
}
Version >= Java SE 7
switch 语句也可以与 Strings 一起使用。
public void rhymingGame(String phrase) {
switch (phrase) {
case "apples and pears":
System.out.println("Stairs");
break;
case "lorry":
System.out.println("truck");
break;
default:
System.out.println("Don't know any more");
}
}