使用字符串实现 switch 语句的 Java 程序
在这篇文章中,我们将了解如何使用字符串实现 switch 语句。switch 表达式只评估一次。该表达式的值将与每个 case 的值进行比较。字符串是一种包含一个或多个字符的数据类型,用双引号 (“ ”) 括起来。
以下是演示 -
假设我们的输入是 -
Input string: Java
期望的输出将是 -
Using siwtch cases: We shall use Java for our coding
算法
Step 1 - START Step 2 - Declare a string namely input_string. Step 3 - Define the values. Step 4 - Define a stwtch statement to check the input string and print the respective statements. Step 5 - Display the result Step 6 - Stop
示例 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 siwtch 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 siwtch cases: We shall use Java for our coding
示例 2
此处,我们将操作封装到函数中以展示面向对象的编程。
public class Demo { static void switch_case(String input_string){ System.out.println("Using siwtch 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 siwtch cases: We shall use Java for our coding
广告