If 表达式
- 语法
1
2
3if (condition) {
// block of code to be executed if the condition is true
} - 示例
1
2
3if (20 > 18) {
System.out.println("20 is greater than 18");
}Switch
- 语法
1
2
3
4
5
6
7
8
9
10switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
} - 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25int 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;
}
// Outputs "Thursday" (day 4)
While Loop
- 语法
1
2
3while (condition) {
// code block to be executed
} - 示例
1
2
3
4
5int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}Do/While Loop
- 语法
1
2
3
4do {
// code block to be executed
}
while (condition); - 示例
1
2
3
4
5
6int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);For Loop
- 语法
1
2
3for (statement 1; statement 2; statement 3) {
// code block to be executed
} - 示例
1
2
3for (int i = 0; i < 5; i++) {
System.out.println(i);
}For-Each Loop
- 语法
1
2
3for (type variableName : arrayName) {
// code block to be executed
} - 示例
1
2
3
4String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}Break
- break用来“跳出”一条switch语句。
- break语句还可以用于跳出 循环
1
2
3
4
5
6for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
Continue
continue如果出现指定条件,该语句将中断一次迭代(在循环中),并在循环中继续进行下一次迭代
1 | for (int i = 0; i < 10; i++) { |