Does the "switch" statement in Java only work with integers? [duplicate]
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 ?
开发者_Go百科switch(string) case "hello": ...
thanks
This answer is only valid for Java 6 or earlier! Switching on strings has been added in Java 7
14.11 The switch Statement
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.
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.
Yes. Until java 6, not with Strings. Tough you can do a workaround with ENUMS, something like:
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;
}
more easy to read for us humans, right?
source is http://download.oracle.com/javase/tutorial/java/javaOO/enum.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
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);
}
}
}
The switch statement cannot work with strings. Under the bug listing....
"Don't hold your breath"
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=1223179
although after looking at the upcoming docs posted in another answer, I suppose this feature is available in JDK7.
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
with java 7 you can use switch with strings. look here
精彩评论