บทนำ
ในบทความนี้ เราจะเรียนรู้วิธีการนำคำสั่ง switch มาใช้กับสตริง (String) นิพจน์ switch จะถูกประเมินค่าเพียงครั้งเดียว ค่าของนิพจน์จะถูกเปรียบเทียบกับค่าของแต่ละ case สตริงเป็นชนิดข้อมูลที่ประกอบด้วยตัวอักษรหนึ่งตัวขึ้นไป และล้อมรอบด้วยเครื่องหมายคำพูดคู่ (" ")
ตัวอย่างการทำงาน
อินพุทตัวอย่าง:
Input string: Java
เอาต์พุทที่คาดหวัง:
Using switch cases: We shall use Java for our coding
อัลกอริทึม
ขั้นตอนที่ 1 - เริ่มต้น ขั้นตอนที่ 2 - ประกาศสตริงชื่อ input_string ขั้นตอนที่ 3 - กำหนดค่า ขั้นตอนที่ 4 - กำหนดคำสั่ง switch เพื่อตรวจสอบสตริงอินพุทและพิมพ์ข้อความที่เกี่ยวข้อง ขั้นตอนที่ 5 - แสดงผลลัพธ์ ขั้นตอนที่ 6 - จบการทำงาน
ตัวอย่างที่ 1: เขียนในฟังก์ชัน main โดยตรง
public class Demo {
public static void main(String[] args) {
String input_string = "Java";
System.out.println("The string is defined as: " + input_string);
System.out.println("Using switch cases: ");
switch (input_string) {
case "Scala":
System.out.println("We shall use Scala for our coding");
break;
case "Python":
System.out.println("We shall use Python for our coding");
break;
case "Java":
System.out.println("We shall use Java for our coding");
break;
default:
System.out.println("The string is undefined");
}
}
}
เอาต์พุท
The string is defined as: Java Using switch cases: We shall use Java for our coding
ตัวอย่างที่ 2: ใช้เมธอดแยก (Object-Oriented Style)
public class Demo {
static void switch_case(String input_string) {
System.out.println("Using switch cases: ");
switch (input_string) {
case "Scala":
System.out.println("We shall use Scala for our coding");
break;
case "Python":
System.out.println("We shall use Python for our coding");
break;
case "Java":
System.out.println("We shall use Java for our coding");
break;
default:
System.out.println("The string is undefined");
}
}
public static void main(String[] args) {
String input_string = "Java";
System.out.println("The string is defined as: " + input_string);
switch_case(input_string);
}
}
เอาต์พุท
The string is defined as: Java Using switch cases: We shall use Java for our coding
หมายเหตุ: รองรับการใช้ String ใน switch ตั้งแต่ Java 7 ขึ้นไป