流程控制语句if-else、switch

流程控制语句

流程指程序执行的先后顺序

1. 顺序结构

public static void main(String[] args)
	{
		System.out.println(1);
		System.out.println(2);
		System.out.println(3);
	}

2. 判断 if语句

if(关系表达式最终得到布尔值即可) {
语句体;
}

public static void main(String[] args)
	{
		System.out.println("去网吧");
		int age = 16;
		if(age >= 18){
		System.out.println("可以进入");          //判断语句,满足则执行,不满足直接跳到最后
	}
		System.out.println("未满18周岁离开");
	}

3. if-else 语句

if(关系表达式最终得到布尔值即可) {
语句体1;
}else{
语句体2;
}
适用于2选1的情况

public static void main(String[] args)      实例判断基偶
	{
	int num = 13;
	if(num % 2 == 0){             //使用取模能除尽为偶数,否则为基数
		System.out.println("偶数");          
	}else{
		System.out.println("基数");
	}

4. if-else 复合语句

if(判断条件1) {
执行语句体1;
}else if (判断条件2){
执行语句体2;
}

}else if (判断条件n ) {
执行语句n;
}else{
执行语句n+1;
}
适用于多选1的情况

public static void main(String[] args)      实例判断基偶
	{
	int x = 13;
	int y = ;
	if (x >= 3){             //假设x为4 条件成立,
		y = 2 * x + 1;		//结果为 9
	} else if (-1 < x && x < 3){ 		//假设x为2 条件成立,
		y = 2 *x;						//结果为 4
	}else{						//假设x为-1与上述条件均不成立,直接跳转最后一步
		y = 2 * x - 1;			//结果为 -3
	}
	System.out.println("结果是" + y)}

练习

public static void main(String[] args) 
	int score = 98;
if(score >= 90 && <=100){      //90<变量<100
	System.out.println("优秀");
}else if (score >= 80 && <=90){		//80<变量<90
	System.out.println("好");	
}else if (score >= 70 && <=80){		//70<变量<80
	System.out.println("良");	
}else if (score >= 0 && <=70){		//0<变量<70
	System.out.println("不及格");
}else{
	System.out.println("数据错");   //超出条件判断外的数字为不合理
}

5. Switch 语句

代码格式:

 switch(表达式){
	case 常量值1:
		语句体;
		break;
	case 常量值2:
		语句体2;
		break;
	...
	default:
		语句体n+1;
		break;
}

案例:
满足匹配哪个case 就向下执行

public static void main(String[] args) 
	int num = 1;
	switch (num){
		case 1;						//case 后为常量
			System.out.println("星期一"); 
			break;
		case 2;
			System.out.println("星期二"); 
			break;
		case 3;
			System.out.println("星期三"); 
			break;
		default:					//类似于else
			System.out.println("数据错");   //超出条件判断外的数字为不合理
			break;
}

tips: case 后数值不可相同

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值