字符串上的 Java switch 语句
在 JDK 7 之前,不可能对字符串使用 switch
语句,但后来,Java 添加了此功能。switch
语句用于针对值列表的变量相等,这些值称为 cases
。
本教程演示了如何在 Java 中对字符串使用 switch
语句。
在 Java 中对字符串使用 switch
语句
在 JDK 7 之后,我们可以在 Java 中对字符串使用 switch
语句,但必须考虑一些重要的点。
- 值
switch
不能为空;否则,将抛出NullPointerException
。 -
switch
语句根据大小写敏感比较字符串,这意味着大小写中的字符串和传递的字符串必须是相同的大小写字母。 - 如果处理的数据是字符串,那么 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.
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。