1、switch多重选择:根据某个表达式的结果,分别去执行不同的分支。
格式:switch(表达式){
case 结果1:
执行语句1;
break;
case 结果2:
case 结果3:
执行语句2;
break;
……
case n:
执行语句n;
break;
default:
执行语句last;
break;
}
public classMain {public static voidmain(String[] args) {
System.out.println("欢迎来到游戏世界");
System.out.println("勇士,您想选择的游戏关卡是(1-4):");
Scanner scanner=newScanner(System.in);int res=scanner.nextInt();switch(res) {case 1:
System.out.print("来到新手报到处,要好好的积累经验哦!");break;case 2:
System.out.print("封釉山谷打怪记得捡装备呦");break;case 3:
System.out.print("疃栾大地需要团队合作才能战胜");break;/*若2、3 结果相同,可以写为:
case 2:
case 3:
System.out.print("疃栾大地需要团队合作才能战胜");
break;*/
default:
System.out.print("稀有怪等待勇士的搏斗");break;
}
}
}
2、switch语句还可以匹配字符串,字符串匹配时,是比较“内容相等”:
1 public classMain {2 public static voidmain(String[] args) {3 String fruit = "apple";4 switch(fruit) {5 case "apple":6 System.out.println("Selected apple");7 break;8 case "pear":9 System.out.println("Selected pear");10 break;11 case "mango":12 System.out.println("Selected mango");13 break;14 default:15 System.out.println("No fruit selected");16 break;17 }18 }19 }
switch语句还可以使用枚举类型,后面讲解。
3、JAVA新版
* switch表达式,遗漏了break会造成严重的逻辑问题,且不易发现,java12开始,该语句升级为更简洁的表达式语法,使用类似模式匹配的方法,不需要break语句,使用->,若有多条语句需要用{}括起来。
1 public classMain {2 public static voidmain(String[] args) {3 String fruit = "apple";4 switch(fruit) {5 case "apple" -> System.out.println("Selected apple");6 case "pear" -> System.out.println("Selected pear");7 case "mango" ->{8 System.out.println("Selected mango");9 System.out.println("Good choice!");10 }11 default -> System.out.println("No fruit selected");12 }13 }14 }
* yield: 用yield返回一个值作为switch语句的返回值
1 public classMain {2 public static voidmain(String[] args) {3 String fruit = "orange";4 int opt = switch(fruit) {5 case "apple" -> 1;6 case "pear", "mango" -> 2;7 default ->{8 int code =fruit.hashCode();9 yield code; //switch语句返回值
10 }11 };12 System.out.println("opt = " +opt);13 }14 }