语句
1.switch语句
复制代码
1
2
3
4
5
6
7
8
9
10
11
12int a = 1,b =2; switch(a+b){ case 1: System.out.print(1); case 3: System.out.print(3); case 4: System.out.print(4); default: System.out.print(5); }
- 先执行 a+b 得出值 3
- 找到相对应case 3,然后继续向下执行
- 执行所有的语句,因为没有 break
345
复制代码
1
2
3
4
5
6
7
8
9
10
11
12int a = 2, b = 34; switch(a + b){ case 5: System.out.println(5); break; case 6: System.out.println(6); break; default: System.out.println(12); }
- 执行 a + b ,得出 36
- 执行 default
12
判断月份
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20Scanner a = new Scanner(System.in); System.out.print("please input a month:"); int month = a.nextInt(); switch(month){ case 1: case 2: case 3: System.out.println("Spring"); break; case 4: case 5: case 6: System.out.println("Summer"); break; case 7: case 8: case 9: System.out.println("Autumn"); break; case 10: case 11: case 12: System.out.println("Winter"); break; default: System.out.println("fasle"); }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28Scanner a = new Scanner(System.in); System.out.print("please input a month:"); int month = a.nextInt(); switch(month){ case 1: case 2: case 3: System.out.println("Spring"); break; case 4: case 5: case 6: System.out.println("Summer"); break; case 7: case 8: case 9: System.out.println("Autumn"); break; case 10: case 11: case 12: System.out.println("Winter"); break; default: System.out.println("fasle"); }
两个方式一样,但switch语句内,的多个语句,即语句块,并不需要加花括号,因为碰到break语句跳出,否则继续执行下去
2.循环语句
求1000以内的素数
复制代码
1
2
3
4
5
6
7
8
9int j; for (int i = 0; i < 1000; i++) { for (j = 2; j < i; j++) if (i % j == 0) break; if (j == i) System.out.println(i); }
2
3
5
…
当然上面犯了一个明显的错误,最外层的循环应该是<=1000,虽然并不影响什么,但要铭记。
复制代码
1
2
3
4
5
6
7
8
9
10
11for (int i = 0; i < 1000; i++) { if(i == 2) System.out.println(2); for (int j = 2; j < i; j++) { if(i % j == 0) break; if(j == i - 1 ) System.out.println(i); } }
金字塔
复制代码
1
2
3
4
5
6
7
8
9
10
11Scanner a = new Scanner(System.in); System.out.print("please input a number for high:"); int high = a.nextInt(); for(int i = 1; i < high + 1 ; i++){ for(int j = 0; j < high - i;j++) System.out.print(" "); for(int j = 0; j < 2*i-1 ;j++) System.out.print("*"); System.out.println(); }
最后
以上就是典雅蜜粉最近收集整理的关于JAVA学习笔记(2)switch语句、循环语句的全部内容,更多相关JAVA学习笔记(2)switch语句、循环语句内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复