📅  最后修改于: 2020-10-13 05:27:19             🧑  作者: Mango
在Java 7中,Java允许您在switch语句的表达式中使用字符串对象。为了使用字符串,您需要考虑以下几点:
传递字符串对象时要小心,将null对象的原因传递给NullPointerException。
public class StringInSwitchStatementExample {
public static void main(String[] args) {
String game = "Cricket";
switch(game){
case "Hockey":
System.out.println("Let's play Hockey");
break;
case "Cricket":
System.out.println("Let's play Cricket");
break;
case "Football":
System.out.println("Let's play Football");
}
}
}
输出:
Let's play Cricket
public class StringInSwitchStatementExample {
public static void main(String[] args) {
String game = "Card-Games";
switch(game){
case "Hockey": case"Cricket": case"Football":
System.out.println("This is a outdoor game");
break;
case "Chess": case"Card-Games": case"Puzzles": case"Indoor basketball":
System.out.println("This is a indoor game");
break;
default:
System.out.println("What game it is?");
}
}
}
输出:
This is a indoor game