java基础学习笔记(四)—— 流程语句
A strong man can save himself,a great man can save another.
| @Author:TTODS
分支语句
分支语句使程序具有了判断能力
if 语句
String animal = "龙";
if(animal=="青蛙") {
System.out.println("奥!是青蛙!呱呱~");
}else if(animal=="小猫") {
System.out.println("奥!是小猫!喵喵~");
}else if(animal=="小狗") {
System.out.println("奥!是小狗!汪汪~");
}else {
System.out.println("??神秘生物?我还没见过呢!");
}
输出
??神秘生物?我还没见过呢!
switch语句
String animal = "小狗";
switch(animal) {
case "青蛙":
System.out.println("奥!是青蛙!呱呱~");
break;
case "小猫":
System.out.println("奥!是小猫!喵喵~");
break;
case "小狗":
System.out.println("奥!是小狗!汪汪~");
break;
default:
System.out.println("??神秘生物?我还没见过呢!");
}
输出
奥!是小狗!汪汪~
循环语句
循环语句可以让代码重复运行
while语句
输出区间[0,40)内的偶数
int i = 0;
while(i<40) {
if(i%2==0)
System.out.print(i+" ");
i++;
}
输出
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
do-while语句
输出区间[0,40)内的偶数
int i = 0;
do{
if(i%2==0)
System.out.print(i+" ");
i++;
}while(i<40)
输出
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
值得注意的是:do-while语句的判断条件在循环体的后面,就是说循环体至少会运行一遍,例如:
int i = 40;
do{
if(i%2==0)
System.out.print(i+" ");
i++;
}while(i<40);
输出
40
for语句
for(int i=0;i<40;i++) {
if(i%2==0)
System.out.print(i+" ");
}
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
for-each语句
String[] zoo = {"青蛙","小猫","小狗","恐龙","外星人"};
System.out.println("动物园里有什么?");
for(String animal : zoo) {
System.out.print(animal+" ");
}
输出
动物员里有什么?
青蛙 小猫 小狗 恐龙 外星人
跳转语句
跳转语句能够改变程序执行的顺序,可以实现程序的跳转。
break语句
九九乘法表
for(int i=1;i<10;i++) {
for(int j=1;j<10;j++) {
if(j>i) break;
System.out.printf("%d*%d=%2d ",j,i,i*j);
}
System.out.println();
}
输出
1*1= 1
1*2= 2 2*2= 4
1*3= 3 2*3= 6 3*3= 9
1*4= 4 2*4= 8 3*4=12 4*4=16
1*5= 5 2*5=10 3*5=15 4*5=20 5*5=25
1*6= 6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7= 7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8= 8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9= 9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
break的默认用法时跳出最近的内循环,如果在多重循环中想要跳出指定的循环层,可以使用break+label语句,如将上面代码改写成如下代码:
a: for(int i=1;i<10;i++) {
for(int j=1;j<10;j++) {
if(j>i) break a;
System.out.printf("%d*%d=%2d ",j,i,i*j);
}
System.out.println();
}
输出:
1*1= 1
break+label语句可以要程序直接跳出label指定的循环层;
continue语句
continue语句不同于break语句,continue语句用来结束本次循环,跳过循环体中尚未执行的语句,接着进行循环终止条件的判断,决定是否继续循环。对于for语句,在进行循环终止条件的判断前,还要先执行迭代语句(下例中的i++
)。
for(int i =0;i<=5;i++) {
if(i==3)
continue;
System.out.print(i+" ");
}
输出:
0 1 2 4 5
类似的,continue语句也有continue+label用法,通过下面两段代码对比,应该还是比较容易理解的。
continue:
for(int i=0;i<10;i++) {
for(int j=0;j<10;j++) {
if(j==4)
continue;
System.out.print(i);
}
System.out.println();
}
输出
000000000
111111111
222222222
333333333
444444444
555555555
666666666
777777777
888888888
999999999
continue+label
a: for(int i=0;i<10;i++) {
for(int j=0;j<10;j++) {
if(j==4)
continue a;
System.out.print(i);
}
System.out.println();
}
输出
0000111122223333444455556666777788889999