决定使用if-then-else语句还是switch语句取决于可读性和语句正在测试的表达式。语句可以基于if-then-else值或条件的范围测试表达式,而switch语句仅基于单个整数、枚举值或String对象测试表达式。
例如,可以使用switch语句编写以下代码。
int month = ...; // any month if (month == 1) { System.out.println("January"); } else if (month == 2) { System.out.println("February"); } ... // and so on
另一方面,以下不能用switch语句编写,因为switch语句不支持类型标签boolean。
int temperature = ...; // any temperature if (temperature < 0) { System.out.println("Water is ice"); } else if (temperature < 100){ System.out.println("Water is liquid, known as water"); } else { System.out.println("Water is vapor"); }