关于switch语句的一点介绍
2015-08-04 11:21
447 查看
switch语句是利用选择器的数值来选择符合条件的执行语句,选择器所产生的值必须为整数。一般char类型的数据会转换为整数(promote),string或者其他类型则不能执行这种功能,当然枚举类型可以解决这个问题。
switch语句中,每个case语句最有会有break,表示这条case执行到最后。若没有break,程序会一直执行下去直到遇到break为止(可以执行到下一条case中的语句)。
运行程序可以发现,autoSwitch1和autoSwitch2 分别用这两个方法会产生相同的结果,在autoSwitch2方法中,无论i为1或者2都会执行到“case 2:”下面的语句,switch语句的这种特性可以在编程中得到很多的方便 。
switch语句中,每个case语句最有会有break,表示这条case执行到最后。若没有break,程序会一直执行下去直到遇到break为止(可以执行到下一条case中的语句)。
public class TestSwitch { public void autoSwitch1(int i){ switch (i) { case 1: System.out.println("this is a number lower than 3"); break; case 2: System.out.println("this is a number lower than 3"); break; default: System.out.println("this encounter the other situation"); break; } } public void autoSwitch2(int i){ switch (i) { case 1: //System.out.println("this is a number lower than 3"); //break; case 2: System.out.println("this is a number lower than 3"); break; default: System.out.println("this encounter the other situation"); break; } } public static void main(String[] args) { TestSwitch t = new TestSwitch(); for (int i = 1; i < 4; i++) { //t.autoSwitch1(i); t.autoSwitch2(i); } } }
运行程序可以发现,autoSwitch1和autoSwitch2 分别用这两个方法会产生相同的结果,在autoSwitch2方法中,无论i为1或者2都会执行到“case 2:”下面的语句,switch语句的这种特性可以在编程中得到很多的方便 。
相关文章推荐
- PHP8新特性之match表达式
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树