JAVA总结之switch分支语句

java流程控制语句:顺序执行,条件和循环(循环即为for循环)。
其中我会详细介绍条件分支语句,if和switch。

switch分支语句

  1. if分支语句四种形式:单分支,双分支,多分支,嵌套if
//单分支
if(i>10){
	//执行语句块
	System.out.println(i);
}
//双分支
if(i>10){
	System.out.println("结果>10");
}
else{
	System.out.println(“结果<=10”);
}
//多分支
if(i<10){
	…………
}
else if(i==10){
	…………
}
else if(i>10){
	…………
}
//嵌套if(输出乘法口诀表)
if(int i=1;i<10;i++){
	if(int j=1;j<=i;j++){
		System.out.print(i+"*"+j+"="+i*j);
	}
	System.out.println();
}
  1. switch分支语句
public static void main(String[] args) {
        int week=2;//定义int型变量week
        switch(week){//定义switch语句的表达式为变量week,week类型只能是byte,short,int,枚举,String字符串,char
        case 1://定义case语句的常量为1
            System.out.println("星期一");//输出结果
            break;//结束
            //return;//return结束整个方法的执行,即后面的所有代码都不执行了
        case 2:
            System.out.println("星期二");
            break;//结束
        case 3:
            System.out.println("星期三");
            break;//结束
        default://default语句
            System.out.println("Sorry,I don't know");
        }
    }

注意:
(1)变量week取值类型只能是,byte,int,short,枚举,String字符串,char
(2)代码中的break,结束switch分支语句,switch外部代码依然执行。
(3)代码中的return,结束整个方法的执行,即后面的所有代码都不执行了
(4)return既可以表示返回值,又可以表示终止方法(单独使用的时候)。
(5)当不含有return和break在switch语句中时,程序会一直往下执行。

探讨switch条件分支中含有break,return几种情况

  1. 没有break和return
public class Song{
	public static void main(String []args){
		int i=1;
		switch(i){
			case 1:System.out.println("code1");
			case 2:System.out.println("code2");
			default:System.out.println("code3");
		}
		System.out.println("code4");
	}
}

输出结果:
在这里插入图片描述

  1. 含有break(break结束当前switch语句程序块的执行,不会影响语句块之外的代码,像下例中的code4会输出来;并且break只结束当前switch语句块程序的执行,即就近原则)
public class Song{
	public static void main(String []args){
		int i=1;
		switch(i){
			case 1:System.out.println("code1");break;
			case 2:System.out.println("code2");break;
			default:System.out.println("code3");
		}
		System.out.println("code4");
	}
}

输出结果:
在这里插入图片描述
3. 含有return(return结束所在方法的执行,满足case1之后输出结果就结束该方法体的执行了只输出了code1,所以code4没有输出来)

public class Song{
	public static void main(String []args){
		int i=1;
		switch(i){
			case 1:System.out.println("code1");return;
			case 2:System.out.println("code2");return;
			default:System.out.println("code3");
		}
		System.out.println("code4");
	}
}

输出结果:
在这里插入图片描述
通过以几个例子便可以清除的看出switch语句中break,return的作用和区别。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值