Does the “switch” statement in Java only work with integers?
Possible Duplicate:
Switch Statement With Strings in Java?
Java中的"Twitter"语句只与整数一起工作吗?
我不能改写这样的东西吗?
开关(串)案例"你好":…
谢谢
此答案仅适用于Java 6或更早的版本!在Java 7中添加了切换字符串。
14.11开关声明
The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, or an enum type (§8.9), or a compile-time error occurs.
通常,当需要打开一个字符串值时,通常可以使用char(因为字符串只有一个字符长)或枚举来绕过这个限制。在您的例子中,枚举看起来更像。
对。直到Java 6,而不是使用字符串。很难用Enums来解决问题,比如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } switch (day) { case MONDAY: System.out.println("Mondays are bad."); break; case FRIDAY: System.out.println("Fridays are better."); break; case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); break; default: System.out.println("Midweek days are so-so."); break; } |
对我们人类来说更容易阅读,对吧?
源代码是http://download.oracle.com/javase/tutorial/java/javaoo/enum.html
实际上,根据JavaSE 7中的Oracle,可以使用带有转换语句的字符串。
http://download.oracle.com/javase/tutorial/java/nutsandbolts/switch.html(下载.oracle.com/javase/tutorial/java/nutsandbolts/switch.html)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | public class StringSwitchDemo { public static int getMonthNumber(String month) { int monthNumber = 0; if (month == null) { return monthNumber; } switch (month.toLowerCase()) { case"january": monthNumber = 1; break; case"february": monthNumber = 2; break; case"march": monthNumber = 3; break; case"april": monthNumber = 4; break; case"may": monthNumber = 5; break; case"june": monthNumber = 6; break; case"july": monthNumber = 7; break; case"august": monthNumber = 8; break; case"september": monthNumber = 9; break; case"october": monthNumber = 10; break; case"november": monthNumber = 11; break; case"december": monthNumber = 12; break; default: monthNumber = 0; break; } return monthNumber; } public static void main(String[] args) { String month ="August"; int returnedMonthNumber = StringSwitchDemo.getMonthNumber(month); if (returnedMonthNumber == 0) { System.out.println("Invalid month"); } else { System.out.println(returnedMonthNumber); } } |
}
使用Java 7,可以使用带有字符串的开关。看这里
Java的教程称它与原始类型(字节、短、char、int)以及字符串一起工作。请参阅http://download.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
switch语句不能用于字符串。在错误列表下….
"别屏住呼吸"
http://bugs.sun.com/bugdatabase/view_bug.do?BugSyID=1223179
尽管在查看了另一个答案中发布的即将发布的文档之后,我想这个特性在JDK7中是可用的。