字符串作为 switch 语句
可能的重复:
Java 中带有字符串的 Switch 语句
我正在尝试在 String 上使用 switch 语句,但是它给出编译错误。如果有人建议我如何在 switch-case 语句中使用 String ,这将对我有帮助。
Possible Duplicate:
Switch Statement with Strings in Java
I am trying to use switch statement on String but it gives compilation error. If any one suggest me how to use String in switch-case statement , it will be helpful to me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您确实想使用 switch 语句,有一种方法。
创建一个包含 switch 语句案例的枚举类
,然后使用枚举切换到语句。
There is a way if you really really want to use switch statements.
Create an enum class which includes the switch statement cases
and then use the enum to switch to statements.
正如已经说过的,你不能。有关技术细节,您可以参考有关 的规范编译开关。在 Java SE 7 中,这个功能已经实现。有关使用 switch 的示例,请参阅此页面在 JDK 7 的
String
上。也许这个问题也可能有帮助。
As already said, you can't. For technical details you can refer to the specification about compiling switches. With Java SE 7, this functionality has been implemented. See this page for an example using switch on
String
with JDK 7.Maybe this question could be helpful too.
你不能。使用 if/else if/else if/else。除非你用的是Java7。关于这个重复问题的答案可以比我更好地解释它: https://stackoverflow.com/a/338230/3333
You can't. Use if/else if/else if/else. Unless you are on Java7. This answer on this duplicate question can explain it far better than I can: https://stackoverflow.com/a/338230/3333
你不能直接使用字符串,但你可以创建一个关键字符串数组,快速搜索它,然后打开索引,如下所示:
You cannot use strings directly, but you can make an array of key strings, quickly search it, and switch on the index, like this:
您不能在
switch
语句中使用String
,但可以使用Enum
类型。使用Enum
比使用String
甚至public static final int MY_CONSTANT
要好得多。您会在这里找到一个非常好的教程:Java Enum 类型教程
You can't use a
String
in aswitch
statement but you can use theEnum
type. Using anEnum
is much better than using aString
or even apublic static final int MY_CONSTANT
.You'll find a really good tutorial here: Java Enum type tutorial