在Java 7及更早版本中,switch语句仅支持基本数据类型(如int、char、byte和short)以及枚举类型。对于字符串,你需要使用if-else语句进行比较。
从Java 8开始,switch语句支持字符串类型。这是一个简单的示例:
public class SwitchStringExample {
public static void main(String[] args) {
String input = "hello";
switch (input) {
case "hello":
System.out.println("Hello!");
break;
case "world":
System.out.println("World!");
break;
default:
System.out.println("Unknown input.");
break;
}
}
}
在这个示例中,我们使用switch语句来比较字符串input。如果input等于"hello",则输出"Hello!“;如果等于"world”,则输出"World!“;否则,输出"Unknown input.”。