java用switch5级_JAVA05-switch多重选择

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 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值