Java中的Switch Case语句及其示例
当我们有许多选项(或多个选项),并且我们可能需要为每个选项执行不同的任务时,会使用Switch case语句。
Switch case语句的语法如下所示——
switch (variable or an integer expression) {case constant://Java code;case constant://Java code;default://Java code; }
A Simple Switch Case Example
public class SwitchCaseExample1 {public static void main(String args[]){int num=2;switch(num+2){case 1:System.out.println("Case1: Value is: "+num);case 2:System.out.println("Case2: Value is: "+num);case 3:System.out.println("Case3: Value is: "+num);default:System.out.println("Default: Value is: "+num);}}
}
说明:在switch中我给出了一个表达式,也可以给出变量。我给出了num+2,其中num值为2,相加后的表达式为4。由于没有定义值为4的情况,因此执行了默认情况。这就是为什么我们应该在switch的情况下使用default,这样,如果没有匹配条件的catch,就会执行默认块。
交换机案例中的Break语句
Break语句在switch情况下是可选的,但您几乎每次处理switch情况时都会使用它。在我们讨论break语句之前,让我们看看下面的示例,其中我没有使用break语句:
public class SwitchCaseExample2 {public static void main(String args[]){int i=2;switch(i){case 1:System.out.println("Case1 ");case 2:System.out.println("Case2 ");case 3:System.out.println("Case3 ");case 4:System.out.println("Case4 ");default:System.out.println("Default ");}}
}
Example with break statement
public class SwitchCaseExample2 {public static void main(String args[]){int i=2;switch(i){case 1:System.out.println("Case1 ");break;case 2:System.out.println("Case2 ");break;case 3:System.out.println("Case3 ");break;case 4:System.out.println("Case4 ");break;default:System.out.println("Default ");}}
}