------- android培训、java培训、期待与您交流! ----------
if、switch、for、while的理解
在JAVA流程控制中,主要用到if-else语句和switch-case语句。If主要用于情况较少的时候,比如要么执行A,要么执行B;Switch适合多种情况的条件,且条件为精确值,适用于byte、short、int、char、枚举类型,不适用条件语句,即变量不能为布尔类型。
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循环控制中,常用for、while和do...while 3种循环语句,这3种语句都可以用来处理同一问题,在一般情况下它们可以互相代替。但是在实际应用中,也有一些区别。
(1)while语句和do...while语句。
int i = 0;
while (i < 100) {
i++;
}
int i = 0;
do{i++;}
while (i < 100) ;
(2)while语句和for语句
int i = 0;
while (i < 100) {
i++;
}
for (int i = 0; i < 100; i++) {
}
(3)while和for实现无限循环
while (true) {}
for (;;) {}