我尝试使用这种格式作为 switch 语句,但在 Eclipse 中出现错误,但不知何故它在 IntelliJ 中没有抛出错误。需要改变什么?
public static void main(String[] args) {
// TODO Auto-generated method stub
int switchValue = 3;
switch(switchValue) {
case 1: System.out.println("Value was 1");
case 2: System.out.println("Value was 2");
case 3,4,5 ->
{
System.out.println("Value was 3");
}
default -> System.out.println("Was not 1,2,3,4 or 5");
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Mixing of different kinds of case statements '->' and ':' is not allowed within a switch
at keywords.Switchhh.main(Switchhh.java:12)
请注意,尽管根据
Eclipse
,您不能在同一个 switch 块中混合 case 语句类型,但您可以混合两种 switch 块类型,只要它们在代码中完全分开即可。 以下内容适用于Eclipse (Version: 2024-03 (4.31.0))
(尽管我想不出这样做的理由)。
switch (switchValue) {
case 1:
System.out.println("Value was 1");
break;
case 2:
System.out.println("Value was 2");
break;
default : {
switch (switchValue) {
case 1, 2, 3 -> System.out.println("Value was 3");
default -> System.out.println("Was not 1,2,3,4 or 5");
}
}
}
不同类型的 case 语句“->”和“:”的混合是不可以的 允许在开关内
就像错误状态一样,不要混用“:”和“->”
switch (switchValue) {
case 1 -> System.out.println("Value was 1");
case 2 -> System.out.println("Value was 2");
case 3, 4, 5 -> System.out.println("Value was 3");
default -> System.out.println("Was not 1,2,3,4 or 5");
}