前言

  • 这是课程的第三篇比较简单,语句篇结束,下一篇开始数组和方法相关的内容,故命名为数组和方法。
  • 以防有新读者所以我简述一下第一篇的前言。
  • 这个Java急速学习课程适合有一定编程基础的人。它通过实际的代码例子来教Java,减少了理论讲解,使学习过程更直观,帮助你更快地掌握Java的核心技能。课程内容经过优化,力求简洁明了。同时,课程鼓励大家交流心得,提出更好的解决方案,以此来不断改进课程内容。

包含的知识

  1. if判断语句

  2. switch判断语句

  3. while循环语句

  4. do…while循环语句

  5. for循环语句

  6. 认识break和continue语句的区别


具体代码

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package basic_0;

public class BasicZc4 {
public static void main(String[] args) {
System.out.println("============if判断语句===========");
test1();//认识if判断语句
System.out.println("==========switch判断语句=========");
test2();//认识switch判断语句
System.out.println("==========while循环语句==========");
test3();//认识while循环语句
System.out.println("========do...while循环语句=======");
test4();//认识do...while循环语句
System.out.println("===========for循环语句===========");
test5();//认识for循环语句
System.out.println("=======break和continue语句=======");
test6();//认识break和continue语句
}

//if语句
//可以嵌套switch
public static void test1() {
int age = 60;
if (age > 30) {
System.out.println("大于30");
} else if (age > 40) {
System.out.println("大于40");
} else if (age > 50) {
System.out.println("大于50");
}
if (age > 20) {
System.out.println("大于20");
}
System.out.println("ok");
}

//switch语句
//表达式类型支持byte、short、int、char,枚举,String、不支持double、float、long
//case给出的值不能重复,且只能是字面量,不能是变量
//使用switch的时候,不要忘记写break,否则会出现穿透现象(作用:通过穿透现象合并case代码块,减少重复代码的书写)
public static void test2() {
String week = "周三";
switch (week) {
case "周一":
System.out.println("修bug");
break;//不能跳过break,否则会穿透到下一条case
case "周二"://穿透性
case "周三":
case "周四":
System.out.println("寻求帮忙");
break;
case "周五":
System.out.println("放弃学习");
break;
case "周六":
case "周日":
System.out.println("打游戏");
break;
default://默认分支,可以不写,但是必须放在最后
System.out.println("星期信息有误!");
}
System.out.println("程序结束!");
}

//while循环语句
//条件判断必须为true,否则会死循环
//while循环语句可以嵌套
//while循环语句可以和for或do...while循环语句结合使用
public static void test3() {
int i = 0;
while (i < 10) {
System.out.println("i = " + i);
i++;
}
}

//do...while循环语句
//条件判断必须为true,否则会死循环
//do...while循环语句可以嵌套
//do...while循环语句可以和while或for循环语句结合使用
public static void test4() {
int i = 0;
do {
System.out.println("i = " + i);
i++;
} while (i < 10);
}

//for循环语句
//for循环语句可以嵌套
public static void test5() {
for (int i = 0; i < 10; i++) {
System.out.println("i = " + i);
}
}

//break和continue语句的区别
public static void test6() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;//跳出循环,不再执行循环体
}
System.out.println("i = " + i);
}
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue;//跳过循环体,直接执行下一次循环
}
System.out.println("i = " + i);
}
}
}