黑马程序员--if、switch、for、while的理解

------- android培训java培训、期待与您交流! ----------

ifswitchforwhile的理解

       JAVA流程控制中,主要用到if-else语句和switch-case语句。If主要用于情况较少的时候,比如要么执行A,要么执行BSwitch适合多种情况的条件,且条件为精确值,适用于byteshortintchar、枚举类型,不适用条件语句,即变量不能为布尔类型。

 

public class Test {
	public static void main(String[] args) {
		int month = 4;
		if (month < 0 || month > 12) {
			System.out.println("错误");
		} else if (month >= 3 && month < 6) {
			System.out.println("Spring");
		} else if (month >= 6 && month < 9) {
			System.out.println("Summer");
		} else if (month >= 9 && month < 11) {
			System.out.println("Summer");
		} else {
			System.out.println("Winter");
		}
	}
}

 

public class Test {
	public static void main(String[] args) {
		int month = 4;
		String season;
		switch (month) {
		case 1:
			season = " Winter";
			break;
		case 2:
			season = " Winter";
			break;
		case 3:
			season = " Spring";
			break;
		case 4:
			season = " Spring";
			break;
		case 5:
			season = " Spring";
			break;
		case 6:
			season = "Summer";
			break;
		case 7:
			season = " Summer";
			break;
		case 8:
			season = " Summer";
			break;
		case 9:
			season = " Autumn";
			break;
		case 10:
			season = "Autumn";
			break;
		case 11:
			season = " Autumn";
			break;
		case 12:
			season = "Winter";
			break;
		default:
			season = "错误";
			break;
		}
		System.out.println(season);
	}
}
/* Switch(表达式),只能是整数(int,byte,char,short)表达式
case条件只能是整数(int byte ,char,short)常量,不能是变量及表达式
case条件的内容可以为空,如果为空,则继续执行之下代码 
fault表示如果没有满足case的条件的其他一切情况
别忘记写break,会出现穿透(一直执行接下来的代码,直到遇到break或者本代码块结束)
*/

 

Java循环控制中,常用forwhiledo...while 3种循环语句,这3种语句都可以用来处理同一问题,在一般情况下它们可以互相代替。但是在实际应用中,也有一些区别。
1while语句和do...while语句。

              int i = 0;

              while (i < 100) {

                     i++;

              }

 

              int i = 0;

              do{i++;}

              while (i < 100) ;

 

2while语句和for语句

int i = 0;

              while (i < 100) {

                     i++;

              }

 

              for (int i = 0; i < 100; i++) {

              }

 

 

3whilefor实现无限循环

 

              while (true) {}

              for (;;) {}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值