为什么我可以将其他类的常数添加到Java中的Switch语句中?
为什么我不能将其他类的常数添加到Java中的Switch语句中?
示例:我有一个课程
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;
}
,但是当我定义一个开关语句时,它给了我一个错误:
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;
}
}
这让我感到困惑。生存,冒险和上帝模式都是恒定的,我在它面前添加了“最终”,为什么我不能在开关语句中使用它?
Why can't I add constant of other class into a switch statement in java?
example: I have a 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;
}
but when I define a switch statement, It give me an error:
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;
}
}
That makes me confused. SURVIVAL, ADVENTURE and GOD mode are all constant, I add "final" in front of it, why can't I use it in switch statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 java语言规范(jls):
您的情况显然不是
枚举常数
,所以我想您正在尝试使用常量表达式
但是您的gamemode
class class不限定为constant表达式
。According to Java Language Specification (JLS):
Your case is obviously not an
enum constant
, so I guess you are trying to use aconstant expression
but yourGameMode
class does not qualify as aconstant expression
.