字符串上的 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.