package com.example.demo; import org.junit.Test; public class SwitchTest { @Test public void Test01(){ int week = 6; // 计算结果 String memo = ""; switch (week){ case 1 -> memo = "休息日"; case 2,3,4,5,6 -> memo = "工作日"; case 7 -> memo = "星期六"; default -> throw new RuntimeException("无效的日期"); } System.out.println(memo); } @Test public void Test02(){ int week = 60; // 计算结果 String memo = switch (week){ case 1 : yield "休息日"; case 2,3,4,5,6 : yield "工作日"; case 7 : yield "星期六"; default : yield "无效的日期"; }; System.out.println(memo); } @Test public void Test03(){ int week = 1; String memo = switch (week){ case 1 -> { System.out.println("星期日"); yield "星期日"; } case 2,3,4,5,6 -> { System.out.println("工作日"); yield "工作日"; } case 7 -> { System.out.println("星期六"); yield "星期六"; } default -> { System.out.println("非法日期"); yield "非法日期"; } }; System.out.println("memo是"+memo); } }
package com.example.demo; import org.junit.Test; public class SwitchTest { @Test public void Test01(){ int week = 6; // 计算结果 String memo = ""; switch (week){ case 1 -> memo = "休息日"; case 2,3,4,5,6 -> memo = "工作日"; case 7 -> memo = "星期六"; default -> throw new RuntimeException("无效的日期"); } System.out.println(memo); } @Test public void Test02(){ int week = 60; // 计算结果 String memo = switch (week){ case 1 : yield "休息日"; case 2,3,4,5,6 : yield "工作日"; case 7 : yield "星期六"; default : yield "无效的日期"; }; System.out.println(memo); } @Test public void Test03(){ int week = 1; String memo = switch (week){ case 1 -> { System.out.println("星期日"); yield "星期日"; } case 2,3,4,5,6 -> { System.out.println("工作日"); yield "工作日"; } case 7 -> { System.out.println("星期六"); yield "星期六"; } default -> { System.out.println("非法日期"); yield "非法日期"; } }; System.out.println("memo是"+memo); } }
JAVA使用Switch-case的箭头函数代码块执行代码并用yield返回值------JAVA
于 2024-01-30 17:28:47 首次发布