在Java中,是否可以编写一个switch语句,其中每种情况都包含多个值?例如(尽管以下代码显然不起作用):
switch (num) {
case 1 .. 5:
System.out.println("testing case 1 to 5");
break;
case 6 .. 10:
System.out.println("testing case 6 to 10");
break;
}
我认为这可以在Objective C中完成,Java中是否有类似的东西?还是应该只使用
if
,else if
语句代替? 最佳答案
Java没有这种东西。为什么不仅仅执行以下操作?
public static boolean isBetween(int x, int lower, int upper) {
return lower <= x && x <= upper;
}
if (isBetween(num, 1, 5)) {
System.out.println("testing case 1 to 5");
} else if (isBetween(num, 6, 10)) {
System.out.println("testing case 6 to 10");
}