`
曹老英雄
  • 浏览: 4781 次
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

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

    博客分类:
  • JAVA
阅读更多

------- 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
6
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics