04.循环
# 01.if else
# 1、if else
package com.case_01;
public class Test{
public static void main(String args[]){
int x = 30;
int y = 10;
if( x == 30 ){
if( y == 10 ){
System.out.println("X = 30 and Y = 10");
}
if (y < 10) {
System.out.println("c");
} else if (y < 20) {
System.out.println("java");
} else {
System.out.println("python");
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 2、三元运算
package com.case_01;
public class Test{
public static void main(String args[]){
int time = 20;
String result = (time < 18) ? "学习python" : "学习java";
System.out.println(result); // 学习java
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 02.switch 语句
package com.case_01;
public class Test{
public static void main(String args[]){
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("没有匹配");
}
// 输出 "Thursday" (day = 4)
}
}
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
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
# 03.while 循环
# 1、简单循环
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
1
2
3
4
5
2
3
4
5
# 2、do while
do while
循环是while
循环的变体。- 在检查条件是否为
true
之前,此循环将执行一次代码块,然后只要条件为true
,它将重复该循环。
do {
// 要执行的代码块
}
while (condition);
1
2
3
4
2
3
4
public class Test{
public static void main(String args[]){
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 3、break
public class Test{
public static void main(String args[]){
int i = 0;
while(i <= 100) {
i++;
if (i > 30) {
System.out.println(i + "已经超过了30,不能在循环了");
break;
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 4、continue
public class Test{
public static void main(String args[]){
int i = 0;
while(i < 100){
i++;
if(i%10 == 0){
System.out.println();
continue;
}
System.out.print(i);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 04.for循环
# 1、for
- 此示例将只输出0到10之间的偶数:
for (int i = 0; i <= 10; i = i + 2) {
System.out.println(i);
}
1
2
3
2
3
# 2、for-each
- 以下示例使用for-each循环输出angs数组中的所有元素
public class Test{
public static void main(String args[]){
String[] langs = {"c", "java", "python", "cjavapy"};
for (String i : langs) {
System.out.println(i);
}
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 3、break
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
1
2
3
4
5
6
2
3
4
5
6
# 4、continue
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
1
2
3
4
5
6
2
3
4
5
6
上次更新: 2024/5/31 11:18:42