为什么我不能将其他 class 的常量添加到 java 的 switch 语句中?
Why can't I add constant of other class into a switch statement in java?
为什么我不能将其他 class 的常量添加到 java 的 switch 语句中?
示例:我有一个 class
public class Game {
static class GameMode {
public static final GameMode SURVIVAL = new GameMode();
public static final GameMode ADVENTURE = new GameMode();
public static final GameMode GOD = new GameMode();
}
GameMode CurrentMode = GameMode.GOD;
}
但是当我定义一个 switch 语句时,它给我一个错误:
void OnGame(){
switch (CurrentMode){
case GameMode.GOD: // case expressions must be constant expressionsJava(536871065)
System.out.println("Player On God Mode");
break;
case GameMode.SURVIVAL: // case expressions must be constant expressionsJava(536871065)
System.out.println("Player On Survival Mode");
break;
case GameMode.ADVENTURE: // case expressions must be constant expressionsJava(536871065)
System.out.println("Player On Adventure Mode");
break;
}
}
这让我很困惑。 SURVIVAL、ADVENTURE、GOD模式都是常量,我在前面加了“final”,为什么不能在switch语句中使用呢?
这是一些图片:
根据 Java Language Specification (JLS):
A case label has one or more case constants. Every case constant must be either a constant expression (§15.29) or the name of an enum constant (§8.9.1), or a compile-time error occurs.
你的情况显然不是 enum constant
,所以我猜你正在尝试使用 constant expression
但你的 GameMode
class 不符合 constant expression
.
A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following...
为什么我不能将其他 class 的常量添加到 java 的 switch 语句中?
示例:我有一个 class
public class Game {
static class GameMode {
public static final GameMode SURVIVAL = new GameMode();
public static final GameMode ADVENTURE = new GameMode();
public static final GameMode GOD = new GameMode();
}
GameMode CurrentMode = GameMode.GOD;
}
但是当我定义一个 switch 语句时,它给我一个错误:
void OnGame(){
switch (CurrentMode){
case GameMode.GOD: // case expressions must be constant expressionsJava(536871065)
System.out.println("Player On God Mode");
break;
case GameMode.SURVIVAL: // case expressions must be constant expressionsJava(536871065)
System.out.println("Player On Survival Mode");
break;
case GameMode.ADVENTURE: // case expressions must be constant expressionsJava(536871065)
System.out.println("Player On Adventure Mode");
break;
}
}
这让我很困惑。 SURVIVAL、ADVENTURE、GOD模式都是常量,我在前面加了“final”,为什么不能在switch语句中使用呢?
这是一些图片:
根据 Java Language Specification (JLS):
A case label has one or more case constants. Every case constant must be either a constant expression (§15.29) or the name of an enum constant (§8.9.1), or a compile-time error occurs.
你的情况显然不是 enum constant
,所以我猜你正在尝试使用 constant expression
但你的 GameMode
class 不符合 constant expression
.
A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following...