Java流程控制可分为循环与分支,循环又可分为for;do whille;while do,分支又可分为if else 与 switch catch
1. for循环
for循环的语法格式:
for(1;2;3){
4
}
1:循环变量的初始化
2:循环的条件
3:循环之后的变化
4:循环执行的语句
for(1;2;3){
4
}
1:循环变量的初始化
2:循环的条件
3:循环之后的变化
4:循环执行的语句
执行步骤:1 2 4 3 2 4 3 2 4 3 2
注意通常 1 2 3 4 这四者之间是有一定关系的,但并不是说没有关系就是错的,比如
public class Test4For{
/*
public static void main(String[] args){
for(;;){//相当于 while(true)
System.out.println("trueOrFalse");
}
}
*/
/*
public static void main(String[] args){
for(System.out.print(1);check(2);System.out.print(3)){
System.out.print(4);
}
}
public static boolean check(int num){
System.out.print(num);
return true;
}
*/
/*
循环控制:
1.循环嵌套:一个循环定义在另一个循环里面
2.循环控制:
continue:表示跳过本次循环 开始下一次,跳到所在循环的第三部分
break:表示跳出循环 跳到所在循环的结束部分
3.循环标签
当我们在内层循环的时候 想要直接的操作外层循环
单个的一个continue/break只能操作所在的循环
这个时候 需要给外层循环贴标签 (标识符: a:)
然后再内层循环里面直接的continue/break a
*/
public static void main(String[] args){
a:for(int x = 6;x > 1;x--){
for(int y = 6;y > 0;y--){
if(x == 5 && y == 4){
continue;
}
if(x == 4 && y == 3){
break;
}
if(x == 2){
System.out.println("中断");
continue a;
}
System.out.println("XY=" + x + y);
}
}
}
}
2. do while 与 while do
do while:执行顺序1 4 3 2 4 3 2
1
do{
4;
3;
}while(2);
do{
4;
3;
}while(2);
while do:执行顺序 1 2 4 3 2 4 3
1
while(2){
4;
3;
}
do while
从这里我们可以很明显的看出,它们之间并无太大区别.do while会先执行后判断,保证至少执行一次,而while do 先判断,后执行
3. if else
if(boolean1){
执行语句1;
}else if(boolean2){
执行语句2;
}else if(boolean3){
执行语句3;
}
执行语句1;
}else if(boolean2){
执行语句2;
}else if(boolean3){
执行语句3;
}
注意:
3.1 if else 是具有排他特性的,简单地说就是当判断boolean2时,有一个隐含条件就是它一定
!boolean1的
3.2 当if else 只有一条语句需要执行的时候,可以省略大括号
3.3 在3.2的基础上,假如if else 有return的时候,可以省略else
3.4 当判断条件return true或false时,其实就是return 条件本身而已
4. switch case
switch(参数){
case XXX: System.out.println("xxx");break;
case YYY: System.out.println("yyy");break;
default:System.out.println("zzz");
}
case XXX: System.out.println("xxx");break;
case YYY: System.out.println("yyy");break;
default:System.out.println("zzz");
}
*:参数:
1.0 char byte short int
5.0 可以传枚举
7.0 可以传String
注意,
break
既有它有利的一面又有它不利的一面,假如是你本身需要使用它来共享代码,那么会大大提高你的效率,
但如果是由于个人疏忽,忘记使用它,又会带来很大的问题。
public class TestSC{
public static void main(String[] args){
//(假设1 2 月份是春天)利用break实现代码共享
printSeason(1);
//(假设 3 4 月份是春天)但是忘了break,会打印春冬,造成错误
printSeason(3);
}
public static void printSeason(int month){
switch(month){
case(1):
case(2):System.out.println("冬");break;
case(3):
case(4):System.out.println("春");
default:System.out.println("冬");
}
}
}