Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีกำหนด Switch Statement ใน JShell Java 9

JShell 基于 REPL (Read-Evaluate-Print-Loop) 在 Java 9 中引入。此工具可用于执行简单语句、评估并打印结果。

Switch 语句 可以测试多个条件,就像 else 子句 一样,并处理默认情况。Default 子句 在没有 case 匹配时执行,break 语句 用于在成功匹配后跳出 switch。

Snippet 1: Switch 不带 break (Fall-through)

jshell> int i = 10;
i ==> 10

jshell> switch(i) {
   ...> case 1 : System.out.println("1");
   ...> case 10 : System.out.println("10");
   ...> default : System.out.println("default");
   ...> }
10
default

jshell> int i = 1;
i ==> 1

jshell> switch(i) {
   ...> case 1 : System.out.println("1");
   ...> case 10 : System.out.println("10");
   ...> default : System.out.println("default");
   ...> }
1
10
default

Fall-through behavior: เมื่อไม่มี break จะรัน case ที่ match และ case ต่อไปจนถึง break หรือจบ switch

Snippet 2: Switch พร้อม break

jshell> switch(i) {
   ...> case 1 : System.out.println("1"); break;
   ...> case 10 : System.out.println("10"); break;
   ...> default : System.out.println("default"); break;
   ...> }
1

Java 12+ Switch Expressions (Preview)

ใน Java 12+ มี Switch Expressions ใหม่ (standard ใน Java 14):

jshell> int day = 3;
jshell> String dayName = switch (day) {
   ...>     case 1 -> "Monday";
   ...>     case 2 -> "Tuesday";
   ...>     case 3 -> "Wednesday";
   ...>     case 4 -> "Thursday";
   ...>     case 5 -> "Friday";
   ...>     case 6 -> "Saturday";
   ...>     case 7 -> "Sunday";
   ...>     default -> "Invalid day";
   ...> };
dayName ==> "Wednesday"

Switch Rules ใน JShell

  • Case values ต้องเป็น compile-time constants
  • ไม่สามารถมี duplicate case values ได้
  • Default case ไม่จำเป็น แต่แนะนำให้มี
  • Break optional - ถ้าไม่มีจะ fall-through
  • ใน JShell ใช้ ...> prompt สำหรับ multi-line input

เปรียบเทียบ Traditional vs Enhanced Switch

คุณสมบัติ Traditional Switch Switch Expression (Java 12+)
Syntax switch(x) { case: ... } switch(x) { case -> ... }
Return value ไม่ได้ (statement) ได้ (expression)
Fall-through Default behavior ไม่มี (ต้องใช้ yield)
Break required ต้องมีเพื่อหยุด ไม่ต้องมี
Multiple constants case 1: case 2: case 1, 2 ->