一.三种循环简介及比较
1.do{代码}while(条件)
与while的区别:先执行一次循环体再判断条件
循环嵌套:循环里边嵌套循环
示例代码:
1
2
3
4
5
6
7
8
9import java.util.Scanner; public class DoubleWhile{ public static void main(String[] args){ int appleCount = 1; do{ System.out.println("吃了第"+appleCount+"个苹果"); appleCount++; }while(appleCount<10); }
2.for循环:
for(初始化变量;循环条件;变量改变){
循环体
}
for循环与while循环对比:
优点:结构紧凑,可读性强
缺点:结构固定,灵活性差
适合:固定循环次数,且循环变量递增或者递减的循环类型
示例代码
1
2
3
4
5
6public class ForStu{ public static void main(String[] args){ for(int i = 1;i < 6;i++){ System.out.println("吃了第"+i+"个苹果"); } }
3. while:判断一段代码是否继续(循环)执行
while(判断条件){代码}
考虑循环的步骤:
1.确认循环的条件
2.确认循环变量
3.具体化循环条件
4.写循环体
5.循环变量改变(向着不满足条件的方向改变)
示例代码
1
2
3
4
5
6
7
8public class WhileStu{ public static void main(String[] args){ int appleCount = 1; while(appleCount < 6){ System.out.println("吃了第"+appleCount+"个苹果"); appleCount++; } }
二.switch与if对比:
适合处理:等值判断,值不连续
switch:根据变量值判断执行分支
switch(变量){
case 字面值:代码;
break;
case 字面值:代码;
.
.
.
default:代码;
}
1.switch支持的类型:int型,枚举类型,jdk1.7之后支持String
2.switch的下穿:遇到break之前一直往下执行
示例代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25import java.util.Scanner; public class SwitchStu{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("请输入0~2的阿拉伯数字"); int number = sc.nextInt(); //String ch = "0"; String s; switch(number){ case 0: s = "零"; //break; case 1: s = "壹"; //break; case 2: s = "贰"; break; default: s = "暂不支持"; } System.out.println(s); } }
三.跳出循环或者判断的两个关键字
break:跳出当前循环
continue:跳过本次循环,继续下一次循环
一.默认作用与关键字所在的循环
二.可以给循环起别名,指定作用于哪一个循环
示例代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19public class BreakAndContinue{ public static void main(String[] args){ for(int i = 1;i < 6;i++){ if(i==3){ break; } System.out.println("吃了第"+i+"个苹果"); } //做零件 out:for(int s = 1;s < 4;s++){ for(int p = 1;p < 6;p++){ if(p==3){ break out; } System.out.println("第"+s+"个员工做了第"+p+"个零件"); } } } }
最后
以上就是微笑紫菜最近收集整理的关于DAY3:循环,switch判断的全部内容,更多相关DAY3:循环内容请搜索靠谱客的其他文章。
发表评论 取消回复