“开关”是否已关闭? Java中的语句只适用于整数?
Possible Duplicate:
Switch Statement With Strings in Java?
Does the "switch" statement in Java only work with integers ?
Can't I write something like this instead ?
switch(string)
case "hello": ...
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
此答案仅对 Java 6 或更早版本有效! Java 7 中添加了字符串切换
14.11 switch 语句
通常,当您需要打开字符串值时,通常可以通过使用 char(因为字符串只有一个字符长)或枚举来解决此限制。在你的情况下,枚举看起来更有可能。
This answer is only valid for Java 6 or earlier! Switching on strings has been added in Java 7
14.11 The switch Statement
Usually, when you need to switch on a string value, you can often work around this limitation by using char (as the string is only ever going to be one character long) or an enum. In your case, enum looks more likely.
是的。直到java 6,还没有使用字符串。
虽然你可以用 ENUMS 来解决这个问题,比如:
对于我们人类来说更容易阅读,对吧?
源是 http://download.oracle.com/javase/tutorial/java /javaOO/enum.html
Yes. Until java 6, not with Strings.
Tough you can do a workaround with ENUMS, something like:
more easy to read for us humans, right?
source is http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
实际上,根据 Java SE 7 中的 Oracle,您可以将字符串与 switch 语句一起使用
http://download.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
}
Actually, according to Oracle in Java SE 7 you can use strings with the switch statement
http://download.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
}
switch 语句不能与字符串一起使用。在错误列表下......
“不要屏住呼吸”
https:// bugs.java.com/bugdatabase/view_bug?bug_id=1223179
尽管在查看另一个答案中发布的即将发布的文档后,我认为该功能在 JDK7 中可用。
The switch statement cannot work with strings. Under the bug listing....
"Don't hold your breath"
https://bugs.java.com/bugdatabase/view_bug?bug_id=1223179
although after looking at the upcoming docs posted in another answer, I suppose this feature is available in JDK7.
Java 的教程说它适用于基本类型(byte、short、char、int)以及字符串。请参阅 http://download.oracle.com/javase/tutorial/java/ nutsandbolts/switch.html
Java's tutorial says it works with primitive types (byte, short, char, int) as well as strings. See http://download.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
在 java 7 中,您可以将 switch 与字符串一起使用。请查看此处
with java 7 you can use switch with strings. look here