当前位置: 首页> 游戏> 攻略 > Java中的Switch Case语句及其示例

Java中的Switch Case语句及其示例

时间:2025/8/23 11:13:10来源:https://blog.csdn.net/Muhtar_/article/details/139829301 浏览次数:0次

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 ");}}
}

关键字:Java中的Switch Case语句及其示例

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: