HOWTO · Java

字串上的 Java switch 語句

本教程演示瞭如何在 Java 中對字串使用 switch 語句。

本頁內容

在 JDK 7 之前,不可能對字串使用 switch 語句,但後來,Java 新增了此功能。switch 語句用於針對值列表的變數相等,這些值稱為 cases

本教程演示瞭如何在 Java 中對字串使用 switch 語句。

在 Java 中對字串使用 switch 語句

在 JDK 7 之後,我們可以在 Java 中對字串使用 switch 語句,但必須考慮一些重要的點。

  1. switch 不能為空;否則,將丟擲 NullPointerException
  2. switch 語句根據大小寫敏感比較字串,這意味著大小寫中的字串和傳遞的字串必須是相同的大小寫字母。
  3. 如果處理的資料是字串,那麼 cases 中的值也應該是字串型別。

讓我們嘗試一個在 Java 中對字串使用 switch 語句的示例。

package delftstack;

import java.util.Scanner;
public class Switch_Strings {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);

    System.out.println("Hired Persons at Delftstack: Jack(CEO), John(ProjectManager),"
        + " Tina(HR), Maria(SeniorDeveloper), Mike(JuniorDeveloper), Shawn(Intern)");

    System.out.println("Enter the Position of Employee:  ");
    String Employee_Position = sc.next();

    switch (Employee_Position) {
      case "CEO":
        System.out.println("The Salary of Jack is $ 10000.");
        break;
      case "ProjectManager":
        System.out.println("The Salary of John is $ 8000.");
        break;
      case "HR":
        System.out.println("The Salary of Tina is $ 4000.");
        break;
      case "SeniorDeveloper":
        System.out.println("The Salary of Maria is $ 6000.");
        break;
      case "JuniorDeveloper":
        System.out.println("The Salary of Mike is $ 3000.");
        break;
      case "Intern":
        System.out.println("The Salary of Shawn is $ 1000.");
        break;
      default:
        System.out.println("Please enter the correct position of employee");
        break;
    }
  }
}

上面的程式碼使用字串上的 switch 語句通過檢查職位來列印帶有姓名的薪水。它將要求使用者輸入該位置。

輸出:

Hired Persons at Delftstack: Jack(CEO), John(ProjectManager), Tina(HR), Maria(SeniorDeveloper), Mike(JuniorDeveloper), Shawn(Intern)
Enter the Position of Employee:
ProjectManager
The Salary of John is $ 8000.